<?php
/**
 * Cancel Service API
 * Handle service reservation cancellations
 */

require_once __DIR__ . '/../config/session.php';
require_once __DIR__ . '/../config/database.php';

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

// Check if user is logged in
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => 'Not authenticated'
    ]);
    exit();
}

$userId = getCurrentUserId();
$serviceId = isset($_POST['id']) ? intval($_POST['id']) : 0;

if (!$serviceId) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Service ID is required'
    ]);
    exit();
}

// Verify the service reservation belongs to the current user
$sql = "SELECT * FROM service_reservations WHERE id = ? AND user_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ii', $serviceId, $userId);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    http_response_code(403);
    echo json_encode([
        'success' => false,
        'message' => 'Service reservation not found or unauthorized'
    ]);
    exit();
}

$service = $result->fetch_assoc();

// Check if service can be cancelled
if ($service['status'] === 'cancelled' || $service['status'] === 'completed') {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'This service reservation cannot be cancelled'
    ]);
    exit();
}

// Cancel the service reservation
try {
    $updateSql = "UPDATE service_reservations SET status = 'cancelled', updated_at = NOW() WHERE id = ?";
    $updateStmt = $conn->prepare($updateSql);
    $updateStmt->bind_param('i', $serviceId);

    if ($updateStmt->execute()) {
        echo json_encode([
            'success' => true,
            'message' => 'Service reservation cancelled successfully'
        ]);
    } else {
        throw new Exception('Failed to cancel service reservation');
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Error cancelling service: ' . $e->getMessage()
    ]);
}
?>
