<?php
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

// Simulate a logged-in session for testing
$_SESSION['user_id'] = 1; // Admin user
$_SESSION['company_id'] = 1;
$_SESSION['user_role'] = 'owner';

try {
    echo "Simulating api/leaves.php company_records action...\n";

    // 1. Let's inspect active company details
    $company_id = $_SESSION['company_id'];
    echo "Using Company ID: $company_id\n";

    // 2. Fetch employees count
    $employees = fetchAll("SELECT id, name FROM employees WHERE company_id = ?", [$company_id]);
    echo "Found " . count($employees) . " employees.\n";

    // 3. Simulate the exact case code in leaves.php
    $search = '';
    $filter_start_date = '';
    $filter_end_date = '';

    // Simulate endpoint query
    $queryStr = "SELECT id, name FROM employees WHERE company_id = ?";
    $params = [$company_id];
    $employees_res = fetchAll($queryStr, $params);

    echo "Fetched Employees List:\n";
    foreach ($employees_res as $emp) {
        echo "  - [ID: {$emp['id']}] {$emp['name']}\n";
        
        // Fetch remaining balances
        $leaveTypes = ['casual', 'annual', 'sick', 'maternity', 'paternity'];
        echo "    Leave balances:\n";
        foreach ($leaveTypes as $type) {
            // Re-create the logic of getLeaveBalance
            $config = fetch("SELECT days_per_year FROM leave_configurations WHERE company_id = ? AND leave_type = ?", [$company_id, $type]);
            $limit = $config ? intval($config['days_per_year']) : 0;
            
            $yearStart = date('Y') . '-01-01';
            $yearEnd = date('Y') . '-12-31';
            $requests = fetchAll("
                SELECT duration_type, start_date, end_date 
                FROM leave_requests 
                WHERE employee_id = ? AND company_id = ? AND leave_type = ? AND status = 'approved'
                  AND start_date BETWEEN ? AND ?
            ", [$emp['id'], $company_id, $type, $yearStart, $yearEnd]);
            
            $taken = 0.0;
            foreach ($requests as $r) {
                // Approximate calculation (no public holidays for simple simulation)
                if ($r['duration_type'] === 'half_day') {
                    $taken += 0.5;
                } else if ($r['duration_type'] === 'short_leave') {
                    $taken += 0.25;
                } else {
                    $start = new DateTime($r['start_date']);
                    $end = new DateTime($r['end_date']);
                    $taken += $start->diff($end)->days + 1;
                }
            }
            $remaining = max(0, $limit - $taken);
            echo "      * $type: limit=$limit, taken=$taken, remaining=$remaining\n";
        }
    }

    echo "Simulation complete! Endpoint queries executed successfully.\n";

} catch (Exception $e) {
    echo "Error occurred: " . $e->getMessage() . "\n";
    exit(1);
}
