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

payrollRequireAdmin($auth);

$payroll = new Payroll($conn);
$summary = $payroll->getPayrollSummary();
$compliance = $payroll->getComplianceStatus();
$branchBreakdown = $payroll->getEmployeesByBranch();
$loans = array_slice($payroll->getLoans(), 0, 5);
$employees = array_slice($payroll->getAllEmployees(), 0, 5);
$payRuns = array_slice($payroll->getPayRuns(), 0, 5);

payrollModuleStyles();
?>
<style>
.payroll-quicknav {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 10px;
    margin-bottom: 20px;
}
.payroll-quicknav-item {
    align-items: center;
    background: #fff;
    border: 1px solid #dde3ea;
    color: #343a40;
    display: flex;
    flex-direction: column;
    gap: 8px;
    padding: 16px 8px 14px;
    text-align: center;
    text-decoration: none;
    transition: border-color .15s, color .15s, background .15s;
}
.payroll-quicknav-item:hover {
    background: #f1f5f9;
    border-color: #0d6efd;
    color: #0d6efd;
}
.payroll-quicknav-item i {
    font-size: 22px;
}
.payroll-quicknav-item span {
    font-size: 11px;
    font-weight: 600;
    letter-spacing: .03em;
    text-transform: uppercase;
}
</style>

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

    <div class="payroll-page-head">
        <div>
            <h1>HR - Payroll Overview</h1>
            <p>Central workspace for employee records, payroll structures, benefits, and staff obligations.</p>
        </div>
        <div class="no-print">
            <a href="../dashboard/admin.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left"></i> Admin Dashboard</a>
            <a href="add_employee_form.php" class="btn btn-primary"><i class="fas fa-user-plus"></i> Add Employee</a>
        </div>
    </div>

    <div class="payroll-metrics">
        <div class="payroll-metric"><strong>Employees</strong><span><?php echo number_format($summary['employees']); ?></span></div>
        <div class="payroll-metric"><strong>Monthly Payroll</strong><span><?php echo payrollMoney($summary['monthly_payroll']); ?></span></div>
        <div class="payroll-metric"><strong>Salary Grades</strong><span><?php echo number_format($summary['salary_grades']); ?></span></div>
        <div class="payroll-metric"><strong>Loan Balance</strong><span><?php echo payrollMoney($summary['loan_balance']); ?></span></div>
    </div>

    <?php payrollMigrationNotice($payroll, ['payroll_runs', 'payroll_payslips', 'hr_attendance', 'hr_leave_requests'], 'Install the professional schema to unlock pay runs, payslips, attendance history, leave approvals, and audit controls.'); ?>

    <div class="payroll-quicknav no-print">
        <a href="employee_list.php"      class="payroll-quicknav-item"><i class="fas fa-user-tie"></i><span>Employees</span></a>
        <a href="departments.php"        class="payroll-quicknav-item"><i class="fas fa-building-user"></i><span>Departments</span></a>
        <a href="salaries.php"           class="payroll-quicknav-item"><i class="fas fa-money-check-alt"></i><span>Salary Grades</span></a>
        <a href="pay_runs.php"           class="payroll-quicknav-item"><i class="fas fa-file-invoice-dollar"></i><span>Pay Runs</span></a>
        <a href="payslips.php"           class="payroll-quicknav-item"><i class="fas fa-receipt"></i><span>Payslips</span></a>
        <a href="loans.php"              class="payroll-quicknav-item"><i class="fas fa-hand-holding-dollar"></i><span>Loans</span></a>
        <a href="attendance.php"         class="payroll-quicknav-item"><i class="fas fa-calendar-check"></i><span>Attendance</span></a>
        <a href="leave.php"              class="payroll-quicknav-item"><i class="fas fa-calendar-alt"></i><span>Leave</span></a>
        <a href="remunerations.php"      class="payroll-quicknav-item"><i class="fas fa-coins"></i><span>Remunerations</span></a>
        <a href="pension.php"            class="payroll-quicknav-item"><i class="fas fa-piggy-bank"></i><span>Pension</span></a>
        <a href="payroll_bills.php"      class="payroll-quicknav-item"><i class="fas fa-file-invoice"></i><span>Payroll Bills</span></a>
        <a href="other_deductions.php"   class="payroll-quicknav-item"><i class="fas fa-circle-minus"></i><span>Deductions</span></a>
        <a href="compliance.php"         class="payroll-quicknav-item"><i class="fas fa-shield-halved"></i><span>Compliance</span></a>
        <a href="setup.php"              class="payroll-quicknav-item"><i class="fas fa-screwdriver-wrench"></i><span>Setup</span></a>
    </div>

    <div class="row g-3">
        <div class="col-lg-7">
            <div class="payroll-panel h-100">
                <div class="payroll-panel-title">
                    <h2>Recent Employees</h2>
                    <a href="employee_list.php" class="btn btn-sm btn-outline-primary no-print">View all</a>
                </div>
                <div class="table-responsive">
                    <table class="table table-bordered payroll-table">
                        <thead>
                            <tr>
                                <th>Employee</th>
                                <th>Branch</th>
                                <th>Position</th>
                                <th>Status</th>
                                <th>Salary</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($employees)): ?>
                                <?php foreach ($employees as $employee): ?>
                                    <tr>
                                        <td><?php echo payrollText($employee['employee_fullname'] ?? ''); ?></td>
                                        <td><?php echo payrollText($employee['branch_name'] ?? $employee['branch'] ?? ''); ?></td>
                                        <td><?php echo payrollText($employee['employee_position'] ?? ''); ?></td>
                                        <td><?php echo payrollStatusBadge($employee['employment_status'] ?? 'active'); ?></td>
                                        <td><?php echo payrollMoney($employee['basic_salary'] ?? 0); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="5" class="text-center">No employees found.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="col-lg-5">
            <div class="payroll-panel h-100">
                <div class="payroll-panel-title">
                    <h2>Employees by Branch</h2>
                    <a href="employee_list.php" class="btn btn-sm btn-outline-primary no-print">Open register</a>
                </div>
                <div class="table-responsive">
                    <table class="table table-bordered payroll-table">
                        <thead>
                            <tr>
                                <th>Branch</th>
                                <th>Employees</th>
                                <th>Payroll</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($branchBreakdown)): ?>
                                <?php foreach ($branchBreakdown as $branch): ?>
                                    <tr>
                                        <td><?php echo payrollText($branch['branch'] ?? ''); ?></td>
                                        <td><?php echo number_format((int)$branch['total_employees']); ?></td>
                                        <td><?php echo payrollMoney($branch['total_salary'] ?? 0); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="3" class="text-center">No branch payroll data found.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="col-lg-5">
            <div class="payroll-panel h-100">
                <div class="payroll-panel-title">
                    <h2>Compliance Readiness</h2>
                    <a href="compliance.php" class="btn btn-sm btn-outline-primary no-print">Open</a>
                </div>
                <?php foreach ($compliance as $check): ?>
                    <?php $percent = $check['total'] > 0 ? round(($check['complete'] / $check['total']) * 100) : 0; ?>
                    <div class="mb-3">
                        <div class="d-flex justify-content-between">
                            <strong><?php echo payrollText($check['label']); ?></strong>
                            <span><?php echo $percent; ?>%</span>
                        </div>
                        <div class="progress" style="height: 10px;">
                            <div class="progress-bar <?php echo $percent >= 90 ? 'bg-success' : ($percent >= 60 ? 'bg-warning' : 'bg-danger'); ?>" style="width: <?php echo $percent; ?>%;"></div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="col-lg-7">
            <div class="payroll-panel h-100">
                <div class="payroll-panel-title">
                    <h2>Recent Pay Runs</h2>
                    <a href="pay_runs.php" class="btn btn-sm btn-outline-primary no-print">Open</a>
                </div>
                <div class="table-responsive">
                    <table class="table table-bordered payroll-table">
                        <thead>
                            <tr>
                                <th>Run</th>
                                <th>Period</th>
                                <th>Pay Date</th>
                                <th>Net Pay</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($payRuns)): ?>
                                <?php foreach ($payRuns as $run): ?>
                                    <tr>
                                        <td><?php echo payrollText($run['run_number'] ?? ''); ?></td>
                                        <td><?php echo payrollText($run['pay_period_start'] ?? ''); ?> to <?php echo payrollText($run['pay_period_end'] ?? ''); ?></td>
                                        <td><?php echo payrollText($run['pay_date'] ?? ''); ?></td>
                                        <td><?php echo payrollMoney($run['net_pay'] ?? 0); ?></td>
                                        <td><?php echo payrollStatusBadge($run['status'] ?? 'draft'); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="5" class="text-center">No pay runs found.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="col-12">
            <div class="payroll-panel">
                <div class="payroll-panel-title">
                    <h2>Recent Loans</h2>
                    <a href="loans.php" class="btn btn-sm btn-outline-primary no-print">View loans</a>
                </div>
                <div class="table-responsive">
                    <table class="table table-bordered payroll-table">
                        <thead>
                            <tr>
                                <th>Employee</th>
                                <th>Type</th>
                                <th>Amount</th>
                                <th>Balance</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($loans)): ?>
                                <?php foreach ($loans as $loan): ?>
                                    <?php $balance = max(0, (float)($loan['loan_amount'] ?? 0) - (float)($loan['loan_total_paid'] ?? 0)); ?>
                                    <tr>
                                        <td><?php echo payrollText($loan['employee_fullname'] ?? ('Employee #' . ($loan['employee_id'] ?? ''))); ?></td>
                                        <td><?php echo payrollText(str_replace('_', ' ', $loan['loan_type'] ?? '')); ?></td>
                                        <td><?php echo payrollMoney($loan['loan_amount'] ?? 0); ?></td>
                                        <td><?php echo payrollMoney($balance); ?></td>
                                        <td><?php echo payrollStatusBadge($loan['loan_status'] ?? ''); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="5" class="text-center">No loans found.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

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

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