<?php
define('ROVO_APP', true);
require_once '../../config.php';
require_once '../../Auth.php';

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

if (!$auth->isLoggedIn() || $auth->isAdmin()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

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

$current_user = $auth->getCurrentUser();
$application_id = isset($_POST['application_id']) ? (int)$_POST['application_id'] : 0;

// Verify application belongs to user
$sql = "SELECT * FROM rental_applications WHERE id = ? AND user_id = ?";
$application = $db->fetchOne($sql, [$application_id, $current_user['id']]);

if (!$application) {
    echo json_encode(['success' => false, 'message' => 'Application not found']);
    exit;
}

// Check if application can be cancelled
if ($application['status'] !== 'pending') {
    echo json_encode(['success' => false, 'message' => 'Only pending applications can be cancelled']);
    exit;
}

try {
    // Update application status
    $sql = "UPDATE rental_applications SET status = 'cancelled', updated_at = NOW() WHERE id = ?";
    $db->execute($sql, [$application_id]);
    
    // Log activity
    $sql = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address, user_agent) 
            VALUES (?, 'application_cancel', 'rental_application', ?, ?, ?, ?)";
    $db->execute($sql, [
        $current_user['id'],
        $application_id,
        "Application {$application['application_number']} cancelled by user",
        Security::getClientIP(),
        $_SERVER['HTTP_USER_AGENT'] ?? ''
    ]);
    
    // Create notification for admin
    $sql = "INSERT INTO notifications (user_id, type, title, message, link) 
            VALUES (1, 'warning', 'Application Cancelled', 'Application {$application['application_number']} was cancelled by user', '/admin/rental-applications.php?view={$application_id}')";
    $db->execute($sql);
    
    echo json_encode([
        'success' => true,
        'message' => 'Application cancelled successfully'
    ]);
    
} catch (Exception $e) {
    error_log("Cancel application error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Failed to cancel application. Please try again.'
    ]);
}
?>