<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

header("Content-Type: application/json");
require 'db_config.php';

$data = json_decode(file_get_contents('php://input'), true);

if (!$data || !isset($data['id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid JSON or missing estimate ID.']);
    exit;
}

try {
    $sql = "DELETE FROM estimates WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$data['id']]);

    // Because of 'ON DELETE CASCADE', line items are deleted automatically.
    
    if ($stmt->rowCount()) {
        echo json_encode(['status' => 'success', 'message' => 'Estimate deleted successfully.']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Estimate not found or could not be deleted.']);
    }

} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => 'Database Query Failed: ' . $e->getMessage()]);
}
?>