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

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

$message = '';
$message_type = 'info';
$attendance_records = [];
$selected_staff = null;
$accumulated_penalty = 0;

// Default last 30 days
$start_date = date('Y-m-d', strtotime('-30 days'));
$end_date   = date('Y-m-d');

/* ====== Fetch settings & staff ====== */
$settings = $connection->query("SELECT * FROM attendance_settings LIMIT 1")->fetch_assoc();
$all_staff = $connection->query("SELECT id, username, name FROM staff ORDER BY name ASC")->fetch_all(MYSQLI_ASSOC);

/* ====== Handle POST Actions ====== */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    /* --- Save Attendance Settings --- */
    if (isset($_POST['save_settings'])) {
        $morning_time    = $_POST['morning_time'];
        $lateness_penalty = floatval($_POST['penalty_amount']);
        $absent_penalty   = floatval($_POST['absent_penalty']);

        if ($settings) {
            $stmt = $connection->prepare("
                UPDATE attendance_settings 
                SET morning_resumption=?, lateness_penalty=?, absent_penalty=? 
                WHERE id=?
            ");
            $stmt->bind_param("sddi", $morning_time, $lateness_penalty, $absent_penalty, $settings['id']);
        } else {
            $stmt = $connection->prepare("
                INSERT INTO attendance_settings (morning_resumption, lateness_penalty, absent_penalty) 
                VALUES (?,?,?)
            ");
            $stmt->bind_param("sdd", $morning_time, $lateness_penalty, $absent_penalty);
        }
        $stmt->execute();

        // Update all pending absence fees in staff_attendance
        $connection->query("
            UPDATE staff_attendance 
            SET absence_fee=$absent_penalty 
            WHERE absent_flag=1
        ");

        $_SESSION['message'] = "✅ Attendance settings saved";
        header("Location: attendance_settings"); exit;
    }

    /* --- Manual Absence Entry (Plan B) --- */
    if (isset($_POST['add_manual_absence'])) {
        $staff_id = intval($_POST['manual_staff_id']);
        $date     = $_POST['manual_absence_date'];

        // Check if already marked absent for that date
        $check = $connection->prepare("
            SELECT id FROM staff_attendance 
            WHERE staff_id=? AND date=? AND absent_flag=1
        ");
        $check->bind_param("is", $staff_id, $date);
        $check->execute();
        $res = $check->get_result();
        if ($res->num_rows > 0) {
            $_SESSION['message'] = "❌ Staff already marked absent for {$date}";
            header("Location: attendance_settings"); exit;
        }
        $check->close();

        // Get absence penalty from settings
        $absence_fee = floatval($settings['absent_penalty'] ?? 0);

        // Insert manual absence
        $stmt = $connection->prepare("
            INSERT INTO staff_attendance (staff_id, date, absent_flag, absence_fee) 
            VALUES (?, ?, 1, ?)
        ");
        $stmt->bind_param("isd", $staff_id, $date, $absence_fee);
        $stmt->execute();
        $stmt->close();

        $_SESSION['message'] = "✅ Manual absence added for staff on {$date} (₦".number_format($absence_fee,2).")";
        header("Location: attendance_settings"); exit;
    }

    /* --- Waive Lateness --- */
    if (isset($_POST['waive_lateness'])) {
        $stmt = $connection->prepare("
            UPDATE staff_attendance 
            SET late_flag=0, late_waived=1, waive_reason=? 
            WHERE id=?
        ");
        $stmt->bind_param("si", $_POST['waive_reason'], $_POST['attendance_id']);
        $stmt->execute();
        $_SESSION['message'] = "✅ Lateness waived"; 
        header("Location: attendance_settings"); exit;
    }

    /* --- Undo Waiver --- */
    if (isset($_POST['undo_waiver'])) {
        $stmt = $connection->prepare("
            UPDATE staff_attendance 
            SET late_flag=1, late_waived=0, waive_reason=NULL 
            WHERE id=?
        ");
        $stmt->bind_param("i", $_POST['attendance_id']); 
        $stmt->execute();
        $_SESSION['message'] = "✅ Waiver undone"; 
        header("Location: attendance_settings"); exit;
    }

    /* --- Bulk Clearance (lateness + absence) --- */
    if (isset($_POST['clear_lateness_bulk'])) {
        $staff_id = intval($_POST['staff_id']);
        $amount   = floatval($_POST['clear_amount']);

        if ($amount <= 0) { 
            $_SESSION['message']="❌ Invalid amount"; 
            header("Location: attendance_settings"); exit; 
        }

        // Fetch all pending lateness + absence
        $stmt = $connection->prepare("
            SELECT id, lateness_fee, late_flag, late_waived, absence_fee, absent_flag
            FROM staff_attendance
            WHERE staff_id=? AND ((late_flag=1 AND late_waived=0) OR (absent_flag=1))
            ORDER BY date ASC
        ");
        $stmt->bind_param("i",$staff_id); 
        $stmt->execute();
        $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

        $remaining = $amount;
        foreach($rows as $row){
            if($remaining <=0) break;
            $update_fee = 0;
            $updates = [];

            if($row['late_flag']==1 && $row['late_waived']==0 && $row['lateness_fee']>0){
                $deduct = min($row['lateness_fee'],$remaining);
                $update_fee += $deduct;
                $remaining -= $deduct;
                $updates[]="late_flag=0, late_waived=1, waive_reason='Bulk clearance'";
            }

            if($row['absent_flag']==1 && $row['absence_fee']>0 && $remaining>0){
                $deduct = min($row['absence_fee'],$remaining);
                $update_fee += $deduct;
                $remaining -= $deduct;
                $updates[]="absent_flag=0";
            }

            if($update_fee>0){
                $connection->query("UPDATE staff_attendance SET ".implode(',',$updates)." WHERE id={$row['id']}");
            }
        }

        $_SESSION['message']="✅ ₦".number_format($amount,2)." cleared successfully"; 
        header("Location: attendance_settings"); exit;
    }

    /* --- Fetch Staff Attendance --- */
    if (isset($_POST['fetch_staff'])) {
        $staff_id   = intval($_POST['staff_id']);
        $start_date = $_POST['start_date'];
        $end_date   = $_POST['end_date'];

        $selected_staff = $connection->query("SELECT * FROM staff WHERE id={$staff_id} LIMIT 1")->fetch_assoc();
        if($selected_staff){
            $stmt = $connection->prepare("
                SELECT * FROM staff_attendance
                WHERE staff_id=? AND date BETWEEN ? AND ?
                ORDER BY date DESC
            ");
            $stmt->bind_param("iss",$staff_id,$start_date,$end_date); 
            $stmt->execute();
            $attendance_records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

            $accumulated_penalty=0;
            foreach($attendance_records as $rec){
                $accumulated_penalty += ($rec['late_flag']==1 && $rec['late_waived']==0 ? $rec['lateness_fee'] : 0);
                $accumulated_penalty += ($rec['absent_flag']==1 ? $rec['absence_fee'] : 0);
            }
        }
    }

    /* --- Add Holiday --- */
    if (isset($_POST['add_holiday'])){
        $title = $_POST['title'];
        $date  = $_POST['holiday_date'];
        $applies_to = $_POST['applies_to'] ?? 'all';
        $stmt = $connection->prepare("INSERT INTO school_holidays (title, holiday_date, applies_to) VALUES (?,?,?)");
        $stmt->bind_param("sss",$title,$date,$applies_to); $stmt->execute();
        $_SESSION['message']="✅ Holiday added"; header("Location: attendance_settings"); exit;
    }

    /* --- Add Closure --- */
    if (isset($_POST['add_closure'])){
        $reason = $_POST['reason'];
        $start  = $_POST['start_date'];
        $end    = $_POST['end_date'];
        $applies_to = $_POST['applies_to'] ?? 'all';
        $stmt = $connection->prepare("INSERT INTO school_closed_days (reason,start_date,end_date,applies_to) VALUES (?,?,?,?)");
        $stmt->bind_param("ssss",$reason,$start,$end,$applies_to); $stmt->execute();
        $_SESSION['message']="✅ Closure added"; header("Location: attendance_settings"); exit;
    }

    /* --- Delete Holiday --- */
    if (isset($_POST['delete_holiday'])){
        $id = intval($_POST['holiday_id']);
        $connection->query("DELETE FROM school_holidays WHERE id=$id");
        $_SESSION['message']="✅ Holiday deleted"; header("Location: attendance_settings"); exit;
    }

    /* --- Delete Closure --- */
    if (isset($_POST['delete_closure'])){
        $id = intval($_POST['closure_id']);
        $connection->query("DELETE FROM school_closed_days WHERE id=$id");
        $_SESSION['message']="✅ Closure deleted"; header("Location: attendance_settings"); exit;
    }
}

/* --- Holidays & Closures --- */
$holidays = $connection->query("SELECT * FROM school_holidays ORDER BY holiday_date DESC")->fetch_all(MYSQLI_ASSOC);
$closures = $connection->query("SELECT * FROM school_closed_days ORDER BY start_date DESC")->fetch_all(MYSQLI_ASSOC);

/* --- Flash --- */
if(isset($_SESSION['message'])) { $message=$_SESSION['message']; unset($_SESSION['message']); }

?>



<!-- ========================= PAGE UI ========================= -->

<div class="page-title mb-3">
    <h1><i class="fa fa-calendar-alt"></i> Attendance Settings & School Calendar</h1>
</div>

<?php if($message): ?>
<div class="alert alert-info"><?=htmlspecialchars($message)?></div>
<?php endif; ?>

<!-- Attendance Settings -->
<div class="card mb-4">
    <div class="card-header"><h3>Attendance Settings</h3></div>
    <form method="POST">
        <div class="card-body row g-3">
            <div class="col-md-4">
                <label>Morning Resumption</label>
                <input type="time" name="morning_time" class="form-control"
                       value="<?= $settings['morning_resumption'] ?? '08:00' ?>" required>
            </div>
            <div class="col-md-4">
                <label>Lateness Penalty (₦)</label>
                <input type="number" step="0.01" name="penalty_amount" class="form-control"
                       value="<?= $settings['lateness_penalty'] ?? 0 ?>">
            </div>
            <div class="col-md-4">
                <label>Absent Penalty (₦)</label>
                <input type="number" step="0.01" name="absent_penalty" class="form-control"
                       value="<?= $settings['absent_penalty'] ?? 0 ?>">
            </div>
        </div>
        <div class="card-footer text-end">
            <button name="save_settings" class="btn btn-primary">Save Settings</button>
        </div>
    </form>
</div>

<!-- Add Holiday -->
<div class="card mb-4">
    <div class="card-header"><h3>Add Public Holiday</h3></div>
    <form method="POST" class="card-body row g-3">
        <div class="col-md-4">
            <input type="text" name="title" class="form-control" placeholder="Holiday Name" required>
        </div>
        <div class="col-md-3">
            <input type="date" name="holiday_date" class="form-control" required>
        </div>
        <div class="col-md-3">
            <select name="applies_to" class="form-control">
                <option value="all">All</option>
                <option value="staff">Staff only</option>
            </select>
        </div>
        <div class="col-md-2 d-grid">
            <button name="add_holiday" class="btn btn-success">Add Holiday</button>
        </div>
    </form>
</div>

<!-- Add Closure -->
<div class="card mb-4">
    <div class="card-header"><h3>Add School Closure</h3></div>
    <form method="POST" class="card-body row g-3">
        <div class="col-md-3">
            <input type="text" name="reason" class="form-control" placeholder="Reason" required>
        </div>
        <div class="col-md-3">
            <input type="date" name="start_date" class="form-control" required>
        </div>
        <div class="col-md-3">
            <input type="date" name="end_date" class="form-control" required>
        </div>
        <div class="col-md-2">
            <select name="applies_to" class="form-control">
                <option value="all">All</option>
                <option value="staff">Staff only</option>
            </select>
        </div>
        <div class="col-md-1 d-grid">
            <button name="add_closure" class="btn btn-danger">Add</button>
        </div>
    </form>
</div>

<!-- Holidays Table -->
<div class="card mb-4">
    <div class="card-header"><h3>Public Holidays</h3></div>
    <div class="card-body table-responsive">
        <table class="table table-bordered table-striped">
            <thead>
            <tr>
                <th>#</th>
                <th>Holiday</th>
                <th>Date</th>
                <th>Applies To</th>
                <th>Action</th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($holidays as $i => $h): ?>
                <tr>
                    <td><?= $i + 1 ?></td>
                    <td><?= htmlspecialchars($h['title']) ?></td>
                    <td><?= $h['holiday_date'] ?></td>
                    <td><?= $h['applies_to'] ?></td>
                    <td>
                        <form method="POST">
                            <input type="hidden" name="holiday_id" value="<?= $h['id'] ?>">
                            <button name="delete_holiday" class="btn btn-sm btn-danger">Delete</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Closures Table -->
<div class="card mb-4">
    <div class="card-header"><h3>School Closed Days</h3></div>
    <div class="card-body table-responsive">
        <table class="table table-bordered table-striped">
            <thead>
            <tr>
                <th>#</th>
                <th>Reason</th>
                <th>Start</th>
                <th>End</th>
                <th>Applies To</th>
                <th>Action</th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($closures as $i => $c): ?>
                <tr>
                    <td><?= $i + 1 ?></td>
                    <td><?= htmlspecialchars($c['reason']) ?></td>
                    <td><?= $c['start_date'] ?></td>
                    <td><?= $c['end_date'] ?></td>
                    <td><?= $c['applies_to'] ?></td>
                    <td>
                        <form method="POST">
                            <input type="hidden" name="closure_id" value="<?= $c['id'] ?>">
                            <button name="delete_closure" class="btn btn-sm btn-danger">Delete</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- ========================= FETCH STAFF ATTENDANCE ========================= -->
<div class="card mb-4">
    <div class="card-header"><h3>Fetch Staff Attendance</h3></div>
    <form method="POST">
        <div class="card-body row g-3">
            <div class="col-md-4">
                <label>Staff</label>
                <select name="staff_id" class="form-control" required>
                    <option value="">-- Select Staff --</option>
                    <?php foreach ($all_staff as $s): ?>
                        <option value="<?= $s['id'] ?>" <?= ($selected_staff && $selected_staff['id']==$s['id'])?'selected':'' ?>>
                            <?= htmlspecialchars($s['name']) ?> (<?= htmlspecialchars($s['username']) ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-3">
                <label>Start Date</label>
                <input type="date" name="start_date" value="<?= $start_date ?>" class="form-control" required>
            </div>

            <div class="col-md-3">
                <label>End Date</label>
                <input type="date" name="end_date" value="<?= $end_date ?>" class="form-control" required>
            </div>

            <div class="col-md-2 d-grid">
                <button name="fetch_staff" class="btn btn-success">Fetch</button>
            </div>
        </div>
    </form>
</div>

<?php if($selected_staff): ?>
<div class="card mb-4">
    <div class="card-body">
        <span class="badge bg-info mb-3">
            Accumulated Penalty: ₦<?= number_format($accumulated_penalty,2) ?>
        </span>
    </div>
</div>

<?php if(count($attendance_records)): ?>
<table class="table table-bordered table-striped">
    <thead>
        <tr>
            <th>#</th>
            <th>Date</th>
            <th>Time In</th>
            <th>Status</th>
            <th>Fee (₦)</th>
            <th>Waived</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach($attendance_records as $i=>$r): ?>
        <tr>
            <td><?=$i+1?></td>
            <td><?=$r['date']?></td>
            <td><?=$r['time_morning']?></td>
            <td><?= ((int)$r['late_flag']===1)?'<span class="badge bg-danger">Late</span>':'<span class="badge bg-success">On Time</span>' ?></td>
            <td><?= number_format($r['lateness_fee'],2)?></td>
            <td><?= $r['late_waived'] ? htmlspecialchars($r['waive_reason']):'No' ?></td>
            <td>
                <?php if((int)$r['late_flag']===1 && (int)$r['late_waived']===0): ?>
                <form method="POST">
                    <input type="hidden" name="attendance_id" value="<?=$r['id']?>">
                    <input type="text" name="waive_reason" class="form-control mb-1" placeholder="Reason" required>
                    <button name="waive_lateness" class="btn btn-sm btn-success">Waive</button>
                </form>
                <?php elseif((int)$r['late_waived']===1): ?>
                <form method="POST">
                    <input type="hidden" name="attendance_id" value="<?=$r['id']?>">
                    <button name="undo_waiver" class="btn btn-sm btn-warning">Undo</button>
                </form>
                <?php else: ?>
                —
                <?php endif; ?>
            </td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>
<?php endif; ?>

<!-- Bulk Clear Form -->
<div class="card mb-4 border-danger">
    <div class="card-header bg-danger text-white">
        <h4>Clear Staff Lateness / Absence (Bulk)</h4>
    </div>
    <form method="POST" class="card-body">
        <input type="hidden" name="staff_id" value="<?=$selected_staff['id']?>">
        <div class="row">
            <div class="col-md-6">
                <label>Total Outstanding</label>
                <input type="text" class="form-control" value="₦<?= number_format($accumulated_penalty,2) ?>" readonly>
            </div>
            <div class="col-md-6">
                <label>Amount to Clear</label>
                <input type="number" step="0.01" name="clear_amount" class="form-control" required>
            </div>
        </div>
        <button name="clear_lateness_bulk" onclick="return confirm('Are you sure?')" class="btn btn-danger mt-3">Clear Lateness</button>
    </form>
</div>
<?php endif; ?>

<!-- ========================= MANUAL ABSENCE ENTRY ========================= -->
<div class="card mb-4 border-warning">
    <div class="card-header bg-warning text-dark">
        <h4>Manual Absence Entry (Plan B)</h4>
        <p>Use this if daily absence cron failed.</p>
    </div>
    <form method="POST" class="card-body row g-3">
        <div class="col-md-4">
            <label>Select Staff</label>
            <select name="manual_staff_id" class="form-control" required>
                <option value="">-- Select Staff --</option>
                <?php foreach ($all_staff as $s): ?>
                    <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['name']) ?> (<?= htmlspecialchars($s['username']) ?>)</option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-3">
            <label>Select Date</label>
            <input type="date" name="manual_absence_date" class="form-control" required>
        </div>
        <div class="col-md-3 d-grid">
            <button name="add_manual_absence" class="btn btn-warning mt-4">Add Absence</button>
        </div>
    </form>
</div>

