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

if (!isset($_GET['id'])) { header("Location: manage-categories.php"); exit; }

$id = intval($_GET['id']);
// Fetch Category details
$cat_res = $conn->query("SELECT * FROM categories WHERE id = $id");
$cat = $cat_res->fetch_assoc();

if (!$cat) { die("Category not found."); }

// Fetch existing permissions
$allowed_res = $conn->query("SELECT * FROM category_permissions WHERE category_id_pk = $id");
$current_allowed = [];
while($row = $allowed_res->fetch_assoc()) { $current_allowed[] = $row['id']; }

// Fetch all companies for the selection grid
$companies = $conn->query("SELECT id, company_name FROM company ORDER BY company_name ASC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Category | Grovia Admin</title>
    <style>
        :root {
            --sidebar-bg: #3b4368;        /* Deep Navy-Purple */
            --accent: #3498db;
            --bg-body: #f4f7f6;
            --border-muted: rgba(255, 255, 255, 0.1);
        }

        body { margin: 0; font-family: 'Segoe UI', sans-serif; background: var(--bg-body); display: flex; }

        /* --- Sidebar & Fixed Header --- */
        .sidebar { width: 280px; background: var(--sidebar-bg); height: 100vh; position: fixed; color: #fff; }
        .logo-area { padding: 30px; text-align: center; border-bottom: 1px solid var(--border-muted); }
        .menu-link { display: flex; justify-content: space-between; padding: 18px 25px; color: #fff; text-decoration: none; border-bottom: 1px solid var(--border-muted); font-size: 16px; }
        .menu-link:hover { background: #4a537d; }
        .chevron { width: 8px; height: 8px; border-top: 2px solid #fff; border-right: 2px solid #fff; transform: rotate(45deg); opacity: 0.6; }

        .main-content { margin-left: 280px; width: 100%; padding: 40px; }
        .top-bar { height: 70px; background: #fff; display: flex; justify-content: flex-end; align-items: center; padding: 0 30px; margin-bottom: 30px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }

        /* --- Card & Form --- */
        .edit-card { background: #fff; padding: 40px; border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); max-width: 900px; margin: auto; }
        .form-header { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #eee; padding-bottom: 20px; margin-bottom: 30px; }
        
        label { display: block; margin-bottom: 8px; font-weight: 600; color: #666; font-size: 13px; text-transform: uppercase; }
        input[type="text"], select { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; background: #fff; }
        input:disabled { background: #f9f9f9; color: #999; cursor: not-allowed; }

        /* --- Selective Permission Box --- */
        .selective-box { 
            display: <?php echo ($cat['companies_allowed'] == 'For Selective Companies') ? 'block' : 'none'; ?>; 
            margin-top: 25px; padding: 25px; background: #f8f9fa; border: 2px dashed #d1d8e0; border-radius: 10px; 
        }
        .company-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 15px; margin-top: 15px; }
        .company-item { background: #fff; padding: 10px 15px; border: 1px solid #eee; border-radius: 6px; display: flex; align-items: center; gap: 10px; cursor: pointer; transition: 0.2s; }
        .company-item:hover { border-color: var(--accent); }
        .company-item input { width: 18px; height: 18px; cursor: pointer; }

        .btn-update { background: #2ecc71; color: #fff; border: none; padding: 15px 30px; border-radius: 6px; cursor: pointer; font-weight: bold; width: 100%; margin-top: 30px; font-size: 16px; transition: 0.3s; }
        .btn-update:hover { background: #27ae60; transform: translateY(-2px); }
        
        .alert { padding: 15px; border-radius: 6px; margin-bottom: 20px; display: none; }
        .alert-success { background: #d4edda; color: #155724; }
    </style>
</head>
<body>

<?php include 'top-bar.php'; ?>
<div class="sidebar">
    <div class="logo-area"><h2>GROVIA</h2></div>
    <a href="manage-categories.php" class="menu-link">← Back to Categories</a>
</div>

<div class="main-content">
        <div class="edit-card">
        <div class="form-header">
            <h2 style="margin:0;">Edit Category Assets</h2>
            <span style="color:#aaa; font-family:monospace; font-weight:bold;"><?php echo $cat['category_id']; ?></span>
        </div>
        
        <div id="msg" class="alert"></div>

        <form id="editCategoryForm">
            <input type="hidden" name="id" value="<?php echo $cat['id']; ?>">
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
                <div>
                    <label>Category Title</label>
                    <input type="text" value="<?php echo htmlspecialchars($cat['category_name']); ?>" disabled>
                </div>
                <div>
                    <label>Active Status</label>
                    <select name="status">
                        <option value="Active" <?php if($cat['status'] == 'Active') echo 'selected'; ?>>Active</option>
                        <option value="Not Active" <?php if($cat['status'] == 'Not Active') echo 'selected'; ?>>Not Active</option>
                    </select>
                </div>
            </div>

            <label>Permission Visibility</label>
            <select name="companies_allowed" id="permissionSelect" onchange="toggleCompanyList()">
                <option value="For All" <?php if($cat['companies_allowed'] == 'For All') echo 'selected'; ?>>Public (Visible to All Companies)</option>
                <option value="For Selective Companies" <?php if($cat['companies_allowed'] == 'For Selective Companies') echo 'selected'; ?>>Restricted (Only Selective Companies)</option>
            </select>

            <div id="selectiveBox" class="selective-box">
                <label>Select Authorized Companies:</label>
                <div class="company-grid">
                    <?php while($comp = $companies->fetch_assoc()): ?>
                        <label class="company-item">
                            <input type="checkbox" name="allowed_companies[]" value="<?php echo $comp['id']; ?>" 
                            <?php if(in_array($comp['id'], $current_allowed)) echo 'checked'; ?>> 
                            <span style="font-size: 14px; font-weight: 500; color: #444;"><?php echo htmlspecialchars($comp['company_name']); ?></span>
                        </label>
                    <?php endwhile; ?>
                </div>
            </div>

            <button type="submit" class="btn-update">Update Category Settings</button>
        </form>
    </div>
</div>

<script>
function toggleCompanyList() {
    const select = document.getElementById('permissionSelect');
    const box = document.getElementById('selectiveBox');
    box.style.display = (select.value === 'For Selective Companies') ? 'block' : 'none';
}

document.getElementById('editCategoryForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const btn = e.target.querySelector('button');
    btn.innerText = "Updating...";
    btn.disabled = true;

    const res = await fetch("api/update-category.php", {
        method: "POST",
        body: new FormData(e.target)
    });
    
    const data = await res.json();
    const msg = document.getElementById('msg');
    msg.style.display = "block";
    msg.className = "alert " + (data.success ? "alert-success" : "alert-error");
    msg.innerText = data.message;
    
    btn.innerText = "Synchronize Category Settings";
    btn.disabled = false;
    window.scrollTo(0,0);
});
</script>
</body>
</html>