<?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 pay components.";
    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_component'])) {
    $name = trim($_POST['name']);
    $code = strtolower(preg_replace('/[^a-zA-Z0-9]+/', '_', trim($_POST['name'])));
    $type = $_POST['type'];
    $category = $_POST['category'];
    $isTaxable = isset($_POST['is_taxable']) ? 1 : 0;
    $isDefault = isset($_POST['is_default']) ? 1 : 0;
    $calcType = ($_POST['calculation_type'] ?? 'fixed') === 'percentage_of_gross' ? 'percentage_of_gross' : 'fixed';
    $pctValue = $calcType === 'percentage_of_gross' ? (float) ($_POST['percentage_value'] ?? 0) : null;

    $maxOrder = $conn->query("SELECT COALESCE(MAX(display_order),0) as m FROM payroll_pay_components")->fetch_assoc()['m'];
    $nextOrder = $maxOrder + 1;

    $stmt = $conn->prepare("INSERT INTO payroll_pay_components (name, code, type, category, is_taxable, is_default, calculation_type, percentage_value, display_order, is_active) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)");
    $stmt->bind_param('ssssiisdi', $name, $code, $type, $category, $isTaxable, $isDefault, $calcType, $pctValue, $nextOrder);
    try {
        $stmt->execute();
        $_SESSION['flash_success'] = "Component '$name' added.";
    } catch (mysqli_sql_exception $e) {
        if ($e->getCode() === 1062) {
            $_SESSION['flash_error'] = "A component named (or coded as) '$name' already exists. Choose a different name.";
        } else {
            $_SESSION['flash_error'] = "Could not add component: " . $e->getMessage();
        }
    }
    $stmt->close();
    header("Location: components.php");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_component'])) {
    $id = (int) $_POST['component_id'];
    $name = trim($_POST['name']);
    $type = $_POST['type'];
    $category = $_POST['category'];
    $isTaxable = isset($_POST['is_taxable']) ? 1 : 0;
    $isDefault = isset($_POST['is_default']) ? 1 : 0;
    $calcType = ($_POST['calculation_type'] ?? 'fixed') === 'percentage_of_gross' ? 'percentage_of_gross' : 'fixed';
    $pctValue = $calcType === 'percentage_of_gross' ? (float) ($_POST['percentage_value'] ?? 0) : null;

    // Statutory components: only name/category are safe to change, type/taxable stay locked to how the engine expects them
    $isStatutory = $conn->query("SELECT is_statutory FROM payroll_pay_components WHERE id = $id")->fetch_assoc()['is_statutory'] ?? 0;

    if ($isStatutory) {
        $stmt = $conn->prepare("UPDATE payroll_pay_components SET name = ? WHERE id = ?");
        $stmt->bind_param('si', $name, $id);
    } else {
        $stmt = $conn->prepare("UPDATE payroll_pay_components SET name = ?, type = ?, category = ?, is_taxable = ?, is_default = ?, calculation_type = ?, percentage_value = ? WHERE id = ?");
        $stmt->bind_param('sssiisdi', $name, $type, $category, $isTaxable, $isDefault, $calcType, $pctValue, $id);
    }
    $stmt->execute();
    $stmt->close();
    $_SESSION['flash_success'] = "Component '$name' updated.";
    header("Location: components.php");
    exit;
}

if (isset($_GET['toggle_active'])) {
    $id = (int) $_GET['toggle_active'];
    $conn->query("UPDATE payroll_pay_components SET is_active = 1 - is_active WHERE id = $id AND is_statutory = 0");
    header("Location: components.php");
    exit;
}

if (isset($_GET['toggle_default'])) {
    $id = (int) $_GET['toggle_default'];
    $conn->query("UPDATE payroll_pay_components SET is_default = 1 - is_default WHERE id = $id");
    header("Location: components.php");
    exit;
}

