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

// 1. Capture Filter Parameters
$search = isset($_GET['search']) ? $conn->real_escape_string($_GET['search']) : '';
$cat_filter = isset($_GET['cat']) ? $conn->real_escape_string($_GET['cat']) : '';
$sub_filter = isset($_GET['sub']) ? $conn->real_escape_string($_GET['sub']) : '';

// 2. Build the Dynamic SQL Query
$where = "WHERE 1=1";
if ($search != '') {
    $where .= " AND (template_id LIKE '%$search%' OR category_name LIKE '%$search%' OR sub_category_name LIKE '%$search%')";
}
if ($cat_filter != '') {
    $where .= " AND category_name = '$cat_filter'";
}
if ($sub_filter != '') {
    $where .= " AND sub_category_name = '$sub_filter'";
}

$query = "SELECT * FROM templates $where ORDER BY id DESC";
$result = $conn->query($query);

// Fetch all active categories for the filter dropdown
$categories = $conn->query("SELECT DISTINCT category_name FROM categories WHERE status='Active' ORDER BY category_name ASC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Admin - Manage GVT Templates</title>
    <link rel="stylesheet" href="assets/css/admin.css">
    <style>
        /* Shared Styles */
        .filter-section { 
            background: #fff; 
            width: 95%;
            padding: 20px; 
            border-radius: 8px; 
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            margin-bottom: 25px;
            display: flex;
            gap: 15px;
            align-items: flex-end;
            flex-wrap: wrap;
        }
        .filter-group { display: flex; flex-direction: column; gap: 5px; flex: 1; min-width: 200px; }
        .filter-group label { font-size: 12px; font-weight: bold; color: #666; text-transform: uppercase; }
        .filter-group select, .filter-group input { padding: 10px; border: 1px solid #ddd; border-radius: 5px; width: 100%; }
        
        .btn-filter { background: #3498db; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: bold; margin: 0;  }
        .btn-reset { background: #95a5a6; color: white; text-decoration: none; border-radius: 5px; font-size: 13px; margin: 0; }
        
        .template-table { width: 100%; border-collapse: collapse; background: #fff; border-radius: 8px; overflow: hidden; }
        .template-table th, .template-table td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #eee; }
        .img-preview { width: 50px; height: 50px; object-fit: cover; border-radius: 4px; border: 1px solid #eee; }
        .layer-badge { display: inline-block; padding: 2px 6px; font-size: 10px; border-radius: 3px; margin-right: 2px; font-weight: bold; }
        .layer-on { background: #e8f5e9; color: #2e7d32; border: 1px solid #c8e6c9; }
        .layer-off { background: #f5f5f5; color: #9e9e9e; border: 1px solid #e0e0e0; }
    </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>Template Library</h2>
        <a href="add-template.php" style="text-decoration:none; background:#2ecc71; color:#fff; padding:10px 20px; border-radius:5px; font-weight:bold;">+ New GVT Template</a>
    </div>

    <form action="" method="GET" class="filter-section">
        <div class="filter-group">
            <label>Keyword Search</label>
            <input type="text" name="search" placeholder="Search ID or Name..." value="<?php echo htmlspecialchars($search); ?>">
        </div>

        <div class="filter-group">
            <label>Category</label>
            <select name="cat" id="filterCat" onchange="loadSubs()">
                <option value="">-- All Categories --</option>
                <?php while($c = $categories->fetch_assoc()): ?>
                    <option value="<?php echo $c['category_name']; ?>" <?php echo ($cat_filter == $c['category_name']) ? 'selected' : ''; ?>>
                        <?php echo $c['category_name']; ?>
                    </option>
                <?php endwhile; ?>
            </select>
        </div>

        <div class="filter-group">
            <label>Sub-Category</label>
            <select name="sub" id="filterSub">
                <option value="">-- All Sub-categories --</option>
                </select>
        </div>

        <div style="display: flex; gap: 10px;">
            <button type="submit" class="btn-filter">Apply Filters</button>
            <button href="manage-templates.php" class="btn-reset">Reset</button>
        </div>
    </form>

    <table class="template-table">
        <thead>
            <tr>
                <th>GVT ID</th>
                <th>Thumbnail</th>
                <th>Classification</th>
                <th>Layers</th>
                <th>Rate</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($result->num_rows > 0): ?>
                <?php while($row = $result->fetch_assoc()): ?>
                <tr>
                    <td><strong><?php echo $row['template_id']; ?></strong></td>
                    <td><img src="<?php echo $row['thumbnail_image']; ?>" class="img-preview"></td>
                    <td>
                        <div style="font-weight:bold;"><?php echo $row['category_name']; ?></div>
                        <div style="font-size:11px; color:#888;"><?php echo $row['sub_category_name']; ?></div>
                    </td>
                    <td>
                        <span class="layer-badge <?php echo !empty($row['layer_0']) ? 'layer-on' : 'layer-off'; ?>">L0</span>
                        <span class="layer-badge <?php echo !empty($row['layer_1']) ? 'layer-on' : 'layer-off'; ?>">L1</span>
                        <span class="layer-badge <?php echo !empty($row['layer_2']) ? 'layer-on' : 'layer-off'; ?>">L2</span>
                        <span class="layer-badge <?php echo !empty($row['layer_3']) ? 'layer-on' : 'layer-off'; ?>">L3</span>
                    </td>
                    <td><strong>₹<?php echo (int)$row['template_rate']; ?></strong></td>
                    <td>
                        <a href="edit-template.php?id=<?php echo $row['id']; ?>" style="color:#3498db; text-decoration:none; font-size:13px;">Edit</a> | 
                        <a href="delete-template.php?id=<?php echo $row['id']; ?>" style="color:#e74c3c; text-decoration:none; font-size:13px;" onclick="return confirm('Delete this GVT template?');">Delete</a>
                    </td>
                </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="6" style="text-align:center; padding:40px; color:#999;">No templates match these filters.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<script>
// Logic to load sub-categories based on category name
async function loadSubs() {
    const catName = document.getElementById('filterCat').value;
    const subSelect = document.getElementById('filterSub');
    const currentSub = "<?php echo $sub_filter; ?>"; // Keep track of current selection
    
    if(!catName) {
        subSelect.innerHTML = '<option value="">-- All Sub-categories --</option>';
        return;
    }

    const res = await fetch(`api/get-subs-by-name.php?cat_name=${encodeURIComponent(catName)}`);
    const data = await res.json();
    
    subSelect.innerHTML = '<option value="">-- All Sub-categories --</option>';
    data.forEach(s => {
        const selected = (currentSub === s.sub_category_name) ? 'selected' : '';
        subSelect.innerHTML += `<option value="${s.sub_category_name}" ${selected}>${s.sub_category_name}</option>`;
    });
}

// Load sub-categories on page load if a category is already selected
window.onload = loadSubs;
</script>

</body>
</html>