<?= $this->extend('layouts/enterprise') ?>

<?= $this->section('content') ?>

<?php
$emp  = $overview['employees'];
$att  = $overview['attendance'];
$leave = $overview['leave'];
$pay  = $overview['payroll'];
$assets = $overview['assets'];
$docs   = $overview['documents'];

$statusPill = static function (string $status): string {
    $map = [
        'pending'   => 'on_leave',
        'approved'  => 'active',
        'rejected'  => 'terminated',
        'cancelled' => 'inactive',
        'draft'     => 'on_leave',
        'calculated'=> 'on_leave',
        'paid'      => 'active',
        'locked'    => 'inactive',
    ];
    $class = $map[$status] ?? 'inactive';
    return '<span class="enterprise-status-pill enterprise-status-pill--' . esc($class) . '">' . esc(ucfirst($status)) . '</span>';
};

$formatDate = static fn (?string $d): string => $d ? date('M j, Y', strtotime($d)) : '—';
$formatMoney = static fn ($v) => number_format((float) $v, 3) . ' BHD';
?>

<?= view('partials/workspace_hero', [
    'workspaceCrumbPill'    => 'HRM',
    'workspaceCrumbCurrent' => 'Dashboard',
    'workspaceTitle'        => 'Human Resources Overview',
    'workspaceDesc'         => 'Workforce snapshot, today\'s attendance, pending approvals, and payroll status at a glance.',
    'workspaceAction'       => [
        'href'  => base_url('employees/create'),
        'label' => 'Add Employee',
        'icon'  => 'fa-solid fa-user-plus',
    ],
]) ?>

