<?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 configure approval workflows.";
    header("Location: dashboard.php");
    exit;
}

// Release the session lock on plain page views; the POST branches below still
// need to write flash data, so they keep the session open for themselves.
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    session_write_close();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_workflow'])) {
    $name = trim($_POST['workflow_name']);
    $stmt = $conn->prepare("INSERT INTO payroll_approval_workflows (name, is_active) VALUES (?, 1)");
    $stmt->bind_param('s', $name);
    $stmt->execute();
    $stmt->close();
    header("Location: approval_settings.php");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_stage'])) {
    $workflowId = (int) $_POST['workflow_id'];
    $stageName = trim($_POST['stage_name']);
    $approverType = $_POST['approver_type'];
    $approverRole = $approverType === 'role' ? trim($_POST['approver_role']) : null;
    $approverUserId = $approverType === 'user' ? (int) $_POST['approver_user_id'] : null;

    $maxOrder = $conn->query("SELECT COALESCE(MAX(stage_order),0) as m FROM payroll_approval_stages WHERE workflow_id = $workflowId")->fetch_assoc()['m'];
    $nextOrder = $maxOrder + 1;

    $stmt = $conn->prepare("INSERT INTO payroll_approval_stages (workflow_id, stage_order, stage_name, approver_type, approver_role, approver_user_id) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->bind_param('iisssi', $workflowId, $nextOrder, $stageName, $approverType, $approverRole, $approverUserId);
    $stmt->execute();
    $stmt->close();
    $_SESSION['flash_success'] = "Stage added.";
    header("Location: approval_settings.php?workflow_id=$workflowId");
    exit;
}

if (isset($_GET['delete_stage'])) {
    $stageId = (int) $_GET['delete_stage'];
    $wf = $conn->query("SELECT workflow_id FROM payroll_approval_stages WHERE id = $stageId")->fetch_assoc()['workflow_id'] ?? null;

    $usageCount = $conn->query("SELECT COUNT(*) as c FROM payroll_cycle_approvals WHERE stage_id = $stageId")->fetch_assoc()['c'];

    if ($usageCount > 0) {
        // This stage has real approval history against it -- deactivate instead of
        // deleting, so past cycles' approval trails don't lose a stage they went through.
        $conn->query("UPDATE payroll_approval_stages SET is_active = 0 WHERE id = $stageId");
        $_SESSION['flash_success'] = "This stage has already been used in $usageCount past approval(s), so it's been deactivated instead of deleted (to keep that history intact). It won't be used for new payroll cycles.";
    } else {
        $conn->query("DELETE FROM payroll_approval_stages WHERE id = $stageId");
        $_SESSION['flash_success'] = "Stage removed.";
    }

    header("Location: approval_settings.php" . ($wf ? "?workflow_id=$wf" : ''));
    exit;
}

if (isset($_GET['reactivate_stage'])) {
    $stageId = (int) $_GET['reactivate_stage'];
    $wf = $conn->query("SELECT workflow_id FROM payroll_approval_stages WHERE id = $stageId")->fetch_assoc()['workflow_id'] ?? null;
    $conn->query("UPDATE payroll_approval_stages SET is_active = 1 WHERE id = $stageId");
    $_SESSION['flash_success'] = "Stage reactivated.";
    header("Location: approval_settings.php" . ($wf ? "?workflow_id=$wf" : ''));
    exit;
}

if (isset($_GET['move_stage'])) {
    // move_stage=<id>&dir=up|down -- swap stage_order with neighbor
    $stageId = (int) $_GET['move_stage'];
    $dir = $_GET['dir'] === 'up' ? 'up' : 'down';
    $stage = $conn->query("SELECT * FROM payroll_approval_stages WHERE id = $stageId")->fetch_assoc();
    if ($stage) {
        $cmp = $dir === 'up' ? '<' : '>';
        $order = $dir === 'up' ? 'DESC' : 'ASC';
        $neighbor = $conn->query("SELECT * FROM payroll_approval_stages WHERE workflow_id = {$stage['workflow_id']} AND stage_order $cmp {$stage['stage_order']} ORDER BY stage_order $order LIMIT 1")->fetch_assoc();
        if ($neighbor) {
            $conn->query("UPDATE payroll_approval_stages SET stage_order = {$neighbor['stage_order']} WHERE id = {$stage['id']}");
            $conn->query("UPDATE payroll_approval_stages SET stage_order = {$stage['stage_order']} WHERE id = {$neighbor['id']}");
        }
        header("Location: approval_settings.php?workflow_id={$stage['workflow_id']}");
        exit;
    }
}

$workflows = $conn->query("SELECT * FROM payroll_approval_workflows ORDER BY id ASC");
$selectedWorkflowId = (int) ($_GET['workflow_id'] ?? 1);
$stages = $conn->query("SELECT * FROM payroll_approval_stages WHERE workflow_id = $selectedWorkflowId ORDER BY stage_order ASC");
$users = $conn->query("SELECT id, username, role FROM users ORDER BY username ASC");

