<?php
$active = 'categories';
$pageTitle = 'Categories';
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 {
  $ext = strtolower($ext);
  return in_array($ext, ['jpg','jpeg','png','webp'], true);
}

function upload_image(array $file, string $destDir): array {
  // returns [ok(bool), path(string), error(string)]
  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 delete_file_if_exists(?string $path): void {
  if ($path && file_exists($path) && is_file($path)) {
    @unlink($path);
  }
}

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

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

    if ($name === '') {
      $msg = "<div class='alert alert-danger'>Category name is required.</div>";
    } else {
      // fetch existing thumbnail if editing
      $existingThumb = '';
      if ($cat_id) {
        $st = $pdo->prepare("SELECT thumbnail FROM categories WHERE id=?");
        $st->execute([$cat_id]);
        $row = $st->fetch();
        $existingThumb = $row['thumbnail'] ?? '';
        if (!$row) {
          $msg = "<div class='alert alert-danger'>Category not found.</div>";
        }
      }

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

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

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

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

    // Block delete if subcategories/services exist (recommended)
    $st = $pdo->prepare("SELECT COUNT(*) FROM subcategories WHERE category_id=?");
    $st->execute([$cat_id]);
    $subCount = (int)$st->fetchColumn();

    $st = $pdo->prepare("SELECT COUNT(*) FROM services WHERE category_id=?");
    $st->execute([$cat_id]);
    $svcCount = (int)$st->fetchColumn();

    if ($subCount > 0 || $svcCount > 0) {
      $msg = "<div class='alert alert-danger'>Cannot delete: category has subcategories/services.</div>";
    } else {
      $st = $pdo->prepare("SELECT thumbnail FROM categories WHERE id=?");
      $st->execute([$cat_id]);
      $row = $st->fetch();

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

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

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

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

  if ($action === 'edit') {
    $stmt = $pdo->prepare("SELECT * FROM categories WHERE id=?");
    $stmt->execute([$id]);
    $category = $stmt->fetch();
    if (!$category) { echo "<div class='alert alert-danger'>Category 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 Category':'Edit Category'; ?></h4>
      <div class="text-muted small">Categories are used in Subcategories and Services.</div>
    </div>
    <a class="btn btn-outline-dark" href="categories.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="category_id" value="<?php echo (int)$category['id']; ?>">
      <div class="row g-3">
        <div class="col-md-8">
          <label class="form-label">Category Name</label>
          <input class="form-control" name="name" required value="<?php echo htmlspecialchars($category['name']); ?>">
        </div>

        <div class="col-md-4">
          <label class="form-label">Thumbnail</label>
          <input class="form-control" type="file" name="thumbnail" accept=".jpg,.jpeg,.png,.webp">
          <?php if (!empty($category['thumbnail'])): ?>
            <div class="mt-2 small text-muted">Current:</div>
            <img src="<?php echo htmlspecialchars($category['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)$category['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 Category</button>
        </div>
      </div>
    </form>
  </div>
  <?php
  require_once __DIR__ . '/partials/bottom.php';
  exit;
}

$categories = $pdo->query("SELECT * FROM categories ORDER BY created_at DESC")->fetchAll();
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="fw-bold mb-0">Categories</h4>
    <div class="text-muted small">Create, edit, enable/disable, and delete categories.</div>
  </div>
  <a class="btn btn-dark" href="categories.php?action=add">+ Create Category</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>Name</th>
          <th>Status</th>
          <th class="text-end">Actions</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach ($categories as $c): ?>
        <tr>
          <td style="width:80px;">
            <?php if (!empty($c['thumbnail'])): ?>
              <img src="<?php echo htmlspecialchars($c['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($c['name']); ?></td>
          <td>
            <?php if ((int)$c['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="categories.php?action=edit&id=<?php echo (int)$c['id']; ?>">Edit</a>

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

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

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