<div class="enterprise-kpi-grid mb-4">
    <article class="enterprise-kpi-card">
        <div class="enterprise-kpi-header"><span class="enterprise-kpi-label">Total Employees</span><span class="enterprise-kpi-icon"><i class="fa-solid fa-users"></i></span></div>
        <div class="enterprise-kpi-value"><?= $emp['total'] ?></div>
        <div class="enterprise-kpi-footer">
            <span class="enterprise-kpi-badge enterprise-kpi-badge--<?= $emp['new_this_month'] > 0 ? 'positive' : 'positive' ?>">
                <?= $emp['new_this_month'] > 0 ? '+' . $emp['new_this_month'] . ' new this month' : 'no new hires' ?>
            </span>
        </div>
    </article>
    <article class="enterprise-kpi-card">
        <div class="enterprise-kpi-header"><span class="enterprise-kpi-label">Active</span><span class="enterprise-kpi-icon"><i class="fa-solid fa-user-check"></i></span></div>
        <div class="enterprise-kpi-value text-success"><?= $emp['active'] ?></div>
        <div class="enterprise-kpi-footer">
            <span class="enterprise-kpi-badge enterprise-kpi-badge--positive"><?= $overview['departments'] ?> departments</span>
        </div>
    </article>
    <article class="enterprise-kpi-card">
        <div class="enterprise-kpi-header"><span class="enterprise-kpi-label">Present Today</span><span class="enterprise-kpi-icon"><i class="fa-solid fa-circle-check"></i></span></div>
        <div class="enterprise-kpi-value text-success"><?= $att['present'] ?></div>
        <div class="enterprise-kpi-footer">
            <span class="enterprise-kpi-badge enterprise-kpi-badge--<?= $att['late'] > 0 ? 'negative' : 'positive' ?>"><?= $att['late'] ?> late</span>
        </div>
    </article>
    <article class="enterprise-kpi-card">
        <div class="enterprise-kpi-header"><span class="enterprise-kpi-label">Absent Today</span><span class="enterprise-kpi-icon"><i class="fa-solid fa-user-xmark"></i></span></div>
        <div class="enterprise-kpi-value text-danger"><?= $att['absent'] ?></div>
        <div class="enterprise-kpi-footer">
            <span class="enterprise-kpi-badge enterprise-kpi-badge--positive"><?= $att['on_leave'] ?> on leave</span>
        </div>
    </article>
    <article class="enterprise-kpi-card">
        <div class="enterprise-kpi-header"><span class="enterprise-kpi-label">Pending Leave</span><span class="enterprise-kpi-icon"><i class="fa-solid fa-file-lines"></i></span></div>
        <div class="enterprise-kpi-value<?= $leave['pending_count'] > 0 ? ' text-warning' : '' ?>"><?= $leave['pending_count'] ?></div>
        <div class="enterprise-kpi-footer">
            <a href="<?= base_url('leave/requests?status=pending') ?>" class="enterprise-kpi-badge enterprise-kpi-badge--positive text-decoration-none">review requests</a>
        </div>
    </article>
    <article class="enterprise-kpi-card">
        <div class="enterprise-kpi-header"><span class="enterprise-kpi-label">Corrections</span><span class="enterprise-kpi-icon"><i class="fa-solid fa-pen-to-square"></i></span></div>
        <div class="enterprise-kpi-value<?= $att['pending_corrections'] > 0 ? ' text-warning' : '' ?>"><?= $att['pending_corrections'] ?></div>
        <div class="enterprise-kpi-footer">
            <a href="<?= base_url('attendance/corrections?status=pending') ?>" class="enterprise-kpi-badge enterprise-kpi-badge--positive text-decoration-none">attendance fixes</a>
        </div>
    </article>
    <article class="enterprise-kpi-card">
        <div class="enterprise-kpi-header"><span class="enterprise-kpi-label">Assets Assigned</span><span class="enterprise-kpi-icon"><i class="fa-solid fa-boxes-stacked"></i></span></div>
        <div class="enterprise-kpi-value"><?= $assets['assigned'] ?></div>
        <div class="enterprise-kpi-footer">
            <a href="<?= base_url('assets/assignments') ?>" class="enterprise-kpi-badge enterprise-kpi-badge--positive text-decoration-none">view assignments</a>
        </div>
    </article>
    <article class="enterprise-kpi-card">
        <div class="enterprise-kpi-header"><span class="enterprise-kpi-label">Doc Expiry (30d)</span><span class="enterprise-kpi-icon"><i class="fa-solid fa-file-circle-exclamation"></i></span></div>
        <div class="enterprise-kpi-value<?= ($docs['expiring_30'] + $docs['expired']) > 0 ? ' text-warning' : '' ?>"><?= $docs['expiring_30'] + $docs['expired'] ?></div>
        <div class="enterprise-kpi-footer">
            <a href="<?= base_url('documents/expiry') ?>" class="enterprise-kpi-badge enterprise-kpi-badge--positive text-decoration-none"><?= $docs['expired'] ?> expired</a>
        </div>
    </article>
    <article class="enterprise-kpi-card">
        <div class="enterprise-kpi-header"><span class="enterprise-kpi-label">Payroll</span><span class="enterprise-kpi-icon"><i class="fa-solid fa-money-check-dollar"></i></span></div>
        <div class="enterprise-kpi-value" style="font-size:1.25rem;"><?= $pay['run'] ? esc(ucfirst($pay['run']['status'])) : 'No Run' ?></div>
        <div class="enterprise-kpi-footer">
            <span class="enterprise-kpi-badge enterprise-kpi-badge--positive"><?= esc($pay['period_label']) ?></span>
        </div>
    </article>
</div>

<div class="row g-4 mb-4">
    <div class="col-lg-6">
        <div class="enterprise-data-panel h-100">
            <div class="enterprise-data-panel__head">
                <h2 class="enterprise-data-panel__title">Pending Leave Requests</h2>
                <p class="enterprise-data-panel__subtitle">Requests awaiting approval.</p>
            </div>
            <div class="enterprise-data-panel__body">
                <?php if ($leave['pending'] === []): ?>
                    <p class="text-muted text-center py-4 mb-0">No pending leave requests.</p>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="enterprise-data-table">
                            <thead>
                                <tr><th>Employee</th><th>Type</th><th>Dates</th><th>Days</th></tr>
                            </thead>
                            <tbody>
                                <?php foreach ($leave['pending'] as $req): ?>
                                    <tr>
                                        <td>
                                            <a href="<?= base_url('leave/requests/' . $req['id']) ?>" class="enterprise-data-table__primary text-decoration-none">
                                                <?= esc($req['full_name']) ?>
                                            </a>
                                            <br><small class="text-muted"><?= esc($req['employee_number']) ?></small>
                                        </td>
                                        <td><?= esc($req['leave_type_name'] ?? '—') ?></td>
                                        <td><?= $formatDate($req['start_date']) ?> – <?= $formatDate($req['end_date']) ?></td>
                                        <td><?= esc($req['days']) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
            <div class="enterprise-data-panel__toolbar border-top-0 pt-0">
                <a href="<?= base_url('leave/requests') ?>" class="btn btn-sm btn-outline-primary">All Leave Requests</a>
            </div>
        </div>
    </div>

    <div class="col-lg-6">
        <div class="enterprise-data-panel h-100">
            <div class="enterprise-data-panel__head">
                <h2 class="enterprise-data-panel__title">Upcoming Leave (7 Days)</h2>
                <p class="enterprise-data-panel__subtitle">Approved leave starting soon.</p>
            </div>
            <div class="enterprise-data-panel__body">
                <?php if ($leave['upcoming'] === []): ?>
                    <p class="text-muted text-center py-4 mb-0">No approved leave in the next 7 days.</p>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="enterprise-data-table">
                            <thead>
                                <tr><th>Employee</th><th>Type</th><th>Starts</th><th>Days</th></tr>
                            </thead>
                            <tbody>
                                <?php foreach ($leave['upcoming'] as $req): ?>
                                    <tr>
                                        <td>
                                            <span class="enterprise-data-table__primary"><?= esc($req['full_name']) ?></span>
                                            <br><small class="text-muted"><?= esc($req['employee_number']) ?></small>
                                        </td>
                                        <td><?= esc($req['leave_type_name'] ?? '—') ?></td>
                                        <td><?= $formatDate($req['start_date']) ?></td>
                                        <td><?= esc($req['days']) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
            <div class="enterprise-data-panel__toolbar border-top-0 pt-0">
                <a href="<?= base_url('leave/calendar') ?>" class="btn btn-sm btn-outline-primary">Leave Calendar</a>
            </div>
        </div>
    </div>
</div>

<div class="row g-4 mb-4">
    <div class="col-lg-6">
        <div class="enterprise-data-panel h-100">
            <div class="enterprise-data-panel__head">
                <h2 class="enterprise-data-panel__title">Document Expiry Alerts</h2>
                <p class="enterprise-data-panel__subtitle">Expired and documents expiring within 30 days.</p>
            </div>
            <div class="enterprise-data-panel__body">
                <?php
                $expiryAlerts = array_merge($docs['recently_expired'] ?? [], $docs['upcoming'] ?? []);
                ?>
                <?php if ($expiryAlerts === []): ?>
                    <p class="text-muted text-center py-4 mb-0">No document expiry alerts.</p>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="enterprise-data-table">
                            <thead>
                                <tr><th>Employee</th><th>Document</th><th>Expiry</th></tr>
                            </thead>
                            <tbody>
                                <?php foreach (array_slice($expiryAlerts, 0, 8) as $doc): ?>
                                    <tr>
                                        <td>
                                            <a href="<?= base_url('documents/' . $doc['id']) ?>" class="enterprise-data-table__primary text-decoration-none">
                                                <?= esc($doc['full_name']) ?>
                                            </a>
                                            <br><small class="text-muted"><?= esc($doc['employee_number']) ?></small>
                                        </td>
                                        <td><?= esc($doc['type_name']) ?></td>
                                        <td><?= $formatDate($doc['expiry_date']) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
            <div class="enterprise-data-panel__toolbar border-top-0 pt-0">
                <a href="<?= base_url('documents/expiry') ?>" class="btn btn-sm btn-outline-warning">Full Expiry Tracker</a>
            </div>
        </div>
    </div>

    <div class="col-lg-6">
        <div class="enterprise-data-panel h-100">
            <div class="enterprise-data-panel__head">
                <h2 class="enterprise-data-panel__title">Recent Hires</h2>
                <p class="enterprise-data-panel__subtitle">Latest employees added to the directory.</p>
            </div>
            <div class="enterprise-data-panel__body">
                <?php if ($overview['recentHires'] === []): ?>
                    <p class="text-muted text-center py-4 mb-0">No employees in the directory yet.</p>
                <?php else: ?>
                    <ul class="list-unstyled mb-0">
                        <?php foreach ($overview['recentHires'] as $hire): ?>
                            <li class="d-flex justify-content-between align-items-start py-2 border-bottom">
                                <div>
                                    <a href="<?= base_url('employees/' . $hire['id']) ?>" class="fw-semibold text-decoration-none">
                                        <?= esc($hire['full_name']) ?>
                                    </a>
                                    <br><small class="text-muted"><?= esc($hire['department_name'] ?? 'Unassigned') ?></small>
                                </div>
                                <small class="text-muted"><?= $formatDate($hire['hire_date'] ?? $hire['created_at']) ?></small>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<div class="row g-4 mb-4">
    <div class="col-lg-4">
        <div class="enterprise-data-panel h-100">
            <div class="enterprise-data-panel__head">
                <h2 class="enterprise-data-panel__title">Active by Department</h2>
                <p class="enterprise-data-panel__subtitle">Headcount across departments.</p>
            </div>
            <div class="enterprise-data-panel__body">
                <?php if ($overview['byDepartment'] === []): ?>
                    <p class="text-muted text-center py-4 mb-0">No active employees.</p>
                <?php else: ?>
                    <ul class="list-unstyled mb-0">
                        <?php foreach ($overview['byDepartment'] as $dept): ?>
                            <li class="d-flex justify-content-between align-items-center py-2 border-bottom">
                                <span><?= esc($dept['label']) ?></span>
                                <span class="badge bg-light text-dark"><?= (int) $dept['total'] ?></span>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="enterprise-data-panel h-100">
            <div class="enterprise-data-panel__head">
                <h2 class="enterprise-data-panel__title">Upcoming Holidays</h2>
                <p class="enterprise-data-panel__subtitle">Next 30 days on the calendar.</p>
            </div>
            <div class="enterprise-data-panel__body">
                <?php if ($overview['holidays'] === []): ?>
                    <p class="text-muted text-center py-4 mb-0">No upcoming holidays.</p>
                <?php else: ?>
                    <ul class="list-unstyled mb-0">
                        <?php foreach ($overview['holidays'] as $holiday): ?>
                            <li class="d-flex justify-content-between align-items-start py-2 border-bottom">
                                <div>
                                    <span class="fw-semibold"><?= esc($holiday['name']) ?></span>
                                    <?php if (! empty($holiday['description'])): ?>
                                        <br><small class="text-muted"><?= esc($holiday['description']) ?></small>
                                    <?php endif; ?>
                                </div>
                                <small class="text-muted text-nowrap ms-2"><?= $formatDate($holiday['date']) ?></small>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
            <div class="enterprise-data-panel__toolbar border-top-0 pt-0">
                <a href="<?= base_url('holidays') ?>" class="btn btn-sm btn-outline-primary">Manage Holidays</a>
            </div>
        </div>
    </div>
</div>

