<?php
require_once(__DIR__ . "/../header.php");             
require_once(__DIR__ . "/../../public/connection.php"); 

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['staff']) || empty($_SESSION['staff'])) {
    header("Location: login.php");
    exit;
}

$staff_id = $_SESSION['staff'];

/* ===============================
   FETCH STAFF INFO
   =============================== */
$staff = $connection
    ->query("SELECT id, username, name FROM staff WHERE id='$staff_id'")
    ->fetch_assoc();

/* ===============================
   DEFAULT DATE FILTER
   =============================== */
$start_date = date('Y-m-d', strtotime('-1 month')); 
$end_date   = date('Y-m-d');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['filter_records'])) {
    $start_date = $_POST['start_date'];
    $end_date   = $_POST['end_date'];
}

/* ===============================
   FETCH SETTINGS
   =============================== */
$settings = $connection
    ->query("SELECT lateness_penalty, absent_penalty FROM attendance_settings LIMIT 1")
    ->fetch_assoc();

/* ===============================
   TOTAL LATENESS + ABSENCE PENALTY
   =============================== */
$stmt = $connection->prepare("
    SELECT lateness_fee, late_flag, late_waived,
           COALESCE(absent_flag,0) AS absent_flag,
           COALESCE(absence_fee,?) AS absence_fee
    FROM staff_attendance
    WHERE staff_id=?
");
$absent_penalty = floatval($settings['absent_penalty'] ?? 0);
$stmt->bind_param("di", $absent_penalty, $staff_id);
$stmt->execute();
$records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$total_lateness_fee = 0;
$total_absent_fee   = 0;
$absent_days        = 0;

foreach ($records as $rec) {
    // Lateness
    if ($rec['late_flag']==1 && ($rec['late_waived']==0 || $rec['late_waived']===NULL)) {
        $total_lateness_fee += floatval($rec['lateness_fee']);
    }
    // Absence
    if ($rec['absent_flag']==1) {
        $total_absent_fee += floatval($rec['absence_fee']);
        $absent_days++;
    }
}

/* Grand total */
$grand_total_penalty = $total_lateness_fee + $total_absent_fee;

/* ===============================
   FETCH FILTERED RECORDS
   =============================== */
$stmt = $connection->prepare("
    SELECT date, late_flag, lateness_fee, late_waived, waive_reason,
           COALESCE(absent_flag,0) AS absent_flag,
           COALESCE(absence_fee,?) AS absence_fee
    FROM staff_attendance
    WHERE staff_id=? AND date BETWEEN ? AND ?
    ORDER BY date DESC
");
$stmt->bind_param("diss", $absent_penalty, $staff_id, $start_date, $end_date);
$stmt->execute();
$attendance_records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

?>


<div class="page-title mb-3">
    <h1><i class="fa fa-wallet"></i> My Attendance Penalties</h1>
    <p>View your lateness and absence penalties.</p>
</div>

<!-- SUMMARY -->
<div class="card mb-4">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h3 class="card-title mb-0">Penalty Summary</h3>
        <div class="text-end">
            <div style="
                font-size:3rem;
                font-weight:900;
                background:linear-gradient(90deg,#dc3545,#fd7e14);
                color:#fff;
                padding:10px 24px;
                border-radius:12px;
            ">
                ₦<?= number_format($grand_total_penalty,2) ?>
            </div>
            <small class="text-muted d-block">
                Lateness: ₦<?= number_format($total_lateness_fee,2) ?>
            </small>
            <small class="text-muted d-block">
                Absence (<?= $absent_days ?> days): ₦<?= number_format($total_absent_fee,2) ?>
            </small>
        </div>
    </div>
</div>

<!-- FILTER -->
<div class="card mb-4">
    <div class="card-header"><h3>Filter Records</h3></div>
    <form method="POST">
        <div class="card-body row g-3">
            <div class="col-md-4">
                <input type="date" name="start_date" value="<?= $start_date ?>" class="form-control" required>
            </div>
            <div class="col-md-4">
                <input type="date" name="end_date" value="<?= $end_date ?>" class="form-control" required>
            </div>
            <div class="col-md-4 d-grid">
                <button name="filter_records" class="btn btn-success mt-4">Filter</button>
            </div>
        </div>
    </form>
</div>

<!-- TABLE -->
<div class="card mb-4">
    <div class="card-header">
        <h3>Attendance Records for <?= htmlspecialchars($staff['name']) ?></h3>
    </div>
    <div class="card-body">
        <?php if ($attendance_records): ?>
        <div class="table-responsive">
            <table class="table table-bordered table-striped">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Date</th>
                        <th>Status</th>
                        <th>Penalty (₦)</th>
                        <th>Waived?</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($attendance_records as $i => $r): ?>
                    <tr>
                        <td><?= $i+1 ?></td>
                        <td><?= $r['date'] ?></td>
                        <td>
                            <?php 
                            if ($r['absent_flag']==1) {
                                echo '<span class="badge bg-danger">Absent</span>';
                            } elseif ($r['late_flag']==1) {
                                echo '<span class="badge bg-warning">Late</span>';
                            } else {
                                echo '<span class="badge bg-success">On Time</span>';
                            }
                            ?>
                        </td>
                        <td>
                            ₦<?= number_format(
                                ($r['absent_flag']==1 ? $r['absence_fee'] : 0) + 
                                ($r['late_flag']==1 && ($r['late_waived']==0 || $r['late_waived']===NULL) ? $r['lateness_fee'] : 0)
                            ,2) ?>
                        </td>
                        <td>
                            <?php 
                            if ($r['late_waived']==1) {
                                echo '<span class="badge bg-warning">'.htmlspecialchars($r['waive_reason']).'</span>';
                            } else {
                                echo '-';
                            }
                            ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php else: ?>
            <p>No records found.</p>
        <?php endif; ?>
    </div>
</div>


