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

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

$id = intval($_GET['id']);
// Fetch Sub-Category details
$sub_res = $conn->query("SELECT * FROM sub_categories WHERE id = $id");
$sub = $sub_res->fetch_assoc();

if (!$sub) { die("Sub-category not found."); }

// Fetch active parent categories
$categories = $conn->query("SELECT id, category_name FROM categories WHERE status='Active'");

// Fetch current permissions
$allowed_res = $conn->query("SELECT company_id FROM sub_category_permissions WHERE sub_cat_id_pk = $id");
$current_allowed = [];
while($row = $allowed_res->fetch_assoc()) { $current_allowed[] = $row['company_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 Sub-Category | Grovia Admin</title>
    <style>
        :root {
            --sidebar-bg: #3b4368; /* Matches Side_bar_menu_list.png */
            --accent: #3498db;
            --bg-body: #f4f7f6;
            --white: #ffffff;
            --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 Navigation --- */
        .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; }
        
        /* --- Form Card & UI Elements --- */
        .edit-card { background: var(--white); padding: 40px; border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); max-width: 900px; margin: auto; }
        .form-header { border-bottom: 1px solid #eee; margin-bottom: 30px; padding-bottom: 20px; display: flex; justify-content: space-between; align-items: center; }
        
        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; margin-bottom: 20px; }
        input:disabled, select:disabled { background: #f9f9f9; color: #999; cursor: not-allowed; }

        /* --- Asset Management --- */
        .preview-container { text-align: center; padding: 20px; background: #fafafa; border: 2px dashed #eee; border-radius: 10px; margin-bottom: 20px; }
        #thumbPrev { max-width: 180px; max-height: 120px; border-radius: 8px; margin: 0 auto 15px; display: block; box-shadow: 0 4px 10px rgba(0,0,0,0.1); }
        
        /* --- Selective Permission Box --- */
        .selective-box { 
            display: <?php echo ($sub['companies_allowed'] == 'For Selective Companies') ? 'block' : 'none'; ?>; 
            margin-top: 15px; padding: 25px; background: #f8f9fa; border: 2px dashed #d1d8e0; border-radius: 10px; 
        }
        .company-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 12px; 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); }
        
        .btn-update { background: #3498db; color: #fff; border: none; padding: 15px 30px; border-radius: 6px; cursor: pointer; font-weight: bold; width: 100%; font-size: 16px; transition: 0.3s; margin-top: 20px; }
        .btn-update:hover { background: #2980b9; transform: translateY(-2px); }
        
        .alert { padding: 15px; border-radius: 6px; margin-bottom: 25px; display: none; }
        .alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .alert-error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
    </style>
</head>
<body>

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

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

        <form id="editSubCategoryForm" enctype="multipart/form-data">
            <input type="hidden" name="id" value="<?php echo $sub['id']; ?>">

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div>
                    <label>Parent Category (Locked)</label>
                    <select name="cat_id" disabled>
                        <?php while($c = $categories->fetch_assoc()): ?>
                            <option value="<?php echo $c['id']; ?>" <?php echo ($c['id'] == $sub['cat_id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($c['category_name']); ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>
                <div>
                    <label>Sub-Category Name</label>
                    <input type="text" name="sub_category_name" value="<?php echo htmlspecialchars($sub['sub_category_name']); ?>" disabled>
                    <input type="hidden" name="sub_cat_name" value="<?php echo htmlspecialchars($sub['sub_category_name']); ?>">
                </div>
            </div>

            <label>Thumbnail Asset</label>
            <div class="preview-container">
                <img id="thumbPrev" src="<?php echo $sub['thumbnail_image']; ?>" onerror="this.src='assets/img/placeholder.png'">
                <input type="file" name="thumbnail_image" id="thumbInp" accept="image/*" style="font-size: 13px;">
                <p style="font-size: 11px; color: #999; margin-top: 10px;">Recommended size: 500x500px (PNG/JPG)</p>
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div>
                    <label>Status</label>
                    <select name="status">
                        <option value="Active" <?php echo ($sub['status'] == 'Active') ? 'selected' : ''; ?>>Active</option>
                        <option value="Not Active" <?php echo ($sub['status'] == 'Not Active') ? 'selected' : ''; ?>>Not Active</option>
                    </select>
                </div>
                <div>
                    <label>Visibility Scope</label>
                    <select name="companies_allowed" id="subPerm" onchange="toggleSubCompanies()">
                        <option value="For All" <?php echo ($sub['companies_allowed'] == 'For All') ? 'selected' : ''; ?>>Public (Visible to All)</option>
                        <option value="For Selective Companies" <?php echo ($sub['companies_allowed'] == 'For Selective Companies') ? 'selected' : ''; ?>>Restricted (Selective Companies)</option>
                    </select>
                </div>
            </div>

            <div id="subSelectiveBox" class="selective-box">
                <label>Authorize Specific Companies:</label>
                <div class="company-grid">
                    <?php 
                    $companies->data_seek(0); // Reset pointer
                    while($comp = $companies->fetch_assoc()): ?>
                        <label class="company-item">
                            <input type="checkbox" name="allowed_companies[]" value="<?php echo $comp['id']; ?>" 
                            <?php echo in_array($comp['id'], $current_allowed) ? 'checked' : ''; ?>> 
                            <span style="font-size: 13px; font-weight: 500;"><?php echo htmlspecialchars($comp['company_name']); ?></span>
                        </label>
                    <?php endwhile; ?>
                </div>
            </div>

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

<script>
    // Live preview of thumbnail before upload
    document.getElementById('thumbInp').onchange = evt => {
        const [file] = evt.target.files;
        if (file) { document.getElementById('thumbPrev').src = URL.createObjectURL(file); }
    }

    function toggleSubCompanies() {
        const val = document.getElementById('subPerm').value;
        document.getElementById('subSelectiveBox').style.display = (val === 'For Selective Companies') ? 'block' : 'none';
    }

    document.getElementById('editSubCategoryForm').onsubmit = async (e) => {
        e.preventDefault();
        const btn = e.target.querySelector('button');
        btn.innerText = "Processing Changes...";
        btn.disabled = true;

        const res = await fetch("api/update-sub-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 = "Update Sub-Category Data";
        btn.disabled = false;
        window.scrollTo(0,0);
    };
</script>
</body>
</html>