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

$cycleId = (int) ($_GET['cycle_id'] ?? 0);
$stmt = $conn->prepare("SELECT * FROM payroll_cycles WHERE id = ?");
$stmt->bind_param('i', $cycleId);
$stmt->execute();
$cycle = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$cycle) {
    $_SESSION['flash_error'] = "Payroll cycle not found.";
    header("Location: cycles.php");
    exit;
}

// Release the session lock on plain page views; the POST branch below still
// needs to write flash data, so it keeps the session open for itself.
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    session_write_close();
}

// Show the existing approval trail. Rows are only ever created by an
// explicit "Request Approval" action on cycles.php now -- this page used to
// silently create them the first time anyone merely viewed it, which meant
// the approval process could start just from someone clicking in to look,
// with nobody notified. Purely informational here.
$activeStageCount = 0;
if ($cycle['workflow_id']) {
    $activeStageCount = $conn->query("SELECT COUNT(*) as c FROM payroll_approval_stages WHERE workflow_id = {$cycle['workflow_id']} AND is_active = 1")->fetch_assoc()['c'];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['act_on_stage'])) {
    $approvalId = (int) $_POST['approval_id'];
    $action = $_POST['action'] === 'reject' ? 'rejected' : 'approved';
    $comment = trim($_POST['comment'] ?? '');

    $stmt = $conn->prepare("UPDATE payroll_cycle_approvals SET status = ?, acted_by = ?, acted_at = NOW(), comment = ? WHERE id = ? AND status = 'pending'");
    $stmt->bind_param('sisi', $action, $_SESSION['user_id'], $comment, $approvalId);
    $stmt->execute();
    $stmt->close();

    if ($action === 'rejected') {
        $conn->query("UPDATE payroll_cycles SET status = 'rejected' WHERE id = $cycleId");
        $_SESSION['flash_error'] = "Payroll cycle rejected at this stage.";
    } else {
        // Check if there's a next pending stage; if none remain, cycle is fully approved
        $nextStageRes = $conn->query("
            SELECT s.* FROM payroll_cycle_approvals ca
            JOIN payroll_approval_stages s ON s.id = ca.stage_id
            WHERE ca.payroll_cycle_id = $cycleId AND ca.status = 'pending'
            ORDER BY s.stage_order ASC LIMIT 1
        ");
        $nextStage = $nextStageRes->fetch_assoc();

        if (!$nextStage) {
            $conn->query("UPDATE payroll_cycles SET status = 'approved' WHERE id = $cycleId");
            $conn->query("UPDATE payroll_payslip_runs SET status = 'approved' WHERE payroll_cycle_id = $cycleId");
            $_SESSION['flash_success'] = "Final approval given. Payslips are ready to send.";
        } else {
            // Automatically notify the next stage's approver(s) -- without
            // this, an approved stage just silently sits there with nobody
            // told it's their turn now. Resend Reminder on Cycles remains
            // available as the manual fallback if this notification
            // happens to fail to send (e.g. a transient SMTP error).
            require_once __DIR__ . '/includes/approval_notify.php';
            $notifyResult = notifyStageApprovers($conn, $cycle, $nextStage);

            if ($notifyResult['error']) {
                $_SESSION['flash_success'] = "Stage approved. Moved to the {$nextStage['stage_name']} stage, but the notification email couldn't be sent (" . $notifyResult['error'] . "). Use Resend Reminder on Cycles if needed.";
            } elseif ($notifyResult['sent'] > 0) {
                $_SESSION['flash_success'] = "Stage approved. Notified {$notifyResult['sent']} approver(s) at the {$nextStage['stage_name']} stage.";
            } else {
                $_SESSION['flash_success'] = "Stage approved. Moved to the {$nextStage['stage_name']} stage, but nobody could be notified (no matching user, or no email on file). Use Resend Reminder on Cycles if needed.";
            }
        }
    }
    header("Location: cycle_approve.php?cycle_id=$cycleId");
    exit;
}

$approvals = $conn->query("
    SELECT ca.*, s.stage_name, s.stage_order, s.approver_type, s.approver_role, s.approver_user_id, u.username as acted_by_name
    FROM payroll_cycle_approvals ca
    JOIN payroll_approval_stages s ON s.id = ca.stage_id
    LEFT JOIN users u ON u.id = ca.acted_by
    WHERE ca.payroll_cycle_id = $cycleId
    ORDER BY s.stage_order ASC
");
$rows = [];
while ($a = $approvals->fetch_assoc()) { $rows[] = $a; }

// Has a stage been added (or reactivated) to the workflow since this
// cycle's trail was created/last synced? Surfaced here so it's obvious WHY
// a stage is missing, rather than silently absent -- syncing it in is a
// deliberate action (Resend Reminder on Cycles), not automatic. Only
// relevant once a trail actually exists; an empty trail already gets its
// own "approval hasn't been requested yet" message further down.
$missingStageCount = 0;
if ($activeStageCount > 0 && !empty($rows)) {
    $trailStageIds = array_column($rows, 'stage_id');
    $activeStageIdsRes = $conn->query("SELECT id FROM payroll_approval_stages WHERE workflow_id = {$cycle['workflow_id']} AND is_active = 1");
    $activeStageIds = [];
    while ($s = $activeStageIdsRes->fetch_assoc()) { $activeStageIds[] = $s['id']; }
    $missingStageCount = count(array_diff($activeStageIds, $trailStageIds));
}

// Determine current actionable stage (first pending one, in order) and whether this user can act on it
$currentApprovalId = null;
$canAct = false;
foreach ($rows as $r) {
    if ($r['status'] === 'pending') {
        $currentApprovalId = $r['id'];
        if ($r['approver_type'] === 'role' && strtolower(trim($role)) === strtolower(trim($r['approver_role']))) {
            $canAct = true;
        } elseif ($r['approver_type'] === 'user' && (int) $r['approver_user_id'] === (int) $_SESSION['user_id']) {
            $canAct = true;
        }
        if ($isAdmin) { $canAct = true; } // admins can always act, adjust if you want stricter control
        break;
    }
}

// What's actually being approved -- a summary of the underlying payroll
// numbers. The approve/reject buttons used to be all an approver ever saw
// on this page, with no visibility into what they were approving at all.
$summary = $conn->query("
    SELECT
        COUNT(*) as emp_count,
        COALESCE(SUM(gross_earnings), 0) as total_gross,
        COALESCE(SUM(total_deductions), 0) as total_deductions,
        COALESCE(SUM(net_pay), 0) as total_net,
        COALESCE(SUM(CASE WHEN lop_amount > 0 OR surcharge_amount > 0 THEN 1 ELSE 0 END), 0) as flagged_count
    FROM payroll_payslip_runs
    WHERE payroll_cycle_id = $cycleId
")->fetch_assoc();

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

<div class="bg-white border border-slate-200/80 rounded-xl p-4 shadow-xs">
    <div class="flex items-center justify-between mb-4">
        <h3 class="text-xs font-black text-slate-900 uppercase tracking-tight">What You're Approving</h3>
        <a href="reports.php?cycle_id=<?= $cycleId; ?>" class="text-indigo-600 font-bold text-[11px] hover:underline">View Full Report &rarr;</a>
    </div>
    <div class="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-2">
        <div class="bg-slate-50 border border-slate-200 rounded-lg p-3">
            <p class="text-[9px] font-black text-slate-500 uppercase tracking-wider">Employees Paid</p>
            <h4 class="text-lg font-black text-slate-900 mt-0.5"><?= (int) $summary['emp_count']; ?></h4>
        </div>
        <div class="bg-slate-50 border border-slate-200 rounded-lg p-3">
            <p class="text-[9px] font-black text-slate-500 uppercase tracking-wider">Total Gross</p>
            <h4 class="text-lg font-black text-slate-900 mt-0.5">&#8358;<?= number_format($summary['total_gross'], 2); ?></h4>
        </div>
        <div class="bg-slate-50 border border-slate-200 rounded-lg p-3">
            <p class="text-[9px] font-black text-slate-500 uppercase tracking-wider">Total Deductions</p>
            <h4 class="text-lg font-black text-slate-900 mt-0.5">&#8358;<?= number_format($summary['total_deductions'], 2); ?></h4>
        </div>
        <div class="bg-emerald-50 border border-emerald-200 rounded-lg p-3">
            <p class="text-[9px] font-black text-emerald-700 uppercase tracking-wider">Total Net Pay</p>
            <h4 class="text-lg font-black text-emerald-800 mt-0.5">&#8358;<?= number_format($summary['total_net'], 2); ?></h4>
        </div>
    </div>
    <?php if ((int) $summary['flagged_count'] > 0): ?>
        <p class="text-[11px] text-amber-700 font-semibold bg-amber-50 border border-amber-200 rounded-lg px-3 py-2 mt-1">
            &#9888; <?= (int) $summary['flagged_count']; ?> employee(s) have LOP or surcharge deductions applied this cycle -- worth a look in the <a href="reports.php?cycle_id=<?= $cycleId; ?>" class="underline font-bold">full report</a> before approving.
        </p>
    <?php endif; ?>
</div>

<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-1"><?= h($cycle['name']); ?> &mdash; Approval Trail</h3>
    <p class="text-[11px] text-slate-500 font-semibold mb-5">Cycle status: <span class="uppercase font-black"><?= str_replace('_',' ', $cycle['status']); ?></span></p>

    <?php if ($missingStageCount > 0): ?>
        <div class="mb-4 bg-violet-50 border border-violet-200 text-violet-800 rounded-lg p-3.5 text-xs font-semibold">
            <?= $missingStageCount; ?> stage(s) have been added to this workflow since this cycle's trail was created, so they're not showing below yet.
            Go to <a href="cycles.php" class="underline font-bold">Payroll Cycles</a> and use <strong>Resend Reminder</strong> on this cycle's row to sync them in.
        </div>
    <?php endif; ?>

    <div class="space-y-3">
        <?php foreach ($rows as $r):
            $badge = ['pending' => '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'][$r['status']];
        ?>
        <div class="flex items-center justify-between border border-slate-200 rounded-lg px-4 py-3 <?= $r['id'] === $currentApprovalId ? 'ring-2 ring-indigo-400' : ''; ?>">
            <div>
                <p class="text-sm font-bold text-slate-900">Stage <?= $r['stage_order']; ?>: <?= h($r['stage_name']); ?></p>
                <p class="text-[10px] text-slate-500 uppercase font-black tracking-wider">
                    <?= $r['approver_type'] === 'role' ? 'Approver role: ' . h($r['approver_role']) : 'Specific approver'; ?>
                    <?php if ($r['acted_by_name']): ?> &bull; Acted by <?= h($r['acted_by_name']); ?> on <?= date('d M Y H:i', strtotime($r['acted_at'])); ?><?php endif; ?>
                </p>
                <?php if ($r['comment']): ?><p class="text-xs text-slate-600 mt-1 italic">"<?= h($r['comment']); ?>"</p><?php endif; ?>
            </div>
            <span class="px-2 py-0.5 text-[10px] font-bold border rounded <?= $badge; ?>"><?= $r['status']; ?></span>
        </div>
        <?php endforeach; ?>
    </div>

    <?php if (empty($rows) && $activeStageCount === 0): ?>
        <div class="mt-2 bg-amber-50 border border-amber-200 text-amber-800 rounded-lg p-3.5 text-xs font-semibold">
            This cycle's workflow has no <strong>active</strong> approval stages configured, so there's nothing to approve here yet.
            Go to <a href="approval_settings.php" class="underline font-bold">Approval Workflow</a> and add (or reactivate) at least one stage for this workflow, then reopen this page.
        </div>
    <?php elseif (empty($rows)): ?>
        <div class="mt-2 bg-slate-50 border border-slate-200 text-slate-600 rounded-lg p-3.5 text-xs font-semibold">
            Approval hasn't been requested for this cycle yet. Go to <a href="cycles.php" class="underline font-bold">Payroll Cycles</a> and use <strong>Request Approval</strong> on this cycle's row to start the approval trail and notify the first-stage approver.
        </div>
    <?php elseif ($currentApprovalId && $canAct && $cycle['status'] !== 'rejected'): ?>
    <form method="POST" class="mt-5 border-t border-slate-200 pt-4 space-y-3">
        <input type="hidden" name="approval_id" value="<?= $currentApprovalId; ?>">
        <textarea name="comment" placeholder="Optional comment" class="w-full text-sm border border-slate-200 rounded-lg p-3" rows="2"></textarea>
        <div class="flex gap-3">
            <button type="submit" name="act_on_stage" value="1" data-action="approve" onclick="document.getElementById('actionField').value='approve'" class="bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-black uppercase px-5 py-2.5 rounded-lg transition active:scale-95 border border-emerald-700">Approve Stage</button>
            <button type="submit" name="act_on_stage" value="1" onclick="document.getElementById('actionField').value='reject'" class="bg-rose-600 hover:bg-rose-700 text-white text-xs font-black uppercase px-5 py-2.5 rounded-lg transition active:scale-95 border border-rose-700">Reject</button>
            <input type="hidden" name="action" id="actionField" value="approve">
        </div>
    </form>
    <?php elseif ($currentApprovalId): ?>
        <p class="mt-5 text-xs text-slate-500 italic">Waiting on the assigned approver for the current stage.</p>
    <?php endif; ?>
</div>

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