<?php
require_once __DIR__ . '/../../classes/Payroll.php';

function payrollRequireAdmin($auth) {
    if (!isset($_SESSION['user_id'])) {
        header('Location: ../../login.php');
        exit();
    }

    $auth->enforceSuperAdminPrivileges($_SESSION['user_id']);
}

function payrollMoney($amount) {
    return 'MWK ' . number_format((float)$amount, 2);
}

function payrollText($value, $fallback = 'N/A') {
    $value = trim((string)($value ?? ''));
    return htmlspecialchars($value !== '' ? $value : $fallback);
}

function payrollStatusBadge($status) {
    $status = strtolower(trim((string)$status));
    $class = 'bg-secondary';

    if ($status === 'approved' || $status === 'active') {
        $class = 'bg-success';
    } elseif ($status === 'pending') {
        $class = 'bg-warning text-dark';
    } elseif ($status === 'closed' || $status === 'paid') {
        $class = 'bg-info text-dark';
    }

    return '<span class="badge ' . $class . '">' . payrollText($status ?: 'unknown') . '</span>';
}

function payrollModuleNav($active = '') {
    $items = [
        'dashboard' => ['index.php', 'fa-gauge-high', 'Overview'],
        'employees' => ['employee_list.php', 'fa-user-tie', 'Employees'],
        'departments' => ['departments.php', 'fa-building-user', 'Departments'],
        'salaries' => ['salaries.php', 'fa-money-check-alt', 'Salary Grades'],
        'pay_runs' => ['pay_runs.php', 'fa-file-invoice-dollar', 'Pay Runs'],
        'payslips' => ['payslips.php', 'fa-receipt', 'Payslips'],
        'loans' => ['loans.php', 'fa-hand-holding-dollar', 'Loans'],
        'attendance' => ['attendance.php', 'fa-calendar-check', 'Attendance'],
        'leave' => ['leave.php', 'fa-calendar-alt', 'Leave'],
        'remunerations' => ['remunerations.php', 'fa-receipt', 'Remunerations'],
        'pension' => ['pension.php', 'fa-piggy-bank', 'Pension'],
        'bills' => ['payroll_bills.php', 'fa-file-invoice', 'Payroll Bills'],
        'other_deductions' => ['other_deductions.php', 'fa-circle-minus', 'Other Deductions'],
        'contract_expiry' => ['contract_expiry.php', 'fa-calendar-xmark', 'Contract Expiry'],
        'compliance' => ['compliance.php', 'fa-shield-halved', 'Compliance'],
        'setup' => ['setup.php', 'fa-screwdriver-wrench', 'Setup'],
    ];
    ?>
    <div class="payroll-shell">
        <aside class="payroll-sidebar no-print">
            <div class="payroll-sidebar-title">HR - Payroll</div>
            <?php foreach ($items as $key => $item): ?>
                <a class="<?php echo $active === $key ? 'active' : ''; ?>" href="<?php echo $item[0]; ?>">
                    <i class="fas <?php echo $item[1]; ?>"></i>
                    <?php echo htmlspecialchars($item[2]); ?>
                </a>
            <?php endforeach; ?>
        </aside>
        <main class="payroll-main">
    <?php
}

function payrollModuleEnd() {
    echo '</main></div>';
}

function payrollModuleStyles() {
    ?>
    <style>
        .payroll-shell {
            display: grid;
            grid-template-columns: 230px minmax(0, 1fr);
            gap: 24px;
            align-items: start;
            margin: 24px 0;
        }

        .payroll-sidebar {
            position: sticky;
            top: 88px;
            border: 1px solid #dde3ea;
            background: #fff;
            padding: 14px;
        }

        .payroll-sidebar-title {
            color: #495057;
            font-size: 12px;
            font-weight: 700;
            letter-spacing: .04em;
            margin: 4px 8px 12px;
            text-transform: uppercase;
        }

        .payroll-sidebar a {
            align-items: center;
            color: #343a40;
            display: flex;
            gap: 10px;
            padding: 10px 12px;
            text-decoration: none;
        }

        .payroll-sidebar a.active,
        .payroll-sidebar a:hover {
            background: #f1f5f9;
            color: #0d6efd;
        }

        .payroll-page-head {
            align-items: flex-start;
            display: flex;
            justify-content: space-between;
            gap: 16px;
            margin-bottom: 18px;
        }

        .payroll-page-head h1 {
            font-size: 26px;
            margin: 0 0 4px;
        }

        .payroll-page-head p {
            color: #6c757d;
            margin: 0;
        }

        .payroll-metrics {
            display: grid;
            gap: 14px;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            margin-bottom: 20px;
        }

        .payroll-metric,
        .payroll-panel {
            background: #fff;
            border: 1px solid #dde3ea;
            padding: 16px;
        }

        .payroll-metric strong {
            color: #6c757d;
            display: block;
            font-size: 12px;
            margin-bottom: 8px;
            text-transform: uppercase;
        }

        .payroll-metric span {
            color: #212529;
            display: block;
            font-size: 24px;
            font-weight: 700;
        }

        .payroll-panel-title {
            align-items: center;
            display: flex;
            justify-content: space-between;
            gap: 12px;
            margin-bottom: 12px;
        }

        .payroll-panel-title h2 {
            font-size: 18px;
            margin: 0;
        }

        .payroll-table {
            margin-bottom: 0;
        }

        .payroll-table th {
            background: #f8f9fa;
            color: #495057;
            font-size: 12px;
            text-transform: uppercase;
        }

        @media (max-width: 900px) {
            .payroll-shell {
                grid-template-columns: 1fr;
            }

            .payroll-sidebar {
                position: static;
            }

            .payroll-page-head {
                display: block;
            }

            .payroll-page-head .btn {
                margin-top: 12px;
            }
        }

        @media print {
            .no-print, .navbar {
                display: none !important;
            }

            .payroll-shell {
                display: block;
            }
        }
    </style>
    <?php
}

function payrollMigrationNotice($payroll, array $tables, $message = null) {
    $missing = [];

    foreach ($tables as $table) {
        if (!$payroll->tableExists($table)) {
            $missing[] = $table;
        }
    }

    if (!$missing) {
        return;
    }

    ?>
    <div class="alert alert-warning">
        <strong>Database upgrade required.</strong>
        <?php echo htmlspecialchars($message ?: 'This area needs the professional HR payroll schema.'); ?>
        Missing table(s): <code><?php echo htmlspecialchars(implode(', ', $missing)); ?></code>.
        Run <code>database_migrations/hr_payroll_professional_schema.sql</code>.
    </div>
    <?php
}
