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

// 1. Capture Form Data
$cat_name = $_POST['category_name'];
$sub_cat_name = $_POST['sub_category_name'];
$rate = intval($_POST['template_rate']);

// 2. Generate GVT ID based on the highest existing ID
$res = $conn->query("SELECT MAX(id) AS last_id FROM templates");
$row = $res->fetch_assoc();

// If table is empty, $row['last_id'] will be null. We use ?? 0 to start at 1.
$next_numeric_id = ($row['last_id'] ?? 0) + 1;

// Format as GVT0001, GVT0002, etc.
$gvt_id = "GVT" . str_pad($next_numeric_id, 4, '0', STR_PAD_LEFT);


// SAFETY CHECK: If $gvt_id is somehow empty, stop the script
if (empty($gvt_id)) {
    echo json_encode(["success" => false, "message" => "Critical Error: Generated ID is null."]);
    exit;
}

// 3. Prepare Physical Directory
// Creates: ../uploads/templates/Category_Name/Sub_Name/GVT0001/
$cat_f = preg_replace('/[^A-Za-z0-9_\-]/', '_', $cat_name);
$sub_f = preg_replace('/[^A-Za-z0-9_\-]/', '_', $sub_cat_name);
$target_dir = "../uploads/templates/$cat_f/$sub_f/$gvt_id/";

if (!is_dir($target_dir)) {
    mkdir($target_dir, 0777, true);
}

// 4. File Processing Helper
function uploadOptionalFile($fileKey, $targetDir, $prefix) {
    if (isset($_FILES[$fileKey]) && $_FILES[$fileKey]['error'] == 0) {
        $ext = pathinfo($_FILES[$fileKey]['name'], PATHINFO_EXTENSION);
        $filename = $prefix . "." . $ext;
        $fullPath = $targetDir . $filename;
        
        if (move_uploaded_file($_FILES[$fileKey]['tmp_name'], $fullPath)) {
            // Clean path for DB: uploads/templates/...
            return str_replace('../', '', $targetDir) . $filename;
        }
    }
    return ""; 
}

// 5. Upload all layers (Thumbnail + Layer 0-3)
$paths = [];
$paths['thumb'] = uploadOptionalFile('thumbnail_image', $target_dir, 'thumbnail');
$paths['l0']    = uploadOptionalFile('layer_0', $target_dir, 'layer_0');
$paths['l1']    = uploadOptionalFile('layer_1', $target_dir, 'layer_1');
$paths['l2']    = uploadOptionalFile('layer_2', $target_dir, 'layer_2');
$paths['l3']    = uploadOptionalFile('layer_3', $target_dir, 'layer_3');

// 5. THE SQL - We specify exactly 9 columns (excluding 'id' and 'created_at')
$sql = "INSERT INTO templates (
            template_id, 
            category_name, 
            sub_category_name, 
            thumbnail_image, 
            layer_0, 
            layer_1, 
            layer_2, 
            layer_3, 
            template_rate
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

$stmt = $conn->prepare($sql);

if (!$stmt) {
    echo json_encode(["success" => false, "message" => "Prepare failed: " . $conn->error]);
    exit;
}

// 6. BINDING - Ensure there are 8 's' (strings) and 1 'i' (integer)
// Order: gvt_id, cat, sub, thumb, l0, l1, l2, l3, rate
$stmt->bind_param("ssssssssi", 
    $gvt_id, 
    $cat_name, 
    $sub_cat_name, 
    $paths['thumb'], 
    $paths['l0'], 
    $paths['l1'], 
    $paths['l2'], 
    $paths['l3'], 
    $rate
);

if ($stmt->execute()) {
    echo json_encode(["success" => true, "message" => "Template $gvt_id created successfully!"]);
} else {
    echo json_encode(["success" => false, "message" => "SQL Error: " . $stmt->error]);
}