if (isset($_GET['move'])) {
    // move=<id>&dir=up|down -- swap display_order with the neighbor in the same type group (earning/deduction)
    $id = (int) $_GET['move'];
    $dir = $_GET['dir'] === 'up' ? 'up' : 'down';
    $comp = $conn->query("SELECT * FROM payroll_pay_components WHERE id = $id")->fetch_assoc();
    if ($comp) {
        $cmp = $dir === 'up' ? '<' : '>';
        $order = $dir === 'up' ? 'DESC' : 'ASC';
        $type = $comp['type'];
        $neighbor = $conn->query("
            SELECT * FROM payroll_pay_components
            WHERE type = '$type' AND is_statutory = {$comp['is_statutory']} AND display_order $cmp {$comp['display_order']}
            ORDER BY display_order $order LIMIT 1
        ")->fetch_assoc();
        if ($neighbor) {
            $conn->query("UPDATE payroll_pay_components SET display_order = {$neighbor['display_order']} WHERE id = {$comp['id']}");
            $conn->query("UPDATE payroll_pay_components SET display_order = {$comp['display_order']} WHERE id = {$neighbor['id']}");
        }
    }
    header("Location: components.php");
    exit;
}

$editId = isset($_GET['edit']) ? (int) $_GET['edit'] : 0;
$editing = null;
if ($editId) {
    $stmt = $conn->prepare("SELECT * FROM payroll_pay_components WHERE id = ?");
    $stmt->bind_param('i', $editId);
    $stmt->execute();
    $editing = $stmt->get_result()->fetch_assoc();
    $stmt->close();
}

$components = $conn->query("SELECT * FROM payroll_pay_components ORDER BY is_statutory ASC, display_order ASC, name ASC");

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

<?php if ($editing): ?>
<div class="bg-white border-2 border-indigo-300 rounded-xl p-4 shadow-xs">
    <h3 class="text-xs font-black text-slate-900 uppercase tracking-tight mb-4">Edit Component: <?= h($editing['name']); ?></h3>
    <form method="POST" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-4 items-end">
        <input type="hidden" name="component_id" value="<?= $editing['id']; ?>">
        <div class="lg:col-span-2">
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Name</label>
            <input type="text" name="name" required value="<?= h($editing['name']); ?>"
                   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">Type</label>
            <select name="type" <?= $editing['is_statutory'] ? 'disabled' : ''; ?> class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3 disabled:bg-slate-100">
                <option value="earning" <?= $editing['type']==='earning'?'selected':''; ?>>Earning</option>
                <option value="deduction" <?= $editing['type']==='deduction'?'selected':''; ?>>Deduction</option>
            </select>
        </div>
        <div>
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Category</label>
            <select name="category" <?= $editing['is_statutory'] ? 'disabled' : ''; ?> class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3 disabled:bg-slate-100">
                <?php foreach (['allowance'=>'Allowance','bonus'=>'Bonus','deduction_other'=>'Other Deduction','statutory'=>'Statutory','custom'=>'Custom'] as $val=>$lbl): ?>
                    <option value="<?= $val; ?>" <?= $editing['category']===$val?'selected':''; ?>><?= $lbl; ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="flex items-center gap-2 pb-2">
            <input type="checkbox" name="is_taxable" <?= $editing['is_taxable']?'checked':''; ?> <?= $editing['is_statutory'] ? 'disabled' : ''; ?> id="edit_is_taxable" class="rounded">
            <label for="edit_is_taxable" class="text-xs font-bold text-slate-700">Taxable</label>
        </div>
        <div class="flex items-center gap-2 pb-2">
            <input type="checkbox" name="is_default" <?= $editing['is_default']?'checked':''; ?> <?= $editing['is_statutory'] ? 'disabled' : ''; ?> id="edit_is_default" class="rounded">
            <label for="edit_is_default" class="text-xs font-bold text-slate-700">Default for all employees</label>
        </div>
        <?php if (!$editing['is_statutory']): ?>
        <div>
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Amount Comes From</label>
            <select name="calculation_type" id="edit_calc_type" onchange="document.getElementById('edit_pct_field').classList.toggle('hidden', this.value !== 'percentage_of_gross')" class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
                <option value="fixed" <?= $editing['calculation_type']==='fixed'?'selected':''; ?>>Fixed Amount (manual entry)</option>
                <option value="percentage_of_gross" <?= $editing['calculation_type']==='percentage_of_gross'?'selected':''; ?>>% of Employee's Gross Salary</option>
            </select>
        </div>
        <div id="edit_pct_field" class="<?= $editing['calculation_type']==='percentage_of_gross' ? '' : 'hidden'; ?>">
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Percentage</label>
            <input type="number" step="0.01" name="percentage_value" value="<?= h($editing['percentage_value'] ?? ''); ?>" placeholder="e.g. 40"
                   class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
        </div>
        <?php endif; ?>
        <div class="lg:col-span-6 flex gap-3">
            <button type="submit" name="update_component" 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">
                Save Changes
            </button>
            <a href="components.php" class="text-xs font-bold text-slate-500 self-center hover:underline active:scale-95 transition inline-block">Cancel</a>
        </div>
    </form>
    <?php if ($editing['is_statutory']): ?>
        <p class="text-[10px] text-slate-500 font-semibold mt-3">Type, category, and taxable status are locked for statutory components since the calculation engine relies on them. Only the display name can be changed here.</p>
    <?php endif; ?>
</div>
<?php endif; ?>

<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">Add Pay Component</h3>
    <form method="POST" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-4 items-end">
        <div class="lg:col-span-2">
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Name</label>
            <input type="text" name="name" required placeholder="e.g. Transport Allowance"
                   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">Type</label>
            <select name="type" class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
                <option value="earning">Earning</option>
                <option value="deduction">Deduction</option>
            </select>
        </div>
        <div>
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Category</label>
            <select name="category" class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
                <option value="allowance">Allowance</option>
                <option value="bonus">Bonus</option>
                <option value="deduction_other">Other Deduction</option>
                <option value="custom">Custom</option>
            </select>
        </div>
        <div class="flex items-center gap-2 pb-2">
            <input type="checkbox" name="is_taxable" id="is_taxable" class="rounded">
            <label for="is_taxable" class="text-xs font-bold text-slate-700">Taxable</label>
        </div>
        <div class="flex items-center gap-2 pb-2">
            <input type="checkbox" name="is_default" id="is_default" class="rounded">
            <label for="is_default" class="text-xs font-bold text-slate-700">Default for all employees</label>
        </div>
        <div>
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Amount Comes From</label>
            <select name="calculation_type" onchange="document.getElementById('add_pct_field').classList.toggle('hidden', this.value !== 'percentage_of_gross')" class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
                <option value="fixed">Fixed Amount (manual entry)</option>
                <option value="percentage_of_gross">% of Employee's Gross Salary</option>
            </select>
        </div>
        <div id="add_pct_field" class="hidden">
            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Percentage</label>
            <input type="number" step="0.01" name="percentage_value" placeholder="e.g. 40"
                   class="mt-1 w-full text-sm border border-slate-200 rounded-lg p-3">
        </div>
        <div class="lg:col-span-6">
            <button type="submit" name="create_component" 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">
                + Add Component
            </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 Components</h3>
        <p class="text-[10px] text-slate-500 font-semibold mt-1">Statutory components (PAYE, Pension, NHF, NHIS) are system-calculated from Settings and can't be edited here, but you can turn them on/off in <a href="settings.php" class="text-indigo-600 underline">Statutory Settings</a>.</p>
    </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">Order</th>
                    <th class="text-left p-3">Name</th>
                    <th class="text-left p-3">Type</th>
                    <th class="text-left p-3">Category</th>
                    <th class="text-left p-3">Calculation</th>
                    <th class="text-left p-3">Taxable</th>
                    <th class="text-left p-3">Default for All</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 = $components->fetch_assoc()): ?>
                <tr class="hover:bg-slate-50/50 transition <?= $c['is_statutory'] ? 'bg-slate-50/60' : ''; ?>">
                    <td class="p-3 text-xs font-bold">
                        <a href="?move=<?= $c['id']; ?>&dir=up" class="text-slate-400 hover:text-indigo-700">&uarr;</a>
                        <a href="?move=<?= $c['id']; ?>&dir=down" class="text-slate-400 hover:text-indigo-700">&darr;</a>
                    </td>
                    <td class="p-3 font-bold text-slate-900"><?= h($c['name']); ?> <?php if ($c['is_statutory']): ?><span class="text-[9px] text-indigo-600 font-black uppercase ml-1">Statutory</span><?php endif; ?></td>
                    <td class="p-3 capitalize text-slate-600"><?= $c['type']; ?></td>
                    <td class="p-3 capitalize text-slate-600"><?= str_replace('_',' ', $c['category']); ?></td>
                    <td class="p-3">
                        <?php if ($c['calculation_type'] === 'percentage_of_gross'): ?>
                            <span class="px-2 py-0.5 text-[10px] font-bold border rounded bg-indigo-50 text-indigo-700 border-indigo-100"><?= h($c['percentage_value']); ?>% of Gross</span>
                        <?php else: ?>
                            <span class="text-slate-400 text-[11px]">Fixed</span>
                        <?php endif; ?>
                    </td>
                    <td class="p-3"><?= $c['is_taxable'] ? 'Yes' : 'No'; ?></td>
                    <td class="p-3">
                        <?php if ($c['is_statutory']): ?>
                            <span class="text-slate-400">Always</span>
                        <?php else: ?>
                            <a href="?toggle_default=<?= $c['id']; ?>" class="font-bold <?= $c['is_default'] ? 'text-emerald-700' : 'text-slate-400'; ?>"><?= $c['is_default'] ? 'Yes' : 'No'; ?></a>
                        <?php endif; ?>
                    </td>
                    <td class="p-3">
                        <span class="px-2 py-0.5 text-[10px] font-bold border rounded <?= $c['is_active'] ? 'bg-emerald-50 text-emerald-700 border-emerald-100' : 'bg-slate-100 text-slate-500 border-slate-200'; ?>"><?= $c['is_active'] ? 'Active' : 'Inactive'; ?></span>
                    </td>
                    <td class="p-3 space-x-2">
                        <a href="?edit=<?= $c['id']; ?>" class="text-indigo-600 font-bold text-xs hover:underline active:scale-95 transition inline-block">Edit</a>
                        <?php if (!$c['is_statutory']): ?>
                            <a href="?toggle_active=<?= $c['id']; ?>" class="text-slate-600 font-bold text-xs hover:underline active:scale-95 transition inline-block"><?= $c['is_active'] ? 'Deactivate' : 'Activate'; ?></a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

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