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

// 1. CAPTURE DATA
$id = intval($_POST['id'] ?? 0);
$sub_name = $_POST['sub_cat_name'] ?? ''; // Fixed: Added null coalescing
$status = $_POST['status'] ?? 'Active';
$companies_allowed = $_POST['companies_allowed'] ?? 'For All';
$allowed_companies = $_POST['allowed_companies'] ?? [];

// 2. FETCH CURRENT DATA
$curr_res = $conn->query("SELECT thumbnail_image FROM sub_categories WHERE id = $id");
$curr = $curr_res->fetch_assoc();
$new_thumb_path = $curr['thumbnail_image'];

// 3. HANDLE FILE UPLOAD
if (isset($_FILES['thumbnail_image']) && $_FILES['thumbnail_image']['error'] == 0) {
    // Check if directory exists, if not create it
    $upload_dir = "../uploads/thumbnails/";
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }

    // Delete old file if it exists
    if (!empty($curr['thumbnail_image']) && file_exists("../" . $curr['thumbnail_image'])) {
        @unlink("../" . $curr['thumbnail_image']);
    }

    $ext = pathinfo($_FILES['thumbnail_image']['name'], PATHINFO_EXTENSION);
    $filename = "sub_" . time() . "." . $ext;
    $target = $upload_dir . $filename;
    
    // Fixed: Corrected pathing for move_uploaded_file
    if (move_uploaded_file($_FILES['thumbnail_image']['tmp_name'], $target)) {
        $new_thumb_path = "uploads/thumbnails/" . $filename;
    }
}

// 4. DATABASE TRANSACTION
$conn->begin_transaction();

try {
    // Fixed: Changed variable name from $sql_cat to $sql_sub to match usage
    $sql_sub = "UPDATE sub_categories SET sub_category_name = ?, thumbnail_image = ?, status = ?, companies_allowed = ? WHERE id = ?";
    $stmt_sub = $conn->prepare($sql_sub);
    $stmt_sub->bind_param("ssssi", $sub_name, $new_thumb_path, $status, $companies_allowed, $id);
    $stmt_sub->execute();

    // Sync Permissions
    $conn->query("DELETE FROM sub_category_permissions WHERE sub_cat_id_pk = $id");

    if ($companies_allowed === 'For Selective Companies' && !empty($allowed_companies)) {
        $stmt_perm = $conn->prepare("INSERT INTO sub_category_permissions (sub_cat_id_pk, company_id) VALUES (?, ?)");
        foreach ($allowed_companies as $comp_id) {
            $c_id = intval($comp_id);
            $stmt_perm->bind_param("ii", $id, $c_id);
            $stmt_perm->execute();
        }
    }

    $conn->commit();
    echo json_encode(["success" => true, "message" => "Sub-category updated successfully!"]);

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

$conn->close();