<?php
if (!defined('ABSPATH'))
  exit;

function cutqueue_detect_store_id()
{
  $host = isset($_SERVER['HTTP_HOST'])
    ? sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST']))
    : '';

  $raw_request_uri = isset($_SERVER['REQUEST_URI'])
    ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI']))
    : '';

  $uri = trim($raw_request_uri, '/');

  // Break into path parts
  $parts = explode('/', $uri);

  // Remove index.php or other base file names
  if (!empty($parts[0]) && stripos($parts[0], 'index') !== false) {
    array_shift($parts);
  }

  // If homepage (no first segment) or the first segment is "home", treat as home
  $first = isset($parts[0]) ? $parts[0] : '';
  if ($first === '' || strcasecmp($first, 'home') === 0) {
    return 'store_home';
  }

  // Detect first path segment (example.com/galway/)
  if (!empty($parts[0]) && strlen($parts[0]) > 1) {
    return 'store_' . sanitize_title($parts[0]);
  }

  // Detect subdomain (galway.example.com)
  if (preg_match('/^([a-z0-9-]+)\./i', $host, $m)) {
    $sub = strtolower($m[1]);
    if ($sub !== 'www')
      return 'store_' . sanitize_title($sub);
  }

  // Default fallback
  return 'store_default';
}