$pageTitle = 'Approval Workflow';
$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">Approval Workflows</h3>
    <div class="flex flex-wrap gap-2 mb-4">
        <?php $workflows->data_seek(0); while ($w = $workflows->fetch_assoc()): ?>
            <a href="?workflow_id=<?= $w['id']; ?>" class="text-xs font-bold px-3 py-1.5 rounded-lg border transition active:scale-95 inline-block <?= $selectedWorkflowId === (int)$w['id'] ? 'bg-indigo-600 text-white border-indigo-600' : 'bg-white text-slate-600 border-slate-200'; ?>">
                <?= h($w['name']); ?>
            </a>
        <?php endwhile; ?>
    </div>
    <form method="POST" class="flex gap-3">
        <input type="text" name="workflow_name" placeholder="New workflow name e.g. 'Front Office Payroll'" required class="flex-1 text-sm border border-slate-200 rounded-lg p-3">
        <button type="submit" name="create_workflow" class="bg-slate-900 hover:bg-slate-800 text-white text-xs font-black uppercase px-4 py-2 rounded-lg transition active:scale-95 border border-slate-950">+ New Workflow</button>
    </form>
</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">Stages for this Workflow</h3>
    <p class="text-[11px] text-slate-500 font-semibold mb-4">Add as many stages as you like, in the order they should approve. A payroll cycle moves to the next stage only after the current one approves.</p>

    <div class="space-y-2 mb-5">
        <?php $activeIndex = 0; $stages->data_seek(0); while ($s = $stages->fetch_assoc()):
            $isActive = (int) $s['is_active'] === 1;
            if ($isActive) $activeIndex++;
        ?>
        <div class="flex items-center justify-between <?= $isActive ? 'bg-slate-50 border-slate-200' : 'bg-slate-100/50 border-slate-200 opacity-60'; ?> border rounded-lg px-4 py-3">
            <div class="flex items-center gap-3">
                <?php if ($isActive): ?>
                    <span class="w-6 h-6 rounded-full bg-indigo-600 text-white text-xs font-black flex items-center justify-center"><?= $activeIndex; ?></span>
                <?php else: ?>
                    <span class="w-6 h-6 rounded-full bg-slate-300 text-slate-600 text-xs font-black flex items-center justify-center">—</span>
                <?php endif; ?>
                <div>
                    <p class="text-sm font-bold text-slate-900"><?= h($s['stage_name']); ?> <?php if (!$isActive): ?><span class="text-[9px] font-black uppercase text-slate-400 ml-1">Inactive</span><?php endif; ?></p>
                    <p class="text-[10px] text-slate-500 uppercase font-black tracking-wider">
                        <?= $s['approver_type'] === 'role' ? 'Role: ' . h($s['approver_role']) : 'Specific user'; ?>
                    </p>
                </div>
            </div>
            <div class="flex items-center gap-3 text-xs font-bold">
                <?php if ($isActive): ?>
                    <a href="?workflow_id=<?= $selectedWorkflowId; ?>&move_stage=<?= $s['id']; ?>&dir=up" class="text-slate-500 hover:text-indigo-600 active:scale-95 transition inline-block">↑</a>
                    <a href="?workflow_id=<?= $selectedWorkflowId; ?>&move_stage=<?= $s['id']; ?>&dir=down" class="text-slate-500 hover:text-indigo-600 active:scale-95 transition inline-block">↓</a>
                    <a href="?workflow_id=<?= $selectedWorkflowId; ?>&delete_stage=<?= $s['id']; ?>" class="text-rose-600 hover:underline active:scale-95 transition inline-block" onclick="return confirm('Remove this stage? If it has already been used in a past approval, it will be deactivated instead of deleted so that history is preserved.')">Remove</a>
                <?php else: ?>
                    <a href="?workflow_id=<?= $selectedWorkflowId; ?>&reactivate_stage=<?= $s['id']; ?>" class="text-emerald-600 hover:underline active:scale-95 transition inline-block">Reactivate</a>
                <?php endif; ?>
            </div>
        </div>
        <?php endwhile; ?>
    </div>

    <form method="POST" class="grid grid-cols-1 sm:grid-cols-4 gap-3 items-end border-t border-slate-200 pt-4">
        <input type="hidden" name="workflow_id" value="<?= $selectedWorkflowId; ?>">
        <div>
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Stage Name</label>
            <input type="text" name="stage_name" required placeholder="e.g. Department Manager" 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">Approver Type</label>
            <select name="approver_type" onchange="document.getElementById('roleField').classList.toggle('hidden', this.value!=='role'); document.getElementById('userField').classList.toggle('hidden', this.value!=='user');" class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
                <option value="role">By Role</option>
                <option value="user">Specific User</option>
            </select>
        </div>
        <div id="roleField">
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Role (e.g. manager, admin)</label>
            <input type="text" name="approver_role" placeholder="manager" class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
        </div>
        <div id="userField" class="hidden">
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">User</label>
            <select name="approver_user_id" class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
                <?php $users->data_seek(0); while ($u = $users->fetch_assoc()): ?>
                    <option value="<?= $u['id']; ?>"><?= h($u['username']); ?> (<?= h($u['role']); ?>)</option>
                <?php endwhile; ?>
            </select>
        </div>
        <div>
            <button type="submit" name="add_stage" 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 w-full">+ Add Stage</button>
        </div>
    </form>
</div>

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