<?php
// Get Free Estimate Wizard - Alpine.js powered 12-step form + summary
?>
<section class="bg-luxury-cream py-12">
  <div class="max-w-4xl mx-auto px-4">
    <?php $wizardPageTitle = $siteSettings['wizard_page_title'] ?? 'Get Free Estimate'; ?>
    <?php $wizardPageDescription = $siteSettings['wizard_page_description'] ?? 'Share your project details and receive a custom estimate from Balorp Ventures.'; ?>
    <div class="text-center mb-8">
      <h1 class="text-3xl md:text-4xl font-bold text-premium-charcoal"><?= htmlspecialchars($wizardPageTitle) ?></h1>
      <p class="text-base text-architectural-gray mt-2"><?= htmlspecialchars($wizardPageDescription) ?></p>
    </div>

    <form x-data="estimateWizard()" x-ref="form" x-on:submit.prevent="submit()" enctype="multipart/form-data" method="POST" action="<?= htmlspecialchars($baseUrl) ?>/wizard/submit" class="space-y-6">
      <?= CSRF::input() ?>

      <div class="bg-elegant-white rounded-lg p-5 shadow-sm">
        <div class="flex items-center justify-between mb-4">
          <div class="text-sm font-semibold text-architectural-gray">Step <span x-text="step"></span> of 12</div>
          <div class="text-sm font-semibold text-balorp-magenta" x-text="Math.round((step/12)*100) + '%'">0%</div>
        </div>
        <div class="w-full bg-soft-beige h-2 rounded-full overflow-hidden mb-4">
            <div class="h-2 bg-balorp-magenta rounded-full transition-all" :style="`width: ${(step/12)*100}%`"></div>
        </div>

        <div x-show="step === 1" x-cloak>
          <div class="space-y-4">
            <h2 class="text-xl font-bold text-premium-charcoal">Project Type</h2>
            <p class="text-sm text-architectural-gray">What best describes the work you need?</p>
            <div class="grid sm:grid-cols-2 gap-3 mt-3">
              <template x-for="opt in projectTypes" :key="opt">
                <label class="flex items-center gap-3 p-3 rounded-lg border border-soft-beige cursor-pointer" :class="{ 'ring-2 ring-balorp-magenta/30': formData.project_type === opt }">
                  <input type="radio" :value="opt" x-model="formData.project_type" name="project_type" class="h-4 w-4" required>
                  <span class="font-medium text-premium-charcoal" x-text="opt"></span>
                </label>
              </template>
            </div>
          </div>
        </div>

        <div x-show="step === 2" x-cloak>
          <div class="space-y-4">
            <h2 class="text-xl font-bold text-premium-charcoal">Property Type</h2>
            <div class="grid sm:grid-cols-2 gap-3 mt-3">
              <template x-for="opt in propertyTypes" :key="opt">
                <label class="flex items-center gap-3 p-3 rounded-lg border border-soft-beige cursor-pointer" :class="{ 'ring-2 ring-balorp-magenta/30': formData.property_type === opt }">
                  <input type="radio" :value="opt" x-model="formData.property_type" name="property_type" class="h-4 w-4" required>
                  <span class="font-medium text-premium-charcoal" x-text="opt"></span>
                </label>
              </template>
            </div>
          </div>
        </div>

        <div x-show="step === 3" x-cloak>
          <div class="space-y-4">
            <h2 class="text-xl font-bold text-premium-charcoal">Required Services</h2>
            <p class="text-sm text-architectural-gray">Select the services needed for your project.</p>
            <template x-for="category in serviceCategories" :key="category.label">
              <div class="rounded-2xl border border-soft-beige p-4">
                <h3 class="font-semibold mb-3 text-premium-charcoal" x-text="category.label"></h3>
                <div class="grid sm:grid-cols-2 gap-3">
                  <template x-for="opt in category.options" :key="opt">
                    <label class="flex items-start gap-3 p-3 rounded-lg border border-soft-beige cursor-pointer">
                      <input type="checkbox" :value="opt" x-model="formData.services" name="services[]" class="mt-1 h-4 w-4">
                      <span class="font-medium text-premium-charcoal" x-text="opt"></span>
                    </label>
                  </template>
                </div>
              </div>
            </template>
          </div>
        </div>

        <div x-show="step === 4" x-cloak>
          <div class="space-y-4">
            <h2 class="text-xl font-bold text-premium-charcoal">Project Location</h2>
            <p class="text-sm text-architectural-gray">Region · City/Town · Area / Landmark</p>
            <div class="grid sm:grid-cols-3 gap-3 mt-3">
              <input type="text" x-model="formData.region" name="region" placeholder="Region (e.g. Greater Accra)" class="rounded-lg border border-soft-beige px-3 py-2" required>
              <input type="text" x-model="formData.city" name="city" placeholder="City / Town (e.g. Accra)" class="rounded-lg border border-soft-beige px-3 py-2" required>
              <input type="text" x-model="formData.area" name="area" placeholder="Area / Landmark (e.g. East Legon)" class="rounded-lg border border-soft-beige px-3 py-2" required>
            </div>
          </div>
        </div>

        <div x-show="step === 5" x-cloak>
          <div class="space-y-4">
            <h2 class="text-xl font-bold text-premium-charcoal">Project Size</h2>
            <p class="text-sm text-architectural-gray">Choose a size range or enter an approximate floor area.</p>
            <div class="grid sm:grid-cols-2 gap-3 mt-3">
              <template x-for="opt in projectSizes" :key="opt">
                <label class="flex items-center gap-3 p-3 rounded-lg border border-soft-beige cursor-pointer" :class="{ 'ring-2 ring-balorp-magenta/30': formData.project_size === opt }">
                  <input type="radio" :value="opt" x-model="formData.project_size" name="project_size" class="h-4 w-4">
                  <span class="font-medium text-premium-charcoal" x-text="opt"></span>
                </label>
              </template>
            </div>
            <div class="mt-3">
              <label class="block text-sm font-medium text-premium-charcoal">Or enter approximate floor area (sqm)</label>
              <input type="text" x-model="formData.floor_area" name="floor_area" placeholder="e.g. 120" class="mt-2 w-full rounded-lg border border-soft-beige px-3 py-2">
            </div>
          </div>
        </div>

        <div x-show="step === 6" x-cloak>
          <div class="space-y-4">
            <h2 class="text-xl font-bold text-premium-charcoal">Project Stage</h2>
            <p class="text-sm text-architectural-gray">Which stage is your project currently at?</p>
            <div class="grid sm:grid-cols-2 gap-3 mt-3">
              <template x-for="opt in projectStages" :key="opt">
                <label class="flex items-center gap-3 p-3 rounded-lg border border-soft-beige cursor-pointer" :class="{ 'ring-2 ring-balorp-magenta/30': formData.project_stage === opt }">
                  <input type="radio" :value="opt" x-model="formData.project_stage" name="project_stage" class="h-4 w-4" required>
                  <span class="font-medium text-premium-charcoal" x-text="opt"></span>
                </label>
              </template>
            </div>
          </div>
        </div>

        <div x-show="step === 7" x-cloak>
          <div class="space-y-4">
            <h2 class="text-xl font-bold text-premium-charcoal">Timeline</h2>
            <p class="text-sm text-architectural-gray">When would you like the project to start?</p>
            <div class="grid sm:grid-cols-3 gap-3 mt-3">
              <template x-for="opt in timelineOptions" :key="opt">
                <label class="flex items-center gap-3 p-3 rounded-lg border border-soft-beige cursor-pointer" :class="{ 'ring-2 ring-balorp-magenta/30': formData.timeline_start === opt }">
                  <input type="radio" :value="opt" x-model="formData.timeline_start" name="timeline_start" class="h-4 w-4" required>
                  <span class="font-medium text-premium-charcoal" x-text="opt"></span>
                </label>
              </template>
            </div>
            <div class="grid sm:grid-cols-2 gap-3 mt-3">
              <div>
                <label class="block text-sm font-medium text-premium-charcoal">Expected Completion</label>
                <input type="date" x-model="formData.timeline_end" name="timeline_end" class="mt-2 w-full rounded-lg border border-soft-beige px-3 py-2" required>
              </div>
            </div>
          </div>
        </div>

        <div x-show="step === 8" x-cloak>
          <div class="space-y-4">
            <h2 class="text-xl font-bold text-premium-charcoal">Upload Files</h2>
            <p class="text-sm text-architectural-gray">Optional — upload photos, plans, or inspiration documents.</p>
            <div class="mt-3">
              <input type="file" x-ref="uploads" x-on:change="handleFiles" name="uploads[]" multiple accept="image/*,video/*,application/pdf" class="w-full" />
              <div class="mt-2 text-sm text-architectural-gray" x-text="filesCountText"></div>
            </div>
          </div>
        </div>

        <div x-show="step === 9" x-cloak>
          <div class="space-y-4">
            <h2 class="text-xl font-bold text-premium-charcoal">Site Visit Request</h2>
            <p class="text-sm text-architectural-gray">Would you like Balorp to visit your site?</p>
            <div class="grid sm:grid-cols-2 gap-3 mt-3">
              <label class="flex items-center gap-3 p-3 rounded-lg border border-soft-beige cursor-pointer" :class="{ 'ring-2 ring-balorp-magenta/30': formData.site_visit === 'Yes' }">
                <input type="radio" value="Yes" x-model="formData.site_visit" name="site_visit" class="h-4 w-4" required>
                <span class="font-medium text-premium-charcoal">Yes</span>
              </label>
              <label class="flex items-center gap-3 p-3 rounded-lg border border-soft-beige cursor-pointer" :class="{ 'ring-2 ring-balorp-magenta/30': formData.site_visit === 'No' }">
                <input type="radio" value="No" x-model="formData.site_visit" name="site_visit" class="h-4 w-4">
                <span class="font-medium text-premium-charcoal">No</span>
              </label>
            </div>
            <div x-show="formData.site_visit === 'Yes'" x-cloak class="grid sm:grid-cols-2 gap-3 mt-3">
              <div>
                <label class="block text-sm font-medium text-premium-charcoal">Preferred Date</label>
                <input type="date" x-model="formData.preferred_visit_date" name="preferred_visit_date" class="mt-2 w-full rounded-lg border border-soft-beige px-3 py-2">
              </div>
              <div>
                <label class="block text-sm font-medium text-premium-charcoal">Preferred Time</label>
                <select x-model="formData.preferred_visit_time" name="preferred_visit_time" class="mt-2 w-full rounded-lg border border-soft-beige px-3 py-2">
                  <option value="">Select a time</option>
                  <option>Morning</option>
                  <option>Afternoon</option>
                  <option>Evening</option>
                </select>
              </div>
            </div>
          </div>
        </div>

        <div x-show="step === 10" x-cloak>
          <div class="space-y-4">
            <h2 class="text-xl font-bold text-premium-charcoal">Contact Information</h2>
            <div class="grid sm:grid-cols-2 gap-3 mt-3">
              <input type="text" x-model="formData.full_name" name="full_name" placeholder="Full Name" class="rounded-lg border border-soft-beige px-3 py-2" required>
              <input type="tel" x-model="formData.phone" name="phone" placeholder="Phone Number" class="rounded-lg border border-soft-beige px-3 py-2" required>
            </div>
            <div class="grid sm:grid-cols-2 gap-3 mt-3">
              <input type="tel" x-model="formData.whatsapp" name="whatsapp" placeholder="WhatsApp Number" class="rounded-lg border border-soft-beige px-3 py-2">
              <input type="email" x-model="formData.email" name="email" placeholder="Email Address" class="rounded-lg border border-soft-beige px-3 py-2" required>
            </div>
            <div class="mt-3">
              <label class="block text-sm font-medium text-premium-charcoal">Preferred Contact Method</label>
              <select x-model="formData.preferred_contact" name="preferred_contact" class="mt-2 w-full rounded-lg border border-soft-beige px-3 py-2">
                <option value="Phone Call">Phone Call</option>
                <option value="WhatsApp">WhatsApp</option>
                <option value="Email">Email</option>
              </select>
            </div>
          </div>
        </div>

        <div x-show="step === 11" x-cloak>
          <div class="space-y-4">
            <h2 class="text-xl font-bold text-premium-charcoal">Additional Notes</h2>
            <p class="text-sm text-architectural-gray">Tell us more about your project.</p>
            <textarea x-model="formData.notes" name="notes" rows="5" class="mt-3 w-full rounded-lg border border-soft-beige px-3 py-2" placeholder="I want to repaint a 4-bedroom house and install POP ceilings in the living room."></textarea>
          </div>
        </div>

        <div x-show="step === 12" x-cloak>
          <div class="space-y-4">
            <h2 class="text-xl font-bold text-premium-charcoal">Review & Submit</h2>
            <div class="mt-3 bg-soft-beige p-4 rounded-lg text-sm text-premium-charcoal">
              <div class="mb-2"><strong>Project Type:</strong> <span x-text="formData.project_type || '—'"></span></div>
              <div class="mb-2"><strong>Property Type:</strong> <span x-text="formData.property_type || '—'"></span></div>
              <div class="mb-2"><strong>Services:</strong> <span x-text="formData.services.length ? formData.services.join(', ') : '—'"></span></div>
              <div class="mb-2"><strong>Location:</strong> <span x-text="(formData.area ? formData.area + ', ' : '') + formData.city + (formData.region ? ', ' + formData.region : '')"></span></div>
              <div class="mb-2"><strong>Project Size:</strong> <span x-text="formData.project_size || (formData.floor_area ? formData.floor_area + ' sqm' : '—')"></span></div>
              <div class="mb-2"><strong>Stage:</strong> <span x-text="formData.project_stage || '—'"></span></div>
                <div class="mb-2"><strong>Timeline:</strong> <span x-text="formData.timeline_start + (formData.timeline_end ? ' · ' + formData.timeline_end : '')"></span></div>
              <div class="mb-2"><strong>Site Visit Requested:</strong> <span x-text="formData.site_visit || '—'"></span></div>
              <div class="mb-2" x-show="formData.site_visit === 'Yes' && (formData.preferred_visit_date || formData.preferred_visit_time)"><strong>Visit Preference:</strong> <span x-text="(formData.preferred_visit_date ? formData.preferred_visit_date : '') + (formData.preferred_visit_time ? ' · ' + formData.preferred_visit_time : '')"></span></div>
              <div class="mb-2"><strong>Contact:</strong> <span x-text="formData.full_name + ' · ' + formData.phone + (formData.email ? ' · ' + formData.email : '')"></span></div>
              <div class="mb-2"><strong>Preferred Contact:</strong> <span x-text="formData.preferred_contact || '—'"></span></div>
              <div class="mb-2"><strong>Notes:</strong> <span x-text="formData.notes || '—'"></span></div>
              <div class="mb-2"><strong>Files Uploaded:</strong> <span x-text="filesCountText"></span></div>
            </div>
            <div class="flex gap-3 mt-4">
              <button type="button" @click="step = 1" class="px-4 py-2 rounded-lg border border-soft-beige">Edit</button>
              <button type="button" @click="submit()" class="ml-auto px-4 py-2 btn-primary text-white rounded-lg">Submit Estimate Request</button>
            </div>
          </div>
        </div>

        <div class="mt-6 flex items-center gap-3">
          <button type="button" @click="prev()" class="inline-flex items-center gap-2 px-4 py-2 rounded-lg border border-soft-beige" :disabled="step === 1">Previous</button>
          <div class="ml-auto">
            <button type="button" x-show="step < 12" @click="next()" class="px-4 py-2 btn-primary text-white rounded-lg">Next</button>
            <button type="button" x-show="step === 12" @click="submit()" class="px-4 py-2 btn-primary text-white rounded-lg">Submit</button>
          </div>
        </div>
      </div>
    </form>
  </div>
