<?php
$active = 'subcategories';
$pageTitle = 'Subcategories';
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, ''];
}

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

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

  if ($mode === 'save') {
    $sub_id = (int)($_POST['subcategory_id'] ?? 0);
    $category_id = (int)($_POST['category_id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    $is_active = isset($_POST['is_active']) ? 1 : 0;

    if ($category_id <= 0 || $name === '') {
      $msg = "<div class='alert alert-danger'>Category and subcategory name are required.</div>";
    } else {
      $existingThumb = '';
      if ($sub_id) {
        $st = $pdo->prepare("SELECT thumbnail FROM subcategories WHERE id=?");
        $st->execute([$sub_id]);
        $row = $st->fetch();
        if (!$row) {
          $msg = "<div class='alert alert-danger'>Subcategory not found.</div>";
        } else {
          $existingThumb = $row['thumbnail'] ?? '';
        }
      }

      if ($msg === '') {
        $thumbPath = $existingThumb;
        if (!empty($_FILES['thumbnail']) && $_FILES['thumbnail']['error'] !== UPLOAD_ERR_NO_FILE) {
          [$ok, $path, $err] = upload_image($_FILES['thumbnail'], __DIR__ . '/uploads/subcategories');
          if (!$ok) {
            $msg = "<div class='alert alert-danger'>Thumbnail: " . htmlspecialchars($err) . "</div>";
          } else {
            $thumbPath = 'uploads/subcategories/' . basename($path);
            delete_file_if_exists(__DIR__ . '/' . $existingThumb);
          }
        }

        if ($msg === '') {
          if ($sub_id) {
            $stmt = $pdo->prepare("UPDATE subcategories SET category_id=?, name=?, thumbnail=?, is_active=? WHERE id=?");
            $stmt->execute([$category_id, $name, $thumbPath, $is_active, $sub_id]);
            $msg = "<div class='alert alert-success'>Subcategory updated.</div>";
          } else {
            $stmt = $pdo->prepare("INSERT INTO subcategories (category_id, name, thumbnail, is_active) VALUES (?,?,?,?)");
            $stmt->execute([$category_id, $name, $thumbPath, $is_active]);
            $msg = "<div class='alert alert-success'>Subcategory created.</div>";
          }
          $action = '';
          $id = 0;
        }
      }
    }
  }

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

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

    $st = $pdo->prepare("SELECT COUNT(*) FROM services WHERE subcategory_id=?");
    $st->execute([$sub_id]);
    if ((int)$st->fetchColumn() > 0) {
      $msg = "<div class='alert alert-danger'>Cannot delete: subcategory has services.</div>";
    } else {
      $st = $pdo->prepare("SELECT thumbnail FROM subcategories WHERE id=?");
      $st->execute([$sub_id]);
      $row = $st->fetch();

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

      if ($row) delete_file_if_exists(__DIR__ . '/' . ($row['thumbnail'] ?? ''));

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

if ($action === 'edit' || $action === 'add') {
  $subcategory = ['id'=>0,'category_id'=>0,'name'=>'','thumbnail'=>'','is_active'=>1];

  if ($action === 'edit') {
    $stmt = $pdo->prepare("SELECT * FROM subcategories WHERE id=?");
    $stmt->execute([$id]);
    $subcategory = $stmt->fetch();
    if (!$subcategory) { echo "<div class='alert alert-danger'>Subcategory not found</div>"; require_once __DIR__.'/partials/bottom.php'; exit; }
  }
  ?>
  <div class="d-flex justify-content-between align-items-center mb-3">
    <div>
      <h4 class="fw-bold mb-0"><?php echo $action==='add'?'Create Subcategory':'Edit Subcategory'; ?></h4>
      <div class="text-muted small">Subcategories belong to a category and are used in Services.</div>
    </div>
    <a class="btn btn-outline-dark" href="subcategories.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="subcategory_id" value="<?php echo (int)$subcategory['id']; ?>">
      <div class="row g-3">
        <div class="col-md-6">
          <label class="form-label">Category</label>
          <select class="form-select" name="category_id" required>
            <option value="">Select category</option>
            <?php foreach ($categories as $c): ?>
              <option value="<?php echo (int)$c['id']; ?>" <?php if ((int)$subcategory['category_id']===(int)$c['id']) echo 'selected'; ?>>
                <?php echo htmlspecialchars($c['name']); ?>
              </option>
            <?php endforeach; ?>
          </select>
          <div class="text-muted small mt-1">Only active categories are shown.</div>
        </div>

        <div class="col-md-6">
          <label class="form-label">Subcategory Name</label>
          <input class="form-control" name="name" required value="<?php echo htmlspecialchars($subcategory['name']); ?>">
        </div>

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

        <div class="col-12">
          <div class="form-check">
            <input class="form-check-input" type="checkbox" name="is_active" id="active" <?php if ((int)$subcategory['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 Subcategory</button>
        </div>
      </div>
    </form>
  </div>
  <?php
  require_once __DIR__ . '/partials/bottom.php';
  exit;
}

$subcategories = $pdo->query("
  SELECT s.*, c.name AS category_name
  FROM subcategories s
  JOIN categories c ON c.id = s.category_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">Subcategories</h4>
    <div class="text-muted small">Create, edit, enable/disable, and delete subcategories.</div>
  </div>
  <a class="btn btn-dark" href="subcategories.php?action=add">+ Create Subcategory</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>Subcategory</th>
          <th>Category</th>
          <th>Status</th>
          <th class="text-end">Actions</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach ($subcategories 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['name']); ?></td>
          <td><?php echo htmlspecialchars($s['category_name']); ?></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="subcategories.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="subcategory_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 subcategory?');">
              <input type="hidden" name="mode" value="delete">
              <input type="hidden" name="subcategory_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($subcategories)===0): ?>
        <tr><td colspan="5" class="text-muted">No subcategories found.</td></tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

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