<?php
header("Content-Type: application/json");
require_once '../config/db.php';

// 1. Capture Data
$id = intval($_POST['id']);
$status = $_POST['status'];
$companies_allowed = $_POST['companies_allowed'];
$allowed_companies = $_POST['allowed_companies'] ?? [];

// 2. Start a Transaction (Optional but recommended for data integrity)
$conn->begin_transaction();

try {
    // 3. Update the main Categories Table
    $sql_cat = "UPDATE categories SET status = ?, companies_allowed = ? WHERE id = ?";
    $stmt_cat = $conn->prepare($sql_cat);
    $stmt_cat->bind_param("ssi", $status, $companies_allowed, $id);
    $stmt_cat->execute();

    // 4. SMART PERMISSION LOGIC
    // We only touch the category_permissions table for THIS specific Category ID
    
    if ($companies_allowed === 'For Selective Companies') {
        // Step A: Wipe old permissions ONLY for this specific category
        $conn->query("DELETE FROM category_permissions WHERE category_id_pk = $id");

        // Step B: If companies were selected, re-insert them
        if (!empty($allowed_companies)) {
            $stmt_perm = $conn->prepare("INSERT INTO category_permissions (category_id_pk, company_id) VALUES (?, ?)");
            foreach ($allowed_companies as $comp_id) {
                $comp_id = intval($comp_id);
                $stmt_perm->bind_param("ii", $id, $comp_id);
                $stmt_perm->execute();
            }
        }
    } else {
        // If the category is set to "For All", clear the specific permissions for this category
        // This ensures the table stays clean and doesn't hold "ghost" permissions for public categories
        $conn->query("DELETE FROM category_permissions WHERE category_id_pk = $id");
    }

    $conn->commit();
    echo json_encode(["success" => true, "message" => "Category and permissions synchronized successfully!"]);

} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(["success" => false, "message" => "Database Error: " . $e->getMessage()]);
}

$conn->close();