<?php
session_start();
session_write_close();
ini_set('display_errors', '0');
error_reporting(E_ALL);
ob_start();
date_default_timezone_set('Africa/Lagos');
require __DIR__ . '/../config.php';
require __DIR__ . '/includes/auth_init.php';

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

if (!$isAdmin && !$isManager) {
    http_response_code(403);
    ob_clean();
    echo json_encode(['error' => 'You do not have permission to view payroll reports.']);
    exit;
}

$action = $_REQUEST['action'] ?? '';

if ($action === 'load_report') {
    $cycleId = (int) ($_GET['cycle_id'] ?? 0);
    $groupId = isset($_GET['group_id']) && $_GET['group_id'] !== '' ? (int) $_GET['group_id'] : null;

    $stmt = $conn->prepare("SELECT * FROM payroll_cycles WHERE id = ?");
    $stmt->bind_param('i', $cycleId);
    $stmt->execute();
    $cycle = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$cycle) {
        http_response_code(404);
        ob_clean();
        echo json_encode(['error' => 'Payroll cycle not found.']);
        exit;
    }

    // Which statutory deductions are actually switched on right now (Settings).
    // PAYE has no on/off toggle in this system, so it always shows.
    $statutoryFlags = ['pension_employee_pct' => 1, 'nhf_pct' => 1, 'nhis_pct' => 1];
    $flagRes = $conn->query("SELECT setting_key, is_active FROM statutory_settings WHERE setting_key IN ('pension_employee_pct','nhf_pct','nhis_pct')");
    while ($fr = $flagRes->fetch_assoc()) {
        $statutoryFlags[$fr['setting_key']] = (int) $fr['is_active'];
    }

    require_once __DIR__ . '/includes/PayrollEngine.php';
    $engine = new PayrollEngine($conn);

    $sql = "
        SELECT pr.*, e.name, e.employee_no, e.designation, g.name as group_name
        FROM payroll_payslip_runs pr
        JOIN employees e ON e.id = pr.employee_id
        LEFT JOIN groups g ON g.id = pr.group_id
        WHERE pr.payroll_cycle_id = $cycleId
    ";
    if ($isManager && !$isAdmin) {
        $sql .= " AND e.department_id = " . (int) $userDeptId;
    }
    if ($groupId) {
        $sql .= " AND pr.group_id = $groupId";
    }
    $sql .= " ORDER BY g.name ASC, e.name ASC";
    $res = $conn->query($sql);

    $rows = [];
    $totals = ['gross' => 0, 'paye' => 0, 'pension' => 0, 'nhf' => 0, 'nhis' => 0, 'absent_days' => 0, 'days_worked' => 0, 'lop' => 0, 'surcharge' => 0, 'deductions' => 0, 'net' => 0];

    while ($r = $res->fetch_assoc()) {
        // Days worked recalculated live from the cycle's own start_date/end_date
        // (not calendar month), so this stays accurate for custom cycles too.
        $attendance = $engine->calculateAttendanceForRange((int) $r['employee_id'], $cycle['start_date'], $cycle['end_date']);

        $rows[] = [
            'name' => $r['name'],
            'employee_no' => $r['employee_no'],
            'designation' => $r['designation'],
            'group_name' => $r['group_name'],
            'gross_earnings' => (float) $r['gross_earnings'],
            'days_worked' => (int) $attendance['days_worked'],
            'absent_days' => (float) $r['absent_days'],
            'lop_amount' => (float) $r['lop_amount'],
            'surcharge_amount' => (float) $r['surcharge_amount'],
            'paye_tax' => (float) $r['paye_tax'],
            'pension_employee' => (float) $r['pension_employee'],
            'nhf' => (float) $r['nhf'],
            'nhis' => (float) $r['nhis'],
            'total_deductions' => (float) $r['total_deductions'],
            'net_pay' => (float) $r['net_pay'],
        ];
        $totals['gross'] += $r['gross_earnings'];
        $totals['paye'] += $r['paye_tax'];
        $totals['pension'] += $r['pension_employee'];
        $totals['nhf'] += $r['nhf'];
        $totals['nhis'] += $r['nhis'];
        $totals['absent_days'] += $r['absent_days'];
        $totals['days_worked'] += $attendance['days_worked'];
        $totals['lop'] += $r['lop_amount'];
        $totals['surcharge'] += $r['surcharge_amount'];
        $totals['deductions'] += $r['total_deductions'];
        $totals['net'] += $r['net_pay'];
    }

    ob_clean();

    echo json_encode([
        'cycle' => [
            'id' => (int) $cycle['id'],
            'name' => $cycle['name'],
            'start_date' => $cycle['start_date'],
            'end_date' => $cycle['end_date'],
        ],
        'columns' => [
            'show_pension' => (bool) $statutoryFlags['pension_employee_pct'],
            'show_nhf' => (bool) $statutoryFlags['nhf_pct'],
            'show_nhis' => (bool) $statutoryFlags['nhis_pct'],
        ],
        'rows' => $rows,
        'totals' => $totals,
    ]);
    exit;
}

http_response_code(400);
ob_clean();
echo json_encode(['error' => 'Unknown action.']);
