<?php 
session_start();
require_once 'config/auth_check.php';
require_once 'config/db.php';

// Search logic
$search = isset($_GET['search']) ? $conn->real_escape_string($_GET['search']) : '';
$where_clause = "";
if ($search != '') {
    $where_clause = "WHERE s.sub_category_name LIKE '%$search%' OR c.category_name LIKE '%$search%'";
}

// Fetch sub-categories with their parent category name
$query = "SELECT s.*, c.category_name 
          FROM sub_categories s
          JOIN categories c ON s.cat_id = c.id 
          $where_clause
          ORDER BY s.id DESC";
$result = $conn->query($query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Admin - Manage Sub-Categories</title>
  <link rel="stylesheet" href="assets/css/admin.css">
  <style>
    .sub-table {
        width: 100%;
        border-collapse: collapse;
        background: #fff;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 4px 10px rgba(0,0,0,0.05);
    }
    .sub-table th, .sub-table td {
        padding: 12px 15px;
        text-align: left;
        border-bottom: 1px solid #eee;
    }
    .sub-table th { background: #f8f9fa; color: #333; }
    .thumb-img {
        width: 50px;
        height: 50px;
        object-fit: cover;
        border-radius: 4px;
        background: #eee;
    }
    .badge-all { background: #e8f5e9; color: #2e7d32; padding: 4px 8px; border-radius: 4px; font-size: 11px; }
    .badge-selective { background: #fff3e0; color: #ef6c00; padding: 4px 8px; border-radius: 4px; font-size: 11px; }
  </style>
</head>
<body>

<?php include 'side-bar.php' ?>

<div class="main">
  <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
    <h2>Sub-Category Directory</h2>
    <a href="add-sub-category.php" class="btn-view" style="text-decoration:none; background:#3498db; color:#fff; padding:8px 15px; border-radius:5px;">+ Add New</a>
  </div>

  <form action="" method="GET" style="margin-bottom: 20px; display: flex; gap: 10px;">
    <input type="text" name="search" placeholder="Search sub-categories..." value="<?php echo htmlspecialchars($search); ?>" style="flex: 1; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
    <button type="submit" style="background:#3498db; color:#white; border:none; padding:10px 20px; border-radius:5px; cursor:pointer; width:50%">Search</button>
  </form>

  <table class="sub-table">
    <thead>
      <tr>
        <th>ID</th>
        <th>Thumbnail</th>
        <th>Sub-Category Name</th>
        <th>Parent Category</th>
        <th>Visibility</th>
        <th>Status</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
      <?php if ($result->num_rows > 0): ?>
        <?php while($row = $result->fetch_assoc()): ?>
          <tr>
            <td><small style="color:#999"><?php echo $row['sub_cat_id']; ?></small></td>
            <td>
              <img src="<?php echo !empty($row['thumbnail_image']) ? $row['thumbnail_image'] : 'assets/img/no-thumb.png'; ?>" class="thumb-img">
            </td>
            <td><strong><?php echo $row['sub_category_name']; ?></strong></td>
            <td><?php echo $row['category_name']; ?></td>
            <td>
              <span class="<?php echo $row['companies_allowed'] == 'For All' ? 'badge-all' : 'badge-selective'; ?>">
                <?php echo $row['companies_allowed']; ?>
              </span>
            </td>
            <td>
              <span class="status-badge status-<?php echo strtolower(str_replace(' ', '', $row['status'])); ?>">
                <?php echo $row['status']; ?>
              </span>
            </td>
            <div id="toast-container" style="position: fixed; top: 20px; right: 20px; z-index: 1000;"></div>

              <td>
                  <a href="edit-sub-category.php?id=<?php echo $row['id']; ?>" style="color:#3498db; text-decoration:none;">Edit</a> |
                  <a href="javascript:void(0);" 
                    onclick="confirmDelete(<?php echo $row['id']; ?>, '<?php echo addslashes($row['sub_category_name']); ?>', this)" 
                    style="color:#e74c3c; text-decoration:none;">Delete</a>
              </td>
          </tr>
        <?php endwhile; ?>
      <?php else: ?>
        <tr><td colspan="7" style="text-align:center; padding: 50px; color:#999;">No sub-categories found.</td></tr>
      <?php endif; ?>
    </tbody>
  </table>
</div>


<script>
async function confirmDelete(id, name, element) {
    if (!confirm(`Are you sure you want to delete "${name}"? This will remove all associated template files.`)) {
        return;
    }

    // Optional: Visual feedback that process started
    const originalText = element.innerText;
    element.innerText = "Deleting...";
    element.style.pointerEvents = "none";

    try {
        const response = await fetch(`api/delete-sub-category.php?id=${id}`);
        const data = await response.json(); // This captures your JSON response

        if (data.success) {
            showToast(data.message, "success");
            // Remove the row from the table smoothly
            const row = element.closest('tr');
            row.style.transition = "opacity 0.5s";
            row.style.opacity = "0";
            setTimeout(() => row.remove(), 500);
        } else {
            showToast(data.message, "error");
            element.innerText = originalText;
            element.style.pointerEvents = "auto";
        }
    } catch (error) {
        showToast("System error: Could not reach the server.", "error");
        element.innerText = originalText;
        element.style.pointerEvents = "auto";
    }
}

function showToast(message, type) {
    const container = document.getElementById('toast-container');
    const toast = document.createElement('div');
    
    // Style based on type
    const bgColor = type === 'success' ? '#2ecc71' : '#e74c3c';
    
    toast.style.cssText = `
        background: ${bgColor};
        color: white;
        padding: 15px 25px;
        border-radius: 8px;
        margin-bottom: 10px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        font-family: 'Segoe UI', sans-serif;
        font-size: 14px;
        min-width: 250px;
        transition: all 0.5s ease;
        opacity: 0;
        transform: translateX(20px);
    `;
    
    toast.innerText = message;
    container.appendChild(toast);

    // Trigger animation
    setTimeout(() => {
        toast.style.opacity = "1";
        toast.style.transform = "translateX(0)";
    }, 100);

    // Remove after 4 seconds
    setTimeout(() => {
        toast.style.opacity = "0";
        toast.style.transform = "translateX(20px)";
        setTimeout(() => toast.remove(), 500);
    }, 4000);
}
</script>

</body>
</html>