function cutqueue_booking_form_shortcode()
{
  $store_id = cutqueue_detect_store_id();
  $payment_mode = get_option("cutqueue_booking_system_payment_mode_{$store_id}", 'disabled');
  $stripe_public_key = get_option("cutqueue_booking_system_stripe_public_key_{$store_id}", '');

  // ===== Load Store-Scoped Data =====
  $services = get_option("cutqueue_booking_system_services_{$store_id}", []);
  $workers_raw = get_option("cutqueue_booking_system_workers_{$store_id}", []);
  $opening_hours_raw = get_option("cutqueue_booking_system_opening_hours_{$store_id}", []);
  $bookings_raw = get_option("cutqueue_booking_system_bookings_{$store_id}", []);

  if (!is_array($services))
    $services = [];
  if (!is_array($workers_raw))
    $workers_raw = [];
  if (!is_array($opening_hours_raw))
    $opening_hours_raw = [];
  if (!is_array($bookings_raw))
    $bookings_raw = [];

  // ===== Normalize data =====
  $disable_worker_select = get_option(cutqueue_booking_system_opt('cutqueue_booking_system_disable_worker_select', $store_id), false);
  $slots_per_booking = get_option("cutqueue_booking_system_slots_per_booking_{$store_id}", 1);

  $workers = [];
  $workers[] = ['label' => 'Any Available Worker', 'value' => 'any'];

  if (!$disable_worker_select) {
    foreach ($workers_raw as $w) {
      $label = is_array($w) && isset($w['name']) ? $w['name'] : (string) $w;
      $value = sanitize_title($label);
      $workers[] = ['label' => $label, 'value' => $value];
    }
  }

  // --- Normalize opening hours
  $opening_hours = [];
  $days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
  foreach ($days as $day) {
    $hours = $opening_hours_raw[$day] ?? [];
    if (is_array($hours)) {
      $start = $hours['start'] ?? ($hours['open'] ?? '');
      $end = $hours['end'] ?? ($hours['close'] ?? '');
      $opening_hours[$day] = ['start' => $start, 'end' => $end];
    } else {
      $opening_hours[$day] = ['start' => '', 'end' => ''];
    }
  }

  // --- Normalize worker schedules
  $workersSchedule = [];

  foreach ($workers_raw as $w) {
      if (!is_array($w) || empty($w['name'])) {
          continue;
      }
      $label = $w['name'];
      $key   = sanitize_title($label);

      $rawSchedule = $w['schedule'] ?? [];

      $normalized = [];

      foreach ($days as $day) {
          $entry = $rawSchedule[$day] ?? [];

          $start   = $entry['start'] ?? '';
          $end     = $entry['end'] ?? '';
          $enabled = !empty($entry['enabled']);

          $normalized[$day] = [
              'start'   => $start,
              'end'     => $end,
              'enabled' => $enabled,
          ];
      }
      $workersSchedule[$key] = $normalized;
  }

  // --- Normalize bookings
  $bookings = [];
  foreach ($bookings_raw as $b) {
    $workerLabel = $b['worker'] ?? ($b->worker ?? '');
    $date = $b['date'] ?? ($b->date ?? '');
    $time = $b['time'] ?? ($b->time ?? '');
    if ($date && $time) {
      $bookings[] = [
        'worker' => sanitize_title($workerLabel),
        'date' => $date,
        'time' => $time
      ];
    }
  }

  // ===== Enqueue assets =====
  wp_enqueue_script('jquery');

  wp_enqueue_style(
    'cutqueue-shortcode',
    plugin_dir_url(dirname(__FILE__)) . 'assets/css/shortcode.css',
    [],
    '1.0.0'
  );

  wp_enqueue_style(
    'cutqueue_booking_system-bootstrap',
    plugin_dir_url(dirname(__FILE__)) . 'assets/css/bootstrap.min.css',
    [],
    '5.3.8'
  );

  wp_enqueue_script(
    'cutqueue_booking_system-bootstrap-js',
    plugin_dir_url(dirname(__FILE__)) . 'assets/js/bootstrap.bundle.min.js',
    [],
    '5.3.8',
    true
  );

  wp_enqueue_script(
    'cutqueue_booking_system-form-js',
    plugin_dir_url(dirname(__FILE__)) . 'assets/js/booking-form-logic.js',
    ['jquery', 'stripe-js', 'cutqueue_booking_system-bootstrap-js'],
    '1.0',
    true
  );

  wp_localize_script('cutqueue_booking_system-form-js', 'cutqueue_booking_system_formData', [
    'openingHours' => $opening_hours,
    'workers' => $workers,
    'workersSchedule' => $workersSchedule,
    'bookings' => $bookings,
    'totalWorkers' => count($workers_raw),
    'ajaxUrl' => admin_url('admin-ajax.php'),
    'nonce' => wp_create_nonce('cutqueue_booking_system_booking_nonce'),
    'storeId' => $store_id,
    'disableWorkerSelection' => $disable_worker_select,
    'slotsPerBooking' => $slots_per_booking,
    'paymentMode' => $payment_mode,
    'stripePublicKey' => $stripe_public_key
  ]);

  ob_start();
  ?>

  <div class="container my-4">
    <div class="booking-card">
      <form id="cutqueue-form">
        <div class="progress-wrapper mb-4">
          <h2 class="text-center mb-4 fade-in">Book Your Appointment</h2>
          <div class="progress-labels">
            <span class="step-label">Details</span>
            <span class="step-label">Service</span>
            <span class="step-label">Time</span>

            <?php if ($payment_mode === 'online' || $payment_mode === 'both'): ?>
              <span class="step-label">Payment</span>
            <?php endif; ?>

          </div>
          <div class="progress">
            <div class="progress-bar" role="progressbar"></div>
          </div>
        </div>

        <input type="hidden" name="cutqueue_booking_system_store_id" value="<?php echo esc_attr($store_id); ?>">
        <!-- STEP 1 -->
        <div class="form-step active" data-step="1">
          <div class="mb-3"><label class="form-label">Name</label><input type="text" id="cutqueue_booking_system_name" name="cutqueue_booking_system_name"
              class="form-control" placeholder="Enter your name" required></div>
          <div class="mb-3"><label class="form-label">Email</label><input type="email" id="cutqueue_booking_system_email" name="cutqueue_booking_system_email"
              class="form-control" placeholder="Enter your email" required></div>
          <div class="mb-3"><label class="form-label">Mobile Number</label><input type="tel" id="cutqueue_booking_system_mobile"
              name="cutqueue_booking_system_mobile" class="form-control" required pattern="[0-9+\-\s]+" placeholder="Enter your phone number">
          </div>
          <button type="button" class="btn btn-primary w-100 next-step">Next →</button>
        </div>

        <!-- STEP 2 -->
        <div class="form-step" data-step="2">
          <div class="mb-3">
            <label class="form-label">Worker</label>
            <select id="cutqueue_booking_system_worker" name="cutqueue_booking_system_worker" class="form-select" required>
              <option value="">Select worker</option>
              <?php foreach ($workers as $w): ?>
                <option value="<?php echo esc_attr($w['value']); ?>"><?php echo esc_html($w['label']); ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="mb-3">
            <label class="form-label">Service</label>
            <select id="cutqueue_booking_system_service" name="cutqueue_booking_system_service" class="form-select" required>
              <?php foreach ($services as $s): ?>
                <option data-price="<?php echo esc_attr($s['price']); ?>" value="<?php echo esc_attr($s['name']); ?>">
                  <?php echo esc_html($s['name']); ?> (€<?php echo esc_html($s['price']); ?>)
                </option>
              <?php endforeach; ?>
            </select>
            <input type="hidden" name="cutqueue_booking_system_service_price" id="cutqueue_booking_system_service_price" value="0">
          </div>
          <button type="button" class="btn btn-secondary w-100 prev-step mb-2">← Back</button>
          <button type="button" class="btn btn-primary w-100 next-step">Next →</button>
        </div>

        <!-- STEP 3 -->
        <div class="form-step" data-step="3">
          <div class="mb-3"><label>Date</label><input type="date" id="cutqueue_booking_system_date" name="cutqueue_booking_system_date" class="form-control"
              required></div>
          <div class="mb-3"><label>Time</label><select id="cutqueue_booking_system_time" name="cutqueue_booking_system_time" class="form-select" required></select>
          </div>

          <?php if ($payment_mode === 'online' || $payment_mode === 'both'): ?>
            <button type="button" class="btn btn-secondary w-100 prev-step mb-2">← Back</button>
            <button type="button" class="btn btn-primary w-100 next-step">Next →</button>
          <?php else: ?>
            <button type="button" class="btn btn-secondary w-100 prev-step mb-2">← Back</button>
            <button type="submit" class="btn btn-success w-100">Book Now</button>
          <?php endif; ?>
        </div>

        <?php if ($payment_mode === 'online' || $payment_mode === 'both'): ?>
          <!-- STEP 4: PAYMENT -->
          <div class="form-step" data-step="4">
            <h4 class="mb-3 text-center fw-bold">Payment Details</h4>
            <!-- Booking Summary -->
            <div class="card shadow-sm border-0 mb-4">
              <div class="card-body d-flex justify-content-between align-items-center">
                <div class="row">
                  <div class="fs-7" id="summary-service-name">Selected Service</div>
                  <div class="text-muted small">Confirm your booking & payment below</div>
                </div>
              </div>
            </div>

            <!-- Payment Inputs -->
            <div class="card shadow-sm border-0 p-3 mb-3">
              <div class="mb-3">
                <label class="form-label fs-7">Card Number</label>
                <div id="card-number" class="form-control p-2">
                </div>
              </div>
              <div class="row">
                <div class="col-md-6 mb-3">
                  <label class="form-label fs-7">Expiry</label>
                  <div id="card-expiry" class="form-control p-2">
                  </div>
                </div>
                <div class="col-md-6 mb-3">
                  <label class="form-label fs-7">CVC</label>
                  <div id="card-cvc" class="form-control p-2">
                  </div>
                </div>
              </div>
              <div id="card-errors" style="color:red;margin-top:8px;"></div>
            </div>
            <button type="button" class="btn btn-secondary w-100 mb-2 prev-step">← Back</button>
            <button type="submit" class="btn btn-success w-100 fw-semibold py-2">
              Pay <span id="pay-amount-label">€0.00</span>
            </button>
          </div>

        <?php endif; ?>

        <div id="cutqueue_booking_system_message" class="mt-3 fade-in"></div>

        <div class="cutqueue-logo text-center mt-4">
          <img src="<?php echo wp_kses_post(plugin_dir_url(dirname(__FILE__))); ?>assets/images/cutqueue-logo.png"
            alt="CutQueue Logo" class="img-fluid" style="max-width: 50px; opacity: 0.9; margin-bottom: -20px;">
          <div class="small text-muted mt-2"><a href="https://cutqueuebooking.com" target="_blank">Powered by CutQueue</a>
          </div>
        </div>
      </form>
    </div>
  </div>

  <?php
  return ob_get_clean();
}

add_shortcode('cutqueue_booking_form', 'cutqueue_booking_form_shortcode');
