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

$id = (int)($_GET['id'] ?? 0);

$stmt = db()->prepare("SELECT * FROM payroll_periods WHERE id = ? LIMIT 1");
$stmt->execute([$id]);
$period = $stmt->fetch();

if (!$period) {
    redirect('payroll/index.php');
}

$startDate = $period['start_date'];
$endDate   = $period['end_date'];

$stmtItems = db()->prepare("
    SELECT pi.*, e.salary
    FROM payroll_items pi
    INNER JOIN employees e ON e.id = pi.employee_id
    WHERE pi.period_id = ?
");
$stmtItems->execute([$id]);
$items = $stmtItems->fetchAll();

foreach ($items as $item) {
    $employeeId = (int)$item['employee_id'];
    $baseSalary = (float)$item['base_salary'];

    $extras = (float)$item['extras'];
    $discounts = (float)$item['discounts'];

    $stmtAdv = db()->prepare("
        SELECT COALESCE(SUM(amount),0)
        FROM salary_advances
        WHERE employee_id = ?
          AND advance_date BETWEEN ? AND ?
          AND status = 'Activo'
    ");
    $stmtAdv->execute([$employeeId, $startDate, $endDate]);
    $advances = (float)$stmtAdv->fetchColumn();

    $netPay = $baseSalary + $extras - $discounts - $advances;

    if ($netPay < 0) {
        $netPay = 0;
    }

    $stmtUpd = db()->prepare("
        UPDATE payroll_items
        SET advances = ?, net_pay = ?
        WHERE id = ?
    ");
    $stmtUpd->execute([$advances, $netPay, $item['id']]);
}

db()->prepare("UPDATE payroll_periods SET status = 'Cerrado' WHERE id = ?")->execute([$id]);

redirect('payroll/view.php?id=' . $id);