<?php
// ajax/cancel_request.php
session_start();
require_once '../../config/database.php';

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

if (!isset($_SESSION['customer_id']) || !isset($_POST['id'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

$database = new Database();
$db = $database->getConnection();

$request_id = intval($_POST['id']);
$customer_id = $_SESSION['customer_id'];

// Check if request exists and belongs to customer and is in cancellable status
$check_query = "SELECT id, job_status_id FROM service_requests 
                WHERE id = :id AND customer_id = :customer_id AND job_status_id = 1";
$check_stmt = $db->prepare($check_query);
$check_stmt->execute([
    ':id' => $request_id,
    ':customer_id' => $customer_id
]);

if ($check_stmt->rowCount() == 0) {
    echo json_encode(['success' => false, 'message' => 'Request cannot be cancelled']);
    exit;
}

try {
    $db->beginTransaction();
    
    // Update request status to cancelled (assuming 5 is cancelled)
    $update_query = "UPDATE service_requests SET job_status_id = 5 WHERE id = :id";
    $update_stmt = $db->prepare($update_query);
    $update_stmt->execute([':id' => $request_id]);
    
    // Add to status history
    $history_query = "INSERT INTO request_status_history (request_id, job_status_id, notes) 
                      VALUES (:request_id, 5, 'Request cancelled by customer')";
    $history_stmt = $db->prepare($history_query);
    $history_stmt->execute([':request_id' => $request_id]);
    
    $db->commit();
    
    echo json_encode(['success' => true, 'message' => 'Request cancelled successfully']);
} catch (Exception $e) {
    $db->rollBack();
    echo json_encode(['success' => false, 'message' => 'Error cancelling request']);
}