<?php
session_start();
date_default_timezone_set('Africa/Lagos');
require __DIR__ . '/../config.php';
require __DIR__ . '/includes/auth_init.php';

if (!$isAdmin) {
    $_SESSION['flash_error'] = "You don't have permission to manage payroll cycles.";
    header("Location: dashboard.php");
    exit;
}

$isSuperAdmin = strtolower(trim($role)) === 'superadmin';

// Delete a cycle -- superadmin only, since this permanently removes every
// payslip, approval record, and send log tied to it (all cascade via FK).
if (isset($_GET['delete_cycle'])) {
    if (!$isSuperAdmin) {
        $_SESSION['flash_error'] = "Only a superadmin can delete a payroll cycle.";
        header("Location: cycles.php");
        exit;
    }
    $cycleId = (int) $_GET['delete_cycle'];
    $cycleName = $conn->query("SELECT name FROM payroll_cycles WHERE id = $cycleId")->fetch_assoc()['name'] ?? null;
    if ($cycleName) {
        $stmt = $conn->prepare("DELETE FROM payroll_cycles WHERE id = ?");
        $stmt->bind_param('i', $cycleId);
        $stmt->execute();
        $stmt->close();
        $_SESSION['flash_success'] = "Payroll cycle '$cycleName' and all its payslips, approval history, and send logs have been permanently deleted.";
    } else {
        $_SESSION['flash_error'] = "Cycle not found.";
    }
    header("Location: cycles.php");
    exit;
}

// Create a new cycle
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_cycle'])) {
    $name = trim($_POST['name']);
    $month = (int) $_POST['payroll_month'];
    $year = (int) $_POST['payroll_year'];
    $startDate = $_POST['start_date'];
    $endDate = $_POST['end_date'];

    // Pick (or create) a workflow to attach -- default to workflow id 1
    $workflowId = 1;

    $stmt = $conn->prepare("INSERT INTO payroll_cycles (name, payroll_month, payroll_year, start_date, end_date, workflow_id, created_by, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'draft')");
    $stmt->bind_param('siissii', $name, $month, $year, $startDate, $endDate, $workflowId, $_SESSION['user_id']);

    try {
        $stmt->execute();
        $_SESSION['flash_success'] = "Payroll cycle '$name' created.";
    } catch (mysqli_sql_exception $e) {
        if ($e->getCode() === 1062) {
            $monthName = date('F', mktime(0, 0, 0, $month, 1));
            $_SESSION['flash_error'] = "A payroll cycle for $monthName $year already exists. Edit or use the existing one instead of creating another.";
        } else {
            $_SESSION['flash_error'] = "Could not create cycle: " . $e->getMessage();
        }
    }
    $stmt->close();
    header("Location: cycles.php");
    exit;
}

$cycles = $conn->query("SELECT * FROM payroll_cycles ORDER BY payroll_year DESC, payroll_month DESC");

$pageTitle = 'Payroll Cycles';
$pageSubtitle = 'Payroll Module';
require __DIR__ . '/includes/layout_header.php';
?>

<div class="bg-white border border-slate-200/80 rounded-xl p-4 shadow-xs">
    <h3 class="text-xs font-black text-slate-900 uppercase tracking-tight mb-4">Create New Payroll Cycle</h3>
    <form method="POST" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4 items-end">
        <div>
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Cycle Name</label>
            <input type="text" name="name" required placeholder="e.g. January 2026"
                   class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
        </div>
        <div>
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Month</label>
            <select name="payroll_month" class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
                <?php for ($m = 1; $m <= 12; $m++): ?>
                    <option value="<?= $m; ?>" <?= ((int)date('n') === $m) ? 'selected' : ''; ?>><?= date('F', mktime(0,0,0,$m,1)); ?></option>
                <?php endfor; ?>
            </select>
        </div>
        <div>
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Year</label>
            <input type="number" name="payroll_year" value="<?= date('Y'); ?>" required
                   class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
        </div>
        <div>
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Start Date</label>
            <input type="date" name="start_date" required class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
        </div>
        <div>
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">End Date</label>
            <input type="date" name="end_date" required class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
        </div>
        <div class="lg:col-span-5">
            <button type="submit" name="create_cycle" class="bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-black uppercase tracking-wider px-5 py-2.5 rounded-lg transition active:scale-95 border border-indigo-700">
                + Create Cycle
            </button>
        </div>
    </form>
