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

$cat_id = intval($_POST['cat_id']);
$sub_name = trim($_POST['sub_category_name']);
$status = $_POST['status'] ?? 'Active';
$allowed = $_POST['companies_allowed'];

if(empty($sub_name) || empty($cat_id)) {
    echo json_encode(["success" => false, "message" => "All fields are required"]);
    exit;
}

// 1. Fetch Parent Category Name for Template Directory structure
$cat_res = $conn->query("SELECT category_name FROM categories WHERE id = $cat_id");
if($cat_res->num_rows == 0) {
    echo json_encode(["success" => false, "message" => "Parent category not found."]);
    exit;
}
$cat_data = $cat_res->fetch_assoc();
$parent_folder = preg_replace('/[^A-Za-z0-9_\-]/', '_', $cat_data['category_name']);
$sub_folder = preg_replace('/[^A-Za-z0-9_\-]/', '_', $sub_name);

// 2. Create the Template Directory (where layers will go later)
$template_dir = "../uploads/templates/$parent_folder/$sub_folder/";
if (!is_dir($template_dir)) {
    mkdir($template_dir, 0777, true);
}

// 3. Handle Thumbnail Upload (Targeting the NEW directory)
$thumb_dir = "../uploads/cat_thumbnails/";
if (!is_dir($thumb_dir)) {
    mkdir($thumb_dir, 0777, true);
}

$thumb_db_path = "";
if (!empty($_FILES["thumbnail_image"]["name"])) {
    $file_ext = pathinfo($_FILES["thumbnail_image"]["name"], PATHINFO_EXTENSION);
    // Unique name to avoid overwriting (subcat_id prefix or timestamp)
    $file_name = "subcat_" . time() . "_" . bin2hex(random_bytes(4)) . "." . $file_ext;
    $full_upload_path = $thumb_dir . $file_name;
    
    if (move_uploaded_file($_FILES["thumbnail_image"]["tmp_name"], $full_upload_path)) {
        // Path stored in DB relative to the root for easier <img> src usage
        $thumb_db_path = "uploads/cat_thumbnails/" . $file_name;
    }
}

// 4. Insert into Database
$sql = "INSERT INTO sub_categories (cat_id, sub_category_name, thumbnail_image, status, companies_allowed) VALUES (?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("issss", $cat_id, $sub_name, $thumb_db_path, $status, $allowed);

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

    // 5. 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 sub_category_permissions (sub_cat_id_pk, company_id) VALUES ($sub_cat_pk, $comp_id)");
        }
    }

    echo json_encode(["success" => true, "message" => "Sub-category created successfully!"]);
} else {
    echo json_encode(["success" => false, "message" => "DB Error: " . $conn->error]);
}