<?php
/**
 * Client Access Control Functions
 * Check payment status and control access based on subscription
 */

/**
 * Check if a client has paid for the current year
 * @param mysqli $conn Database connection
 * @param int $client_id Client ID
 * @return array ['is_paid' => bool, 'last_paid_year' => int, 'status' => string]
 */
function checkClientPaymentStatus($conn, $client_id) {
    $current_year = date('Y');

    // Get client's access status
    $client_result = mysqli_query($conn, "SELECT access_status FROM clients WHERE id = $client_id");
    if(mysqli_num_rows($client_result) == 0) {
        return ['is_paid' => false, 'last_paid_year' => null, 'status' => 'not_found'];
    }

    $client = mysqli_fetch_assoc($client_result);

    // Check if suspended by admin
    if($client['access_status'] == 'suspended') {
        return ['is_paid' => false, 'last_paid_year' => null, 'status' => 'suspended'];
    }

    // Get last confirmed payment year
    $payment_result = mysqli_query($conn, "
        SELECT MAX(payment_year) as last_paid_year
        FROM client_payments
        WHERE client_id = $client_id AND status = 'confirmed'
    ");
    $payment = mysqli_fetch_assoc($payment_result);
    $last_paid_year = $payment['last_paid_year'];

    // Get grace period setting
    $settings_result = mysqli_query($conn, "SELECT setting_value FROM payment_settings WHERE setting_key = 'grace_period_days'");
    $grace_period = 30;
    if($settings = mysqli_fetch_assoc($settings_result)) {
        $grace_period = intval($settings['setting_value']);
    }

    // Check if paid for current year
    if($last_paid_year >= $current_year) {
        return ['is_paid' => true, 'last_paid_year' => $last_paid_year, 'status' => 'active'];
    }

    // Check grace period (from start of current year)
    $grace_end_date = date('Y-m-d', strtotime("$current_year-01-01 + $grace_period days"));
    if(date('Y-m-d') <= $grace_end_date) {
        return ['is_paid' => false, 'last_paid_year' => $last_paid_year, 'status' => 'grace_period', 'grace_end' => $grace_end_date];
    }

    // Expired
    return ['is_paid' => false, 'last_paid_year' => $last_paid_year, 'status' => 'expired'];
}

/**
 * Check if user can access a specific land (based on ownership and client payment status)
 * @param mysqli $conn Database connection
 * @param int $land_id Land ID
 * @param int $user_id User ID trying to access
 * @param string $user_role User's role
 * @return array ['can_access' => bool, 'reason' => string, 'client_status' => array|null]
 */
function canAccessLand($conn, $land_id, $user_id, $user_role) {
    // Get land info
    $land_result = mysqli_query($conn, "SELECT l.*, c.broker_id
                                         FROM lands l
                                         LEFT JOIN clients c ON l.client_id = c.id
                                         WHERE l.id = $land_id");

    if(mysqli_num_rows($land_result) == 0) {
        return ['can_access' => false, 'reason' => 'Land not found', 'client_status' => null];
    }

    $land = mysqli_fetch_assoc($land_result);

    // Admin can access everything
    if($user_role == 'admin') {
        if($land['client_id']) {
            $client_status = checkClientPaymentStatus($conn, $land['client_id']);
            return ['can_access' => true, 'reason' => 'Admin access', 'client_status' => $client_status];
        }
        return ['can_access' => true, 'reason' => 'Admin access', 'client_status' => null];
    }

    // Check if user owns the land directly
    if($land['user_id'] == $user_id) {
        if($land['client_id']) {
            $client_status = checkClientPaymentStatus($conn, $land['client_id']);
            // Broker can still access, but we return client status for display
            return ['can_access' => true, 'reason' => 'Owner', 'client_status' => $client_status];
        }
        return ['can_access' => true, 'reason' => 'Owner', 'client_status' => null];
    }

    // Check if user is the broker for this client
    if($land['broker_id'] == $user_id) {
        if($land['client_id']) {
            $client_status = checkClientPaymentStatus($conn, $land['client_id']);
            return ['can_access' => true, 'reason' => 'Broker', 'client_status' => $client_status];
        }
        return ['can_access' => true, 'reason' => 'Broker', 'client_status' => null];
    }

    return ['can_access' => false, 'reason' => 'Access denied', 'client_status' => null];
}

/**
 * Auto-update client status based on payment (run periodically or on login)
 * @param mysqli $conn Database connection
 */
function updateExpiredClients($conn) {
    $current_year = date('Y');

    // Get grace period
    $settings_result = mysqli_query($conn, "SELECT setting_value FROM payment_settings WHERE setting_key = 'grace_period_days'");
    $grace_period = 30;
    if($settings = mysqli_fetch_assoc($settings_result)) {
        $grace_period = intval($settings['setting_value']);
    }

    $grace_end_date = date('Y-m-d', strtotime("$current_year-01-01 + $grace_period days"));

    // Only auto-expire after grace period
    if(date('Y-m-d') > $grace_end_date) {
        // Find clients without payment for current year
        $sql = "UPDATE clients c
                SET c.access_status = 'expired'
                WHERE c.access_status = 'active'
                AND c.id NOT IN (
                    SELECT DISTINCT client_id FROM client_payments
                    WHERE payment_year >= $current_year AND status = 'confirmed'
                )";
        mysqli_query($conn, $sql);
    }
}

/**
 * Get yearly fee amount from settings
 * @param mysqli $conn Database connection
 * @return float
 */
function getYearlyFee($conn) {
    $result = mysqli_query($conn, "SELECT setting_value FROM payment_settings WHERE setting_key = 'yearly_fee'");
    if($row = mysqli_fetch_assoc($result)) {
        return floatval($row['setting_value']);
    }
    return 50000; // Default
}
?>