</div>

<div class="bg-white border border-slate-200 rounded-xl shadow-xs overflow-hidden">
    <div class="p-4 border-b border-slate-100">
        <h3 class="text-xs font-black text-slate-900 uppercase tracking-tight">All Cycles</h3>
    </div>
    <div class="overflow-x-auto">
        <table class="w-full text-sm">
            <thead class="bg-slate-50 text-slate-400 uppercase text-[9px] font-black tracking-wider">
                <tr>
                    <th class="text-left p-3">Cycle</th>
                    <th class="text-left p-3">Period</th>
                    <th class="text-left p-3">Status</th>
                    <th class="text-left p-3">Actions</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-100">
                <?php while ($c = $cycles->fetch_assoc()):
                    $statusColors = [
                        'draft' => 'bg-slate-50 text-slate-500 border-slate-100',
                        'processing' => 'bg-amber-50 text-amber-700 border-amber-100',
                        'pending_approval' => 'bg-amber-50 text-amber-700 border-amber-100',
                        'approved' => 'bg-emerald-50 text-emerald-700 border-emerald-100',
                        'rejected' => 'bg-rose-50 text-rose-700 border-rose-100',
                        'paid' => 'bg-indigo-50 text-indigo-700 border-indigo-100',
                    ];
                    $badge = $statusColors[$c['status']] ?? 'bg-slate-50 text-slate-500 border-slate-100';
                ?>
                <tr class="hover:bg-slate-50/50 transition">
                    <td class="p-3 font-bold text-slate-900"><?= h($c['name']); ?></td>
                    <td class="p-3 text-slate-600"><?= date('d M', strtotime($c['start_date'])); ?> &ndash; <?= date('d M Y', strtotime($c['end_date'])); ?></td>
                    <td class="p-3"><span class="px-2 py-0.5 text-[10px] font-bold border rounded <?= $badge; ?>"><?= str_replace('_', ' ', $c['status']); ?></span></td>
                    <td class="p-3 space-x-2">
                        <a href="run_cycle.php?cycle_id=<?= $c['id']; ?>" class="text-indigo-600 font-bold text-xs hover:underline active:scale-95 transition inline-block">Process</a>
                        <a href="cycle_approve.php?cycle_id=<?= $c['id']; ?>" class="text-amber-600 font-bold text-xs hover:underline active:scale-95 transition inline-block">Approvals</a>
                        <a href="reports.php?cycle_id=<?= $c['id']; ?>" class="text-slate-600 font-bold text-xs hover:underline active:scale-95 transition inline-block">Reports</a>
                        <a href="send_payslips.php?cycle_id=<?= $c['id']; ?>" class="text-emerald-600 font-bold text-xs hover:underline active:scale-95 transition inline-block">Send Payslips</a>
                        <?php if ($isSuperAdmin):
                            $warning = $c['status'] === 'paid'
                                ? "This cycle has already had payslips SENT to employees. Deleting it will permanently erase every payslip, approval record, and send log for '" . addslashes($c['name']) . "' -- employees will keep the emails they already received, but you will lose all record of it in this system. This cannot be undone. Delete anyway?"
                                : "Permanently delete '" . addslashes($c['name']) . "' and every payslip, approval record, and send log tied to it? This cannot be undone.";
                        ?>
                        <a href="?delete_cycle=<?= $c['id']; ?>" onclick="return confirm('<?= h($warning); ?>')" class="text-rose-600 font-bold text-xs hover:underline active:scale-95 transition inline-block">Delete</a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

<?php require __DIR__ . '/includes/layout_footer.php'; ?>