<?php
require_once '../auth.php';
ensureAdminAjaxAuth();
// ajax/delete_request.php
require_once '../../config/database.php';

header('Content-Type: application/json');

if($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    
    if(!$id) {
        echo json_encode(['success' => false, 'message' => 'Request ID required']);
        exit;
    }
    
    // First delete history records
    $history_query = "DELETE FROM request_status_history WHERE request_id = :id";
    $history_stmt = $db->prepare($history_query);
    $history_stmt->execute([':id' => $id]);
    
    // Then delete the request
    $query = "DELETE FROM service_requests WHERE id = :id";
    $stmt = $db->prepare($query);
    $result = $stmt->execute([':id' => $id]);
    
    if($result) {
        echo json_encode(['success' => true, 'message' => 'Request deleted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error deleting request']);
    }
    
} catch(Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>