<?php
$active = 'services';
$pageTitle = 'Services';
require_once __DIR__ . '/partials/top.php';
$pdo = db();

$action = $_GET['action'] ?? '';
$id = (int)($_GET['id'] ?? 0);
$msg = '';

function ensure_upload_dir(string $dir): void { if (!is_dir($dir)) { mkdir($dir, 0775, true); } }
function is_allowed_image_ext(string $ext): bool { return in_array(strtolower($ext), ['jpg','jpeg','png','webp'], true); }
function delete_file_if_exists(?string $path): void { if ($path && file_exists($path) && is_file($path)) @unlink($path); }

function upload_image(array $file, string $destDir): array {
  if (!isset($file['tmp_name']) || $file['error'] === UPLOAD_ERR_NO_FILE) return [false,'','No file selected.'];
  if ($file['error'] !== UPLOAD_ERR_OK) return [false,'','Upload failed.'];
  if ($file['size'] > 5 * 1024 * 1024) return [false,'','File too large (max 5MB).'];

  $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
  if (!is_allowed_image_ext($ext)) return [false,'','Invalid file type. Only jpg/jpeg/png/webp allowed.'];

  ensure_upload_dir($destDir);
  $safeName = bin2hex(random_bytes(10)) . '.' . strtolower($ext);
  $destPath = rtrim($destDir,'/').'/'.$safeName;

  if (!move_uploaded_file($file['tmp_name'], $destPath)) return [false,'','Could not save uploaded file.'];
  return [true, $destPath, ''];
}

function upload_multiple_images(array $files, string $destDir): array {
  // returns [paths[], errors[]]
  $paths = [];
  $errors = [];

  if (!isset($files['name']) || !is_array($files['name'])) return [$paths, $errors];

  $count = count($files['name']);
  for ($i=0; $i<$count; $i++) {
    if ($files['error'][$i] === UPLOAD_ERR_NO_FILE) continue;
    $file = [
      'name' => $files['name'][$i],
      'type' => $files['type'][$i],
      'tmp_name' => $files['tmp_name'][$i],
      'error' => $files['error'][$i],
      'size' => $files['size'][$i],
    ];
    [$ok, $path, $err] = upload_image($file, $destDir);
    if ($ok) $paths[] = $path;
    else $errors[] = $file['name'] . ': ' . $err;
  }

  return [$paths, $errors];
}

