<?php
require_once __DIR__ . '/../../models/Database.php';
use Models\Database;

session_start();
if (!isset($_SESSION['user']['id'])) {
    header('Location: /../views/auth/login.php');
    exit();
}

$pdo = Database::getInstance()->getConnection();
$where = [];
$params = [];

if (!empty($_GET['employee_id'])) {
    $where[] = 'p.employee_id = ?';
    $params[] = $_GET['employee_id'];
}
if (!empty($_GET['period'])) {
    $where[] = 'DATE_FORMAT(p.period, "%Y-%m") = ?';
    $params[] = $_GET['period'];
}

$sql = "SELECT p.id, p.period, p.net_final, p.validated, e.first_name, e.last_name
        FROM payslips p
        JOIN employees e ON p.employee_id = e.id";

if ($where) {
    $sql .= ' WHERE ' . implode(' AND ', $where);
}

$sql .= " ORDER BY p.period DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$payslips = $stmt->fetchAll();

?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Fiches de paie</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-5">
    <h2 class="mb-4">Liste des fiches de paie</h2>
    <a href="/payslips/create" class="btn btn-success mb-3">➕ Nouvelle fiche</a>
    <form method="GET" class="row g-2 mb-4">
        <div class="col-md-4">
            <select name="employee_id" class="form-select">
                <option value="">Tous les employés</option>
                <?php
                $emps = $pdo->query("SELECT id, first_name, last_name FROM employees ORDER BY last_name")->fetchAll();
                foreach ($emps as $emp) {
                    $selected = ($_GET['employee_id'] ?? '') == $emp['id'] ? 'selected' : '';
                    echo "<option value=\"{$emp['id']}\" $selected>{$emp['last_name']} {$emp['first_name']}</option>";
                }
                ?>
            </select>
        </div>
        <div class="col-md-4">
            <input type="month" name="period" class="form-control" value="<?= $_GET['period'] ?? '' ?>">
        </div>
        <div class="col-md-4">
            <button type="submit" class="btn btn-primary">🔍 Filtrer</button>
            <a href="/payslips" class="btn btn-secondary">❌ Réinitialiser</a>
        </div>
    </form>

    <table class="table table-bordered table-hover">
        <thead class="table-dark">
            <tr>
                <th>Employé</th>
                <th>Période</th>
                <th>Net à payer (€)</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($payslips as $p): ?>
                <tr>
                    <td><?= htmlspecialchars($p['last_name'] . ' ' . $p['first_name']) ?></td>
                    <td><?= htmlspecialchars($p['period']) ?></td>
                    <td><?= number_format($p['net_final'], 2, ',', ' ') ?></td>
                    <td>
                        <a href="/public/payslips/show?id=<?= $p['id'] ?>" class="btn btn-sm btn-info">🔍 Voir</a>
                        <a href="/public/payslips/duplicate?id=<?= $p['id'] ?>" class="btn btn-sm btn-warning">📄 Dupliquer</a>
                        <a href="/public/payslips/pdf?id=<?= $p['id'] ?>" class="btn btn-sm btn-outline-primary" target="_blank">📄 PDF</a>
                        <a href="/public/payslips/export_excel?id=<?= $p['id'] ?>" class="btn btn-sm btn-outline-success" target="_blank">📊 Excel</a>
                        <?php if ((int)$p['validated'] === 0): ?>
                            <a href="/public/payslips/edit?id=<?= $p['id'] ?>" class="btn btn-sm btn-warning">Modifier</a>
                            <a href="/public/payslips/delete?id=<?= $p['id'] ?>" class="btn btn-sm btn-danger">Supprimer</a>
                            <a href="/public/payslips/validate?id=<?= $p['id'] ?>" class="btn btn-sm btn-success">Valider</a>
                        <?php else: ?>
                            <span class="badge bg-success">Validé</span>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
</body>
</html>
