<?php
include 'db.php';
$month = $_GET['month'] ?? date('Y-m');
$year  = $_GET['year'] ?? date('Y');

// Fetch payroll + employee info for this month
$sql = "SELECT p.*, e.name AS employee_name, e.id AS emp_id
        FROM payrolls p
        JOIN employees e ON p.employee_id = e.id
        WHERE p.payroll_month = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $month);
$stmt->execute();
$res = $stmt->get_result();

// Collect payroll rows
$data = [];
while ($row = $res->fetch_assoc()) {
    // Payments/advances for this employee in the month
    $start = $month . "-01";
    $end = date("Y-m-t", strtotime($start));
    $payQ = $conn->prepare("SELECT SUM(amount) AS total_adv FROM payments WHERE employee_id=? AND payment_date BETWEEN ? AND ?");
    $payQ->bind_param("iss", $row['emp_id'], $start, $end);
    $payQ->execute();
    $payRes = $payQ->get_result()->fetch_assoc();
    $advances = $payRes['total_adv'] ?? 0;

    $row['advances'] = $advances;
    $row['grand_total'] = $row['net_pay'] + $advances;
    $data[] = $row;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Payroll Detail - <?= htmlspecialchars($month) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container py-4">
    <h2 class="mb-4">👥 Payroll Details (<?= htmlspecialchars($month) ?>)</h2>
    <a href="payroll_summary.php?year=<?= urlencode($year) ?>" class="btn btn-secondary mb-3">⬅ Back to Summary</a>

    <table class="table table-bordered">
        <thead class="table-dark">
            <tr>
                <th>Employee</th>
                <th>Net Salary (RM)</th>
                <th>Payments / Advances (RM)</th>
                <th>Total (RM)</th>
                <th>Payslip</th>
            </tr>
        </thead>
        <tbody>
            <?php if (!empty($data)): ?>
                <?php foreach ($data as $row): ?>
                <tr>
                    <td><?= htmlspecialchars($row['employee_name']) ?></td>
                    <td class="text-end">RM <?= number_format($row['net_pay'],2) ?></td>
                    <td class="text-end">RM <?= number_format($row['advances'],2) ?></td>
                    <td class="text-end fw-bold">RM <?= number_format($row['grand_total'],2) ?></td>
                    <td><a href="payslip.php?id=<?= $row['id'] ?>" target="_blank" class="btn btn-sm btn-outline-primary">📄 View Payslip</a></td>
                </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr><td colspan="5" class="text-center">No records found</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</body>
</html>