</section>

<script>
function estimateWizard() {
  return {
    step: 1,
    projectTypes: ['New Construction', 'Renovation', 'Remodeling', 'Maintenance Works', 'Repair Works'],
    propertyTypes: ['Residential Home', 'Apartment', 'Office', 'Shop / Retail Space', 'Hotel / Guest House', 'Church', 'School', 'Warehouse', 'Other'],
    serviceCategories: [
      { label: 'Finishes & Interiors', options: ['Painting', 'Tiling', 'POP Ceiling', 'Gypsum Ceiling', 'Flooring', 'Furniture Design', 'Lighting Installation', 'Wall Panels'] },
      { label: 'Construction & Renovation', options: ['Roofing', 'Walls & Partitions', 'Compound Beautification', 'Landscaping', 'Plumbing', 'Electrical Works'] },
      { label: 'Design & Consultation', options: ['Interior Design', 'Project Measurement', 'Costing', 'Renovation Planning'] }
    ],
    projectSizes: ['Single Room', '1–2 Bedroom House', '3–4 Bedroom House', '5+ Bedroom House', 'Small Office', 'Medium Office', 'Large Property'],
    projectStages: ['Design Stage', 'Foundation Stage', 'Roofing Stage', 'Plastering Stage', 'Ready for Finishes', 'Existing Building for Renovation'],
    timelineOptions: ['Immediately', 'Within 1 Month', 'Within 3 Months', 'Within 6 Months', 'Just Planning'],
    formData: {
      project_type: '',
      property_type: '',
      services: [],
      region: '',
      city: '',
      area: '',
      project_size: '',
      floor_area: '',
      project_stage: '',
      timeline_start: '',
      timeline_end: '',
      site_visit: '',
      preferred_visit_date: '',
      preferred_visit_time: '',
      full_name: '',
      phone: '',
      whatsapp: '',
      email: '',
      preferred_contact: 'Phone Call',
      notes: ''
    },
    filesCount: 0,
    get filesCountText() {
      return this.filesCount ? this.filesCount + ' file(s) uploaded' : 'No files uploaded';
    },
    handleFiles() {
      const files = this.$refs.uploads.files;
      this.filesCount = files ? files.length : 0;
    },
    validateCurrent() {
      const fd = this.formData;
      switch (this.step) {
        case 1: return !!fd.project_type;
        case 2: return !!fd.property_type;
        case 3: return fd.services.length > 0;
        case 4: return !!fd.region && !!fd.city && !!fd.area;
        case 5: return !!fd.project_size || !!fd.floor_area;
        case 6: return !!fd.project_stage;
        case 7: return !!fd.timeline_start && !!fd.timeline_end;
        case 8: return true;
        case 9: return !!fd.site_visit && (fd.site_visit === 'No' || (!!fd.preferred_visit_date && !!fd.preferred_visit_time));
        case 10: return !!fd.full_name && !!fd.phone && !!fd.email;
        case 11: return true;
        case 12: return true;
        default: return true;
      }
    },
    next() {
      if (!this.validateCurrent()) {
        alert('Please complete the required fields on this step before continuing.');
        return;
      }
      if (this.step < 12) this.step++;
      window.scrollTo({ top: 0, behavior: 'smooth' });
    },
    prev() {
      if (this.step > 1) this.step--;
      window.scrollTo({ top: 0, behavior: 'smooth' });
    },
    async submit() {
      if (!this.validateCurrent()) {
        alert('Please complete required fields.');
        return;
      }
      const form = this.$refs.form;
      const formData = new FormData(form);
      try {
        const res = await fetch(form.getAttribute('action'), {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        body: formData
      });
      if (!res.ok) {
        const text = await res.text().catch(() => '');
        throw new Error('Network error: ' + res.status + ' ' + text);
      }
      const json = await res.json();
      if (json.success) {
        alert('Thank you! Your estimate request was submitted. Reference: ' + (json.reference || 'BV-EST-2026-00001'));
        window.location.href = '<?= htmlspecialchars($baseUrl) ?>/';
      } else {
        alert('Submission failed: ' + (json.message || 'Unknown error'));
      }
    } catch (e) {
      alert('Could not submit request. Please try again later. ' + (e.message || ''));
      console.error(e);
    }
    }
  };
}
</script>