<div class="enterprise-data-panel mb-4">
    <div class="enterprise-data-panel__head">
        <h2 class="enterprise-data-panel__title">Payroll &amp; Settlements</h2>
        <p class="enterprise-data-panel__subtitle">Current month payroll run and open final settlements.</p>
    </div>
    <div class="enterprise-data-panel__body">
        <div class="row g-3">
            <div class="col-md-6">
                <div class="p-3 border rounded h-100">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="text-muted small text-uppercase"><?= esc($pay['period_label']) ?></span>
                        <?php if ($pay['run']): ?>
                            <?= $statusPill($pay['run']['status']) ?>
                        <?php endif; ?>
                    </div>
                    <?php if ($pay['run'] && $pay['totals']): ?>
                        <div class="row g-2">
                            <div class="col-6"><div class="text-muted small">Employees</div><div class="fw-bold"><?= (int) $pay['totals']['employee_count'] ?></div></div>
                            <div class="col-6"><div class="text-muted small">Net Pay</div><div class="fw-bold"><?= $formatMoney($pay['totals']['total_net']) ?></div></div>
                            <div class="col-6"><div class="text-muted small">Gross</div><div class="fw-bold"><?= $formatMoney($pay['totals']['total_gross']) ?></div></div>
                            <div class="col-6"><div class="text-muted small">Employer Cost</div><div class="fw-bold"><?= $formatMoney($pay['totals']['total_cost']) ?></div></div>
                        </div>
                        <a href="<?= base_url('payroll/runs/' . $pay['run']['id']) ?>" class="btn btn-sm btn-outline-primary mt-3">View Payroll Run</a>
                    <?php else: ?>
                        <p class="text-muted mb-2">No payroll run created for this month yet.</p>
                        <a href="<?= base_url('payroll/runs/create') ?>" class="btn btn-sm btn-primary">Create Payroll Run</a>
                    <?php endif; ?>
                </div>
            </div>
            <div class="col-md-6">
                <div class="p-3 border rounded h-100">
                    <div class="text-muted small text-uppercase mb-2">Open Final Settlements</div>
                    <div class="display-6 fw-bold mb-2"><?= $pay['open_settlements'] ?></div>
                    <p class="text-muted small mb-3">Draft or approved settlements awaiting payment.</p>
                    <div class="d-flex gap-2 flex-wrap">
                        <a href="<?= base_url('payroll/settlements') ?>" class="btn btn-sm btn-outline-primary">Settlements</a>
                        <a href="<?= base_url('payroll/reports/summary') ?>" class="btn btn-sm btn-outline-secondary">Payroll Summary</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="enterprise-data-panel">
    <div class="enterprise-data-panel__head">
        <h2 class="enterprise-data-panel__title">Quick Actions</h2>
        <p class="enterprise-data-panel__subtitle">Jump to common HRM tasks.</p>
    </div>
    <div class="enterprise-data-panel__body">
        <div class="d-flex flex-wrap gap-2">
            <a href="<?= base_url('employees/create') ?>" class="btn btn-sm btn-primary"><i class="fa-solid fa-user-plus me-1"></i>Add Employee</a>
            <a href="<?= base_url('leave/requests/create') ?>" class="btn btn-sm btn-outline-primary"><i class="fa-solid fa-file-circle-plus me-1"></i>New Leave Request</a>
            <a href="<?= base_url('attendance') ?>" class="btn btn-sm btn-outline-primary"><i class="fa-solid fa-fingerprint me-1"></i>Attendance Board</a>
            <a href="<?= base_url('attendance/manual') ?>" class="btn btn-sm btn-outline-secondary"><i class="fa-solid fa-keyboard me-1"></i>Manual Attendance</a>
            <a href="<?= base_url('payroll/runs') ?>" class="btn btn-sm btn-outline-secondary"><i class="fa-solid fa-calendar-check me-1"></i>Payroll Runs</a>
            <a href="<?= base_url('assets/assignments') ?>" class="btn btn-sm btn-outline-secondary"><i class="fa-solid fa-hand-holding me-1"></i>Assign Asset</a>
            <a href="<?= base_url('documents') ?>" class="btn btn-sm btn-outline-secondary"><i class="fa-solid fa-folder-open me-1"></i>Employee Documents</a>
        </div>
    </div>
</div>

<?= $this->endSection() ?>
