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

$name = trim($_POST['category_name']);
$status = $_POST['status'];
$allowed = $_POST['companies_allowed'];

if(empty($name)) {
    echo json_encode(["success" => false, "message" => "Name is required"]);
    exit;
}

// 1. Prepare Folder Path
// We replace spaces/special chars with underscores to keep it URL-safe
$folder_name = preg_replace('/[^A-Za-z0-9_\-]/', '_', $name);
$target_path = "../uploads/templates/" . $folder_name;

// 2. Create the Directory if it doesn't exist
if (!is_dir($target_path)) {
    if (!mkdir($target_path, 0777, true)) {
        echo json_encode(["success" => false, "message" => "Failed to create category folder on server."]);
        exit;
    }
}

// 3. Insert Category into Database
$sql = "INSERT INTO categories (category_name, status, companies_allowed) VALUES (?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $name, $status, $allowed);

if ($stmt->execute()) {
    $cat_id_pk = $conn->insert_id;

    // 4. Handle Selective Permissions
    if ($allowed === 'For Selective Companies' && isset($_POST['allowed_companies'])) {
        foreach ($_POST['allowed_companies'] as $comp_id) {
            $comp_id = intval($comp_id);
            $conn->query("INSERT INTO category_permissions (category_id_pk, company_id) VALUES ($cat_id_pk, $comp_id)");
        }
    }

    echo json_encode([
        "success" => true, 
        "message" => "Category created and folder '$folder_name' is ready!"
    ]);
} else {
    // If DB fails, we could optionally remove the created folder (Rollback)
    echo json_encode(["success" => false, "message" => "Database error: " . $conn->error]);
}