<?php
require_once __DIR__ . '/../../classes/RenewalReminder.php';
require_once __DIR__ . '/../../classes/Logger.php';
include '../../includes/header.php';
require_once __DIR__ . '/_module.php';

payrollRequireAdmin($auth);

$payroll = new Payroll($conn);
$logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);
$reminderService = new RenewalReminder($conn, $logger);

payrollModuleStyles();

$expiring = $reminderService->getExpiringContracts(30);
$expired  = $reminderService->getExpiredContracts(50);

$expiringIn7  = count(array_filter($expiring, fn($e) => (int)$e['days_remaining'] <= 7));
$expiringIn30 = count($expiring);
$expiredCount = count($expired);

$alertsSent = isset($_GET['alerts_sent']) ? (int)$_GET['alerts_sent'] : null;
?>

<div class="container-fluid px-4">
    <?php payrollModuleNav('contract_expiry'); ?>

    <div class="payroll-page-head">
        <div>
            <h1>Contract Expiry</h1>
            <p>Employees with fixed-term contracts expiring within 30 days. Alerts appear on the admin dashboard.</p>
        </div>
        <div>
            <a href="contract_expiry_run.php?action=send_alerts" class="btn btn-warning">
                <i class="fas fa-bell"></i> Send Alerts
                <?php if ($expiringIn30 > 0): ?>
                    <span class="badge bg-dark ms-1"><?php echo $expiringIn30; ?></span>
                <?php endif; ?>
            </a>
        </div>
    </div>

    <?php if ($alertsSent !== null): ?>
        <div class="alert alert-success">
            <i class="fas fa-check-circle"></i>
            Sent <?php echo $alertsSent; ?> contract expiry alert(s) to the admin dashboard notifications.
        </div>
    <?php endif; ?>

    <div class="payroll-metrics mb-4">
        <div class="payroll-metric">
            <strong>Expiring in 7 Days</strong>
            <span style="color:<?php echo $expiringIn7 > 0 ? '#dc3545' : '#212529'; ?>">
                <?php echo $expiringIn7; ?>
            </span>
        </div>
        <div class="payroll-metric">
            <strong>Expiring in 30 Days</strong>
            <span style="color:<?php echo $expiringIn30 > 0 ? '#fd7e14' : '#212529'; ?>">
                <?php echo $expiringIn30; ?>
            </span>
        </div>
        <div class="payroll-metric">
            <strong>Already Expired</strong>
            <span><?php echo $expiredCount; ?></span>
        </div>
    </div>

    <?php if (!empty($expiring)): ?>
    <div class="payroll-panel mb-4">
        <div class="payroll-panel-title">
            <h2>Expiring Within 30 Days</h2>
        </div>
        <div class="table-responsive">
            <table class="table payroll-table table-sm" id="expiringTable">
                <thead>
                    <tr>
                        <th>Employee</th>
                        <th>Position</th>
                        <th>Type</th>
                        <th>Branch</th>
                        <th>Contract Start</th>
                        <th>Contract End</th>
                        <th>Urgency</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($expiring as $emp): ?>
                        <?php
                        $days = (int)$emp['days_remaining'];
                        if ($days <= 7) {
                            $badgeClass = 'bg-danger';
                            $badgeLabel = $days === 0 ? 'Expires today' : "Expires in {$days} day(s)";
                        } else {
                            $badgeClass = 'bg-warning text-dark';
                            $badgeLabel = "Expires in {$days} day(s)";
                        }
                        ?>
                        <tr>
                            <td>
                                <strong><?php echo payrollText($emp['employee_fullname']); ?></strong>
                                <?php if (!empty($emp['employee_phone'])): ?>
                                    <br><small class="text-muted"><?php echo payrollText($emp['employee_phone']); ?></small>
                                <?php endif; ?>
                            </td>
                            <td><?php echo payrollText($emp['employee_position']); ?></td>
                            <td><?php echo payrollText(ucwords(str_replace('_', ' ', $emp['employment_type'] ?? ''))); ?></td>
                            <td><?php echo payrollText($emp['branch_name']); ?></td>
                            <td><?php echo payrollText($emp['contract_start']); ?></td>
                            <td><?php echo payrollText($emp['contract_ends']); ?></td>
                            <td><span class="badge <?php echo $badgeClass; ?>"><?php echo htmlspecialchars($badgeLabel); ?></span></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php else: ?>
        <div class="alert alert-success">
            <i class="fas fa-check-circle"></i> No contracts expiring in the next 30 days.
        </div>
    <?php endif; ?>

    <?php if (!empty($expired)): ?>
    <div class="payroll-panel mb-4">
        <div class="payroll-panel-title">
            <h2>Already Expired</h2>
            <small class="text-muted">Most recent 50 records</small>
        </div>
        <div class="table-responsive">
            <table class="table payroll-table table-sm" id="expiredTable">
                <thead>
                    <tr>
                        <th>Employee</th>
                        <th>Position</th>
                        <th>Type</th>
                        <th>Branch</th>
                        <th>Contract End</th>
                        <th>Overdue</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($expired as $emp): ?>
                        <tr>
                            <td><strong><?php echo payrollText($emp['employee_fullname']); ?></strong></td>
                            <td><?php echo payrollText($emp['employee_position']); ?></td>
                            <td><?php echo payrollText(ucwords(str_replace('_', ' ', $emp['employment_type'] ?? ''))); ?></td>
                            <td><?php echo payrollText($emp['branch_name']); ?></td>
                            <td><?php echo payrollText($emp['contract_ends']); ?></td>
                            <td><span class="badge bg-secondary"><?php echo (int)$emp['days_overdue']; ?> day(s) ago</span></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <?php payrollModuleEnd(); ?>
</div>

<script>
    if (document.getElementById('expiringTable')) { new DataTable('#expiringTable'); }
    if (document.getElementById('expiredTable'))  { new DataTable('#expiredTable'); }
</script>

<?php include '../../includes/footer.php'; ?>
