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

// Mock session setup for test
session_start();
$_SESSION['company_id'] = 1;
$_SESSION['user_id'] = 1;

echo "========================================\n";
echo "Payroll Dynamic Configuration Tests\n";
echo "========================================\n";

function runTest($name, $fn) {
    try {
        $fn();
        echo "PASS: $name\n";
    } catch (Exception $e) {
        echo "FAIL: $name - " . $e->getMessage() . "\n";
    }
}

// Ensure clean configurations table for testing
query("DELETE FROM payroll_configurations WHERE company_id = 1");

// Test 1: Saving Configurations
runTest("Save Configurations", function() {
    $company_id = 1;
    $paid_working_days = 22;
    $epf_ee = 8.00;
    $epf_er = 12.00;
    $etf = 3.00;
    $start_day = 26;
    $end_day = 25;
    
    query("
        INSERT INTO payroll_configurations (
            company_id, paid_working_days, epf_employee_percent, epf_employer_percent, etf_percent, cycle_start_day, cycle_end_day
        ) VALUES (?, ?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE 
            paid_working_days = VALUES(paid_working_days),
            epf_employee_percent = VALUES(epf_employee_percent),
            epf_employer_percent = VALUES(epf_employer_percent),
            etf_percent = VALUES(etf_percent),
            cycle_start_day = VALUES(cycle_start_day),
            cycle_end_day = VALUES(cycle_end_day)
    ", [$company_id, $paid_working_days, $epf_ee, $epf_er, $etf, $start_day, $end_day]);
    
    $config = fetch("SELECT * FROM payroll_configurations WHERE company_id = 1");
    if (!$config) {
        throw new Exception("Configuration record not found after insert");
    }
    if (intval($config['paid_working_days']) !== 22) {
        throw new Exception("paid_working_days mismatch: " . $config['paid_working_days']);
    }
    if (floatval($config['epf_employee_percent']) !== 8.00) {
        throw new Exception("epf_employee_percent mismatch: " . $config['epf_employee_percent']);
    }
    if (intval($config['cycle_start_day']) !== 26) {
        throw new Exception("cycle_start_day mismatch: " . $config['cycle_start_day']);
    }
});

// Test 2: Date cycle calculation helper emulation
runTest("Cycle Date Calculations Range", function() {
    $month = 5; // May
    $year = 2026;
    
    // Test for standard cycle (1st to end)
    $startDay = 1;
    $endDay = 0;
    
    if ($startDay == 1) {
        $firstDay = sprintf('%04d-%02d-01', $year, $month);
        $lastDay = date('Y-m-t', strtotime($firstDay));
    }
    
    if ($firstDay !== '2026-05-01' || $lastDay !== '2026-05-31') {
        throw new Exception("Standard month cycle failed: $firstDay to $lastDay");
    }
    
    // Test for custom cycle (26th to 25th)
    $startDay = 26;
    $endDay = 25;
    
    $prevMonth = $month - 1;
    $prevYear = $year;
    if ($prevMonth == 0) {
        $prevMonth = 12;
        $prevYear = $year - 1;
    }
    $firstDay = sprintf('%04d-%02d-%02d', $prevYear, $prevMonth, $startDay);
    $actualEndDay = $endDay > 0 ? $endDay : ($startDay - 1);
    $daysInMonth = intval(date('t', strtotime(sprintf('%04d-%02d-01', $year, $month))));
    if ($actualEndDay > $daysInMonth) {
        $actualEndDay = $daysInMonth;
    }
    $lastDay = sprintf('%04d-%02d-%02d', $year, $month, $actualEndDay);
    
    if ($firstDay !== '2026-04-26' || $lastDay !== '2026-05-25') {
        throw new Exception("Custom cycle 26-25 failed: $firstDay to $lastDay");
    }
});

// Test 3: EPF & ETF Calculations Math
runTest("EPF and ETF calculations matching Sri Lankan labor law", function() {
    $baseSalary = 100000.00; // 100,000 LKR
    $epfEePct = 8.00;
    $epfErPct = 12.00;
    $etfPct = 3.00;
    $allowances = 5000.00;
    $deductions = 2000.00;
    
    $epfEeAmount = round($baseSalary * ($epfEePct / 100), 2); // 8,000 LKR
    $epfErAmount = round($baseSalary * ($epfErPct / 100), 2); // 12,000 LKR
    $etfAmount = round($baseSalary * ($etfPct / 100), 2);    // 3,000 LKR
    
    // Net Salary = Base Salary + Allowances - Deductions - EPF Employee Deduction
    $netSalary = $baseSalary + $allowances - $deductions - $epfEeAmount;
    
    if ($epfEeAmount !== 8000.00) {
        throw new Exception("EPF Employee Amount calculation failed: $epfEeAmount");
    }
    if ($epfErAmount !== 12000.00) {
        throw new Exception("EPF Employer Amount calculation failed: $epfErAmount");
    }
    if ($etfAmount !== 3000.00) {
        throw new Exception("ETF Amount calculation failed: $etfAmount");
    }
    if ($netSalary !== 95000.00) {
        // 100,000 + 5,000 - 2,000 - 8,000 = 95,000
        throw new Exception("Net Salary calculation failed: $netSalary");
    }
});

echo "========================================\n";
echo "All tests finished.\n";
echo "========================================\n";
