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

$id = intval($_POST['id']);
$rate = intval($_POST['template_rate']);

// 1. Fetch current data to get the existing folder path
$query = "SELECT * FROM templates WHERE id = $id";
$res = $conn->query($query);
$current = $res->fetch_assoc();

if (!$current) {
    echo json_encode(["success" => false, "message" => "Template record not found."]);
    exit;
}

// 2. Determine target directory based on existing layer_0 path
$target_dir = "../" . dirname($current['layer_0']) . "/";

// 2. Modified Helper to handle Upload OR Delete
function updateFile($fileKey, $targetDir, $prefix, $oldPath) {
    $deleteFlag = $_POST['delete_' . $fileKey] ?? '0';

    // Scenario A: New File Uploaded
    if (isset($_FILES[$fileKey]) && $_FILES[$fileKey]['error'] == 0) {
        if (!empty($oldPath) && file_exists("../../" . $oldPath)) {
            unlink("../../" . $oldPath);
        }
        $ext = pathinfo($_FILES[$fileKey]['name'], PATHINFO_EXTENSION);
        $filename = $prefix . "." . $ext;
        if (move_uploaded_file($_FILES[$fileKey]['tmp_name'], $targetDir . $filename)) {
            return str_replace('../../', '', $targetDir) . $filename;
        }
    } 
    
    // Scenario B: Delete Button was Clicked
    if ($deleteFlag === '1') {
        if (!empty($oldPath) && file_exists("../../" . $oldPath)) {
            unlink("../../" . $oldPath);
        }
        return ""; // Return empty string to clear DB
    }

    // Scenario C: No change
    return $oldPath;
}

// 4. Process all potential updates
$new_thumb = updateFile('thumbnail_image', $target_dir, 'thumbnail', $current['thumbnail_image']);
$new_l0 = updateFile('layer_0', $target_dir, 'layer_0', $current['layer_0']);
$new_l1 = updateFile('layer_1', $target_dir, 'layer_1', $current['layer_1']);
$new_l2 = updateFile('layer_2', $target_dir, 'layer_2', $current['layer_2']);
$new_l3 = updateFile('layer_3', $target_dir, 'layer_3', $current['layer_3']);

// 5. Update Database
$sql = "UPDATE templates SET 
        thumbnail_image = ?, 
        layer_0 = ?, 
        layer_1 = ?, 
        layer_2 = ?, 
        layer_3 = ?, 
        template_rate = ? 
        WHERE id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("sssssii", 
    $new_thumb, 
    $new_l0, 
    $new_l1, 
    $new_l2, 
    $new_l3, 
    $rate, 
    $id
);

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