<?php
require('../config.php');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header('Content-Type: application/json');

if (!$db) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed']);
    exit;
}

// Read JSON input
$postData = json_decode(file_get_contents('php://input'), true);

// Check if JSON is valid
if (json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid JSON input']);
    exit;
}

// Validate input
if (!isset($_SESSION['client_id']) || empty($_SESSION['client_id']) || !is_numeric($_SESSION['client_id'])) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid or missing clientId']);
    exit;
}

if (!isset($postData['template_id']) || empty($postData['template_id']) || !is_numeric($postData['template_id'])) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid or missing templateId ']);
    exit;
}
if (!isset($postData['template_type']) || empty($postData['template_type'])) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid or missing templateType']);
    exit;
}

// Sanitize input
// $clientId = (int) $postData['clientId'];
$clientId = mysqli_real_escape_string($db, $_SESSION['client_id']);

$template_id = $postData['template_id'];
$template_type = $postData['template_type'];

if ($template_type == "standard") {
    // Start transaction
    mysqli_begin_transaction($db);

    try {
        // Step 1: Delete from template_buttons first
        $deleteButtonsQuery = "DELETE FROM template_buttons WHERE template_id = ?";
        $stmt_buttons = mysqli_prepare($db, $deleteButtonsQuery);
        if (!$stmt_buttons) {
            throw new Exception("Failed to prepare template_buttons delete query.");
        }

        mysqli_stmt_bind_param($stmt_buttons, "i", $template_id);
        mysqli_stmt_execute($stmt_buttons);
        mysqli_stmt_close($stmt_buttons);

        // Step 2: Delete from client_templates
        $deleteTemplateQuery = "DELETE FROM client_templates WHERE id = ? AND client_id = ?";
        $stmt_template = mysqli_prepare($db, $deleteTemplateQuery);
        if (!$stmt_template) {
            throw new Exception("Failed to prepare client_templates delete query.");
        }

        mysqli_stmt_bind_param($stmt_template, "ii", $template_id, $clientId);
        mysqli_stmt_execute($stmt_template);

        if (mysqli_stmt_affected_rows($stmt_template) === 0) {
            mysqli_stmt_close($stmt_template);
            throw new Exception("Template not found or already deleted.");
        }

        mysqli_stmt_close($stmt_template);

        // Commit both deletions
        mysqli_commit($db);

        http_response_code(200);
        echo json_encode([
            'status' => 'success',
            'message' => 'Template deleted successfully'
        ]);
    } catch (Exception $e) {
        // Rollback if anything fails
        mysqli_rollback($db);

        http_response_code(500);
        echo json_encode([
            'status' => 'error',
            'message' => $e->getMessage()
        ]);
    }
} else if ($template_type === "carousel") {
    mysqli_begin_transaction($db);

    try {
        // Step 1: Delete from template_carousel_buttons
        $deleteButtonsQuery = "DELETE FROM template_carousel_buttons WHERE template_id = ?";
        $stmt_buttons = mysqli_prepare($db, $deleteButtonsQuery);
        if (!$stmt_buttons) {
            throw new Exception("Failed to prepare delete query for template_carousel_buttons.");
        }
        mysqli_stmt_bind_param($stmt_buttons, "i", $template_id);
        mysqli_stmt_execute($stmt_buttons);
        mysqli_stmt_close($stmt_buttons);

        // Step 2: Delete from template_carousels
        $deleteCarouselQuery = "DELETE FROM template_carousels WHERE template_id = ?";
        $stmt_carousel = mysqli_prepare($db, $deleteCarouselQuery);
        if (!$stmt_carousel) {
            throw new Exception("Failed to prepare delete query for template_carousels.");
        }
        mysqli_stmt_bind_param($stmt_carousel, "i", $template_id);
        mysqli_stmt_execute($stmt_carousel);
        mysqli_stmt_close($stmt_carousel);

        // Step 3: Delete from client_templates
        $deleteClientTemplateQuery = "DELETE FROM client_templates WHERE id = ? AND client_id = ?";
        $stmt_clientTemplate = mysqli_prepare($db, $deleteClientTemplateQuery);
        if (!$stmt_clientTemplate) {
            throw new Exception("Failed to prepare delete query for client_templates.");
        }
        mysqli_stmt_bind_param($stmt_clientTemplate, "ii", $template_id, $clientId);
        mysqli_stmt_execute($stmt_clientTemplate);

        if (mysqli_stmt_affected_rows($stmt_clientTemplate) === 0) {
            mysqli_stmt_close($stmt_clientTemplate);
            throw new Exception("Template not found or already deleted.");
        }

        mysqli_stmt_close($stmt_clientTemplate);

        // All good — commit transaction
        mysqli_commit($db);

        http_response_code(200);
        echo json_encode([
            'status' => 'success',
            'message' => 'Template deleted successfully.'
        ]);
    } catch (Exception $e) {
        mysqli_rollback($db);
        http_response_code(500);
        echo json_encode([
            'status' => 'error',
            'message' => $e->getMessage()
        ]);
    }
}


// Close database connection
mysqli_close($db);