$categories = $pdo->query("SELECT id, name FROM categories WHERE is_active=1 ORDER BY name ASC")->fetchAll();
$allSubcategories = $pdo->query("SELECT id, category_id, name FROM subcategories WHERE is_active=1 ORDER BY name ASC")->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $mode = $_POST['mode'] ?? '';

  if ($mode === 'remove_image') {
    $service_id = (int)($_POST['service_id'] ?? 0);
    $img = trim($_POST['img'] ?? '');

    $st = $pdo->prepare("SELECT images_json FROM services WHERE id=?");
    $st->execute([$service_id]);
    $row = $st->fetch();

    if (!$row) {
      $msg = "<div class='alert alert-danger'>Service not found.</div>";
    } else {
      $images = json_decode($row['images_json'] ?? '[]', true);
      if (!is_array($images)) $images = [];

      $new = [];
      foreach ($images as $p) {
        if ($p === $img) {
          delete_file_if_exists(__DIR__ . '/' . $p);
        } else {
          $new[] = $p;
        }
      }

      $stmt = $pdo->prepare("UPDATE services SET images_json=? WHERE id=?");
      $stmt->execute([json_encode(array_values($new)), $service_id]);

      $msg = "<div class='alert alert-success'>Image removed.</div>";
      $action = 'edit';
      $id = $service_id;
    }
  }

  if ($mode === 'save') {
    $service_id = (int)($_POST['service_id'] ?? 0);
    $category_id = (int)($_POST['category_id'] ?? 0);
    $subcategory_id = (int)($_POST['subcategory_id'] ?? 0);
    $title = trim($_POST['title'] ?? '');
    $price = (int)($_POST['price'] ?? 0);
    $description = trim($_POST['description'] ?? '');
    $is_active = isset($_POST['is_active']) ? 1 : 0;

    if ($category_id <= 0 || $subcategory_id <= 0 || $title === '' || $price <= 0) {
      $msg = "<div class='alert alert-danger'>Category, subcategory, title, and price are required.</div>";
    } else {
      // Validate subcategory belongs to category
      $st = $pdo->prepare("SELECT COUNT(*) FROM subcategories WHERE id=? AND category_id=?");
      $st->execute([$subcategory_id, $category_id]);
      if ((int)$st->fetchColumn() === 0) {
        $msg = "<div class='alert alert-danger'>Selected subcategory does not belong to the selected category.</div>";
      }
    }

    $existingThumb = '';
    $existingImages = [];

    if ($msg === '' && $service_id) {
      $st = $pdo->prepare("SELECT thumbnail, images_json FROM services WHERE id=?");
      $st->execute([$service_id]);
      $row = $st->fetch();
      if (!$row) {
        $msg = "<div class='alert alert-danger'>Service not found.</div>";
      } else {
        $existingThumb = $row['thumbnail'] ?? '';
        $existingImages = json_decode($row['images_json'] ?? '[]', true);
        if (!is_array($existingImages)) $existingImages = [];
      }
    }

    if ($msg === '') {
      // Thumbnail (optional on edit, recommended on add)
      $thumbPath = $existingThumb;

      if (!empty($_FILES['thumbnail']) && $_FILES['thumbnail']['error'] !== UPLOAD_ERR_NO_FILE) {
        [$ok, $path, $err] = upload_image($_FILES['thumbnail'], __DIR__ . '/uploads/services');
        if (!$ok) {
          $msg = "<div class='alert alert-danger'>Thumbnail: " . htmlspecialchars($err) . "</div>";
        } else {
          $thumbPath = 'uploads/services/' . basename($path);
          delete_file_if_exists(__DIR__ . '/' . $existingThumb);
        }
      } else {
        // If creating and no thumbnail supplied -> error
        if (!$service_id && $thumbPath === '') {
          $msg = "<div class='alert alert-danger'>Thumbnail is required for a new service.</div>";
        }
      }

      // Gallery images
      $galleryPathsRel = [];
      if ($msg === '' && !empty($_FILES['images'])) {
        [$pathsAbs, $errs] = upload_multiple_images($_FILES['images'], __DIR__ . '/uploads/services');
        if (!empty($errs)) {
          $msg = "<div class='alert alert-danger'>Some images failed: " . htmlspecialchars(implode(', ', $errs)) . "</div>";
        } else {
          foreach ($pathsAbs as $p) {
            $galleryPathsRel[] = 'uploads/services/' . basename($p);
          }
        }
      }

      if ($msg === '') {
        $finalImages = array_values(array_merge($existingImages, $galleryPathsRel));

        if ($service_id) {
          $stmt = $pdo->prepare("
            UPDATE services
            SET category_id=?, subcategory_id=?, title=?, price=?, description=?, thumbnail=?, images_json=?, is_active=?
            WHERE id=?
          ");
          $stmt->execute([$category_id, $subcategory_id, $title, $price, $description, $thumbPath, json_encode($finalImages), $is_active, $service_id]);
          $msg = "<div class='alert alert-success'>Service updated.</div>";
        } else {
          $stmt = $pdo->prepare("
            INSERT INTO services (category_id, subcategory_id, title, price, description, thumbnail, images_json, is_active)
            VALUES (?,?,?,?,?,?,?,?)
          ");
          $stmt->execute([$category_id, $subcategory_id, $title, $price, $description, $thumbPath, json_encode($finalImages), $is_active]);
          $msg = "<div class='alert alert-success'>Service created.</div>";
        }

        $action = '';
        $id = 0;
      }
    }
  }

  if ($mode === 'toggle') {
    $service_id = (int)($_POST['service_id'] ?? 0);
    $stmt = $pdo->prepare("UPDATE services SET is_active = IF(is_active=1,0,1) WHERE id=?");
    $stmt->execute([$service_id]);
    $msg = "<div class='alert alert-success'>Service status toggled.</div>";
  }

  if ($mode === 'delete') {
    $service_id = (int)($_POST['service_id'] ?? 0);

    $st = $pdo->prepare("SELECT thumbnail, images_json FROM services WHERE id=?");
    $st->execute([$service_id]);
    $row = $st->fetch();

    $stmt = $pdo->prepare("DELETE FROM services WHERE id=?");
    $stmt->execute([$service_id]);

    if ($row) {
      delete_file_if_exists(__DIR__ . '/' . ($row['thumbnail'] ?? ''));
      $imgs = json_decode($row['images_json'] ?? '[]', true);
      if (is_array($imgs)) {
        foreach ($imgs as $p) delete_file_if_exists(__DIR__ . '/' . $p);
      }
    }

    $msg = "<div class='alert alert-success'>Service deleted.</div>";
  }
}

if ($action === 'edit' || $action === 'add') {
  $service = [
    'id'=>0,'category_id'=>0,'subcategory_id'=>0,'title'=>'','price'=>0,'description'=>'',
    'thumbnail'=>'','images_json'=>'[]','is_active'=>1
  ];

  if ($action === 'edit') {
    $stmt = $pdo->prepare("SELECT * FROM services WHERE id=?");
    $stmt->execute([$id]);
    $service = $stmt->fetch();
    if (!$service) { echo "<div class='alert alert-danger'>Service not found</div>"; require_once __DIR__.'/partials/bottom.php'; exit; }
  }

  $existingImages = json_decode($service['images_json'] ?? '[]', true);
  if (!is_array($existingImages)) $existingImages = [];

  ?>
  <div class="d-flex justify-content-between align-items-center mb-3">
    <div>
      <h4 class="fw-bold mb-0"><?php echo $action==='add'?'Create Service':'Edit Service'; ?></h4>
      <div class="text-muted small">Services appear under category/subcategory with thumbnail and gallery images.</div>
    </div>
    <a class="btn btn-outline-dark" href="services.php">Back</a>
  </div>

  <?php echo $msg; ?>

  <div class="card p-4">
    <form method="post" enctype="multipart/form-data">
      <input type="hidden" name="mode" value="save">
      <input type="hidden" name="service_id" value="<?php echo (int)$service['id']; ?>">

      <div class="row g-3">
        <div class="col-md-6">
          <label class="form-label">Category</label>
          <select class="form-select" name="category_id" id="category_id" required>
            <option value="">Select category</option>
            <?php foreach ($categories as $c): ?>
              <option value="<?php echo (int)$c['id']; ?>" <?php if ((int)$service['category_id']===(int)$c['id']) echo 'selected'; ?>>
                <?php echo htmlspecialchars($c['name']); ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="col-md-6">
          <label class="form-label">Subcategory</label>
          <select class="form-select" name="subcategory_id" id="subcategory_id" required>
            <option value="">Select subcategory</option>
            <?php foreach ($allSubcategories as $s): ?>
              <option value="<?php echo (int)$s['id']; ?>"
                data-category="<?php echo (int)$s['category_id']; ?>"
                <?php if ((int)$service['subcategory_id']===(int)$s['id']) echo 'selected'; ?>>
                <?php echo htmlspecialchars($s['name']); ?>
              </option>
            <?php endforeach; ?>
          </select>
          <div class="text-muted small mt-1">Subcategories are filtered by selected category.</div>
        </div>

        <div class="col-md-8">
          <label class="form-label">Service Title</label>
          <input class="form-control" name="title" required value="<?php echo htmlspecialchars($service['title']); ?>">
        </div>

        <div class="col-md-4">
          <label class="form-label">Price (₹)</label>
          <input class="form-control" type="number" min="1" name="price" required value="<?php echo (int)$service['price']; ?>">
        </div>

        <div class="col-12">
          <label class="form-label">Description</label>
          <textarea class="form-control" name="description" rows="4"><?php echo htmlspecialchars($service['description'] ?? ''); ?></textarea>
        </div>

        <div class="col-md-6">
          <label class="form-label">Thumbnail <?php echo $action==='add' ? '(required)' : '(optional)'; ?></label>
          <input class="form-control" type="file" name="thumbnail" accept=".jpg,.jpeg,.png,.webp">
          <?php if (!empty($service['thumbnail'])): ?>
            <div class="mt-2 small text-muted">Current:</div>
            <img src="<?php echo htmlspecialchars($service['thumbnail']); ?>" style="height:48px;border-radius:8px;">
          <?php endif; ?>
        </div>

        <div class="col-md-6">
          <label class="form-label">Gallery Images (multiple)</label>
          <input class="form-control" type="file" name="images[]" accept=".jpg,.jpeg,.png,.webp" multiple>
          <div class="text-muted small mt-1">You can add more images any time. Max 5MB each.</div>
        </div>

        <?php if (!empty($existingImages)): ?>
          <div class="col-12">
            <div class="fw-semibold mb-2">Current Gallery</div>
            <div class="d-flex flex-wrap gap-2">
              <?php foreach ($existingImages as $img): ?>
                <div class="border rounded p-2">
                  <img src="<?php echo htmlspecialchars($img); ?>" style="height:60px;width:60px;object-fit:cover;border-radius:10px;">
                  <form method="post" class="mt-2">
                    <input type="hidden" name="mode" value="remove_image">
                    <input type="hidden" name="service_id" value="<?php echo (int)$service['id']; ?>">
                    <input type="hidden" name="img" value="<?php echo htmlspecialchars($img); ?>">
                    <button class="btn btn-sm btn-outline-danger" type="submit">Remove</button>
                  </form>
                </div>
              <?php endforeach; ?>
            </div>
          </div>
        <?php endif; ?>

        <div class="col-12">
          <div class="form-check">
            <input class="form-check-input" type="checkbox" name="is_active" id="active" <?php if ((int)$service['is_active']===1) echo 'checked'; ?>>
            <label class="form-check-label" for="active">Active</label>
          </div>
        </div>

        <div class="col-12 d-flex gap-2">
          <button class="btn btn-dark" type="submit">Save Service</button>
        </div>
      </div>
    </form>
  </div>

  <script>
    (function() {
      const cat = document.getElementById('category_id');
      const sub = document.getElementById('subcategory_id');

      function filterSubs() {
        const catId = cat.value;
        const options = sub.querySelectorAll('option');
        let hasSelected = false;

        options.forEach((opt, idx) => {
          if (idx === 0) return;
          const optCat = opt.getAttribute('data-category');
          const show = (!catId) || (optCat === catId);
          opt.style.display = show ? '' : 'none';
          if (!show && opt.selected) opt.selected = false;
          if (opt.selected) hasSelected = true;
        });

        if (!hasSelected) sub.value = '';
      }

      cat.addEventListener('change', filterSubs);
      filterSubs();
    })();
  </script>

  <?php
  require_once __DIR__ . '/partials/bottom.php';
  exit;
}

$services = $pdo->query("
  SELECT s.*,
         c.name AS category_name,
         sc.name AS subcategory_name
  FROM services s
  JOIN categories c ON c.id = s.category_id
  JOIN subcategories sc ON sc.id = s.subcategory_id
  ORDER BY s.created_at DESC
")->fetchAll();
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="fw-bold mb-0">Services</h4>
    <div class="text-muted small">Create, edit, enable/disable, and delete services.</div>
  </div>
  <a class="btn btn-dark" href="services.php?action=add">+ Create Service</a>
</div>

<?php echo $msg; ?>

<div class="card p-3">
  <div class="table-responsive">
    <table class="table align-middle mb-0">
      <thead>
        <tr>
          <th>Thumbnail</th>
          <th>Service</th>
          <th>Category</th>
          <th>Subcategory</th>
          <th>Price</th>
          <th>Status</th>
          <th class="text-end">Actions</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach ($services as $s): ?>
        <tr>
          <td style="width:80px;">
            <?php if (!empty($s['thumbnail'])): ?>
              <img src="<?php echo htmlspecialchars($s['thumbnail']); ?>" style="height:42px;width:42px;object-fit:cover;border-radius:10px;">
            <?php else: ?>
              <span class="text-muted small">—</span>
            <?php endif; ?>
          </td>
          <td class="fw-semibold"><?php echo htmlspecialchars($s['title']); ?></td>
          <td><?php echo htmlspecialchars($s['category_name']); ?></td>
          <td><?php echo htmlspecialchars($s['subcategory_name']); ?></td>
          <td>₹<?php echo (int)$s['price']; ?></td>
          <td>
            <?php if ((int)$s['is_active']===1): ?>
              <span class="badge text-bg-success">active</span>
            <?php else: ?>
              <span class="badge text-bg-secondary">disabled</span>
            <?php endif; ?>
          </td>
          <td class="text-end">
            <a class="btn btn-sm btn-outline-dark" href="services.php?action=edit&id=<?php echo (int)$s['id']; ?>">Edit</a>

            <form method="post" style="display:inline;">
              <input type="hidden" name="mode" value="toggle">
              <input type="hidden" name="service_id" value="<?php echo (int)$s['id']; ?>">
              <button class="btn btn-sm btn-dark" type="submit"><?php echo (int)$s['is_active']===1?'Disable':'Enable'; ?></button>
            </form>

            <form method="post" style="display:inline;" onsubmit="return confirm('Delete this service? This will remove images too.');">
              <input type="hidden" name="mode" value="delete">
              <input type="hidden" name="service_id" value="<?php echo (int)$s['id']; ?>">
              <button class="btn btn-sm btn-outline-danger" type="submit">Delete</button>
            </form>
          </td>
        </tr>
      <?php endforeach; ?>
      <?php if (count($services)===0): ?>
        <tr><td colspan="7" class="text-muted">No services found.</td></tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<?php require_once __DIR__ . '/partials/bottom.php'; ?>
