<?php
session_start();
if (!isset($_SESSION["user_id"]) || $_SESSION["role"] !== "company_admin") { header("Location: ../auth/login.php"); exit; }
require_once '../config/database.php';
$companyId = (int)$_SESSION["company_id"];

/* ── Save ── */
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["save_allow"])) {
    $staffId   = (int)$_POST["staff_id"];
    $type      = trim($_POST["type"] ?? "");
    $amount    = (float)str_replace(",", "", $_POST["amount"] ?? 0);
    $recurring = isset($_POST["is_recurring"]) ? 1 : 0;
    $effFrom   = $_POST["effective_from"] ?: null;
    $editId    = (int)($_POST["edit_id"] ?? 0);

    if ($type && $amount >= 0) {
        if ($editId) {
            $pdo->prepare("UPDATE hr_allowances SET type=?,amount=?,is_recurring=?,effective_from=? WHERE id=? AND company_id=?")
                ->execute([$type,$amount,$recurring,$effFrom,$editId,$companyId]);
        } else {
            $pdo->prepare("INSERT INTO hr_allowances (staff_id,company_id,type,amount,is_recurring,effective_from) VALUES (?,?,?,?,?,?)")
                ->execute([$staffId,$companyId,$type,$amount,$recurring,$effFrom]);
        }
    }
    header("Location: hr_allowances.php?msg=saved&staff_id=$staffId"); exit;
}

/* ── Delete ── */
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["del_allow"])) {
    $sid = (int)$_POST["staff_id"];
    $pdo->prepare("DELETE FROM hr_allowances WHERE id=? AND company_id=?")->execute([(int)$_POST["allow_id"],$companyId]);
    header("Location: hr_allowances.php?msg=deleted&staff_id=$sid"); exit;
}

$selStaff = (int)($_GET["staff_id"] ?? 0);
$msg      = $_GET["msg"] ?? "";

$allStaff = $pdo->prepare("SELECT u.id,u.name,cs.position,cs.department FROM company_staff cs JOIN users u ON u.id=cs.user_id WHERE cs.company_id=? AND u.status='active' ORDER BY u.name");
$allStaff->execute([$companyId]);
$allStaff = $allStaff->fetchAll(PDO::FETCH_ASSOC);

if (!$selStaff && !empty($allStaff)) $selStaff = $allStaff[0]["id"];

$allows = [];
if ($selStaff) {
    $st = $pdo->prepare("SELECT * FROM hr_allowances WHERE staff_id=? AND company_id=? ORDER BY type");
    $st->execute([$selStaff,$companyId]);
    $allows = $st->fetchAll(PDO::FETCH_ASSOC);
}

$total = array_sum(array_column($allows,"amount"));
$commonTypes = ["Transport","Housing","Meal","Communication","Medical","Uniform","Performance","Other"];
?>
<!DOCTYPE html>
<html lang="lo">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Allowances — <?= htmlspecialchars($_SESSION["company_name"]) ?></title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{--p:#0f766e;--s:#fff;--bg:#f0f4f8;--b:#e2e8f0;--t:#0f172a;--m:#64748b;--g:#16a34a;--gl:#dcfce7;--r:#dc2626;--rl:#fee2e2;--a:#d97706;--al:#fef3c7;--rad:14px;--sh:0 2px 14px rgba(15,23,42,.09)}
body{font-family:"Inter",Arial,sans-serif;background:var(--bg);color:var(--t);min-height:100vh}
.top-bar{background:var(--s);border-bottom:1px solid var(--b);padding:12px 32px;display:flex;align-items:center;gap:14px;position:sticky;top:0;z-index:100;box-shadow:0 1px 6px rgba(15,23,42,.06)}
.back{display:inline-flex;align-items:center;gap:6px;color:var(--m);text-decoration:none;font-size:13px;font-weight:600;padding:6px 12px;border-radius:8px;border:1.5px solid var(--b);transition:all .15s}
.back:hover{border-color:var(--p);color:var(--p)}
h1{font-size:17px;font-weight:800;flex:1}
.pb{padding:24px 32px;max-width:900px;margin:auto}
.alert{padding:12px 16px;border-radius:10px;margin-bottom:18px;font-size:13px;font-weight:600}
.al-s{background:var(--gl);color:var(--g);border:1.5px solid #86efac}
.al-d{background:var(--rl);color:var(--r);border:1.5px solid #fca5a5}
.fbar{display:flex;align-items:center;gap:10px;margin-bottom:18px;flex-wrap:wrap}
.fbar select{padding:9px 13px;border:1.5px solid var(--b);border-radius:9px;font-size:13px;font-family:inherit;outline:none;background:var(--s)}
.fbar select:focus{border-color:var(--p)}
.btn{display:inline-flex;align-items:center;gap:6px;padding:9px 18px;border-radius:9px;font-size:13px;font-weight:700;font-family:inherit;cursor:pointer;border:none;transition:all .15s}
.btn-p{background:linear-gradient(135deg,#084740,#0f766e);color:#fff}.btn-p:hover{opacity:.9}

/* total banner */
.tot-banner{background:linear-gradient(135deg,#084740,#0f766e);border-radius:14px;padding:18px 24px;color:#fff;display:flex;align-items:center;justify-content:space-between;margin-bottom:20px}
.tot-lbl{font-size:12px;opacity:.75;text-transform:uppercase;letter-spacing:.5px}
.tot-val{font-size:28px;font-weight:800;margin-top:4px}

/* allow grid */
.allow-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:12px;margin-bottom:20px}
.acard{background:var(--s);border-radius:var(--rad);box-shadow:var(--sh);border:1px solid var(--b);padding:18px}
.acard-top{display:flex;align-items:center;justify-content:space-between;margin-bottom:10px}
.atype{font-size:14px;font-weight:700}
.amount{font-size:22px;font-weight:800;color:var(--p)}
.acard-sub{font-size:12px;color:var(--m);margin-top:4px}
.acard-actions{display:flex;gap:6px;margin-top:12px;padding-top:12px;border-top:1px solid var(--b)}
.bs{padding:5px 11px;border-radius:7px;font-size:12px;font-weight:700;font-family:inherit;cursor:pointer;border:1.5px solid;display:inline-flex;align-items:center;gap:4px;transition:all .15s}
.be{border-color:#93c5fd;color:#2563eb;background:#eff6ff}.be:hover{background:#2563eb;color:#fff;border-color:#2563eb}
.bd{border-color:#fca5a5;color:var(--r);background:var(--rl)}.bd:hover{background:var(--r);color:#fff;border-color:var(--r)}

/* add card */
.add-card{background:var(--s);border-radius:var(--rad);box-shadow:var(--sh);border:1.5px dashed var(--b);padding:24px}
.add-card h3{font-size:15px;font-weight:800;margin-bottom:16px;padding-bottom:12px;border-bottom:1px solid var(--b)}
.fr2{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.fg{margin-bottom:12px}
.fg label{display:block;font-size:12px;font-weight:700;margin-bottom:4px}
.fg input,.fg select{width:100%;padding:9px 12px;border:1.5px solid var(--b);border-radius:8px;font-size:13px;font-family:inherit;outline:none;background:#f8fafc}
.fg input:focus,.fg select:focus{border-color:var(--p);background:#fff}
.quick-types{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:14px}
.qt{padding:5px 12px;border-radius:999px;border:1.5px solid var(--b);background:var(--s);font-size:12px;font-weight:600;color:var(--m);cursor:pointer;font-family:inherit;transition:all .15s}
.qt:hover{border-color:var(--p);color:var(--p)}

.empty{text-align:center;padding:40px;color:var(--m);font-size:13px}
@media(max-width:700px){.pb{padding:16px}.top-bar{padding:10px 16px}.fr2{grid-template-columns:1fr}}
</style>
</head>
<body>
<div class="top-bar">
    <a class="back" href="dashboard.php">← Dashboard</a>
    <h1>🎁 Allowances</h1>
</div>
<div class="pb">

<?php if($msg==="saved"): ?><div class="alert al-s">✅ Allowance saved.</div>
<?php elseif($msg==="deleted"): ?><div class="alert al-d">🗑️ Allowance deleted.</div><?php endif; ?>

<!-- Staff picker -->
<form method="GET" class="fbar">
    <select name="staff_id" onchange="this.form.submit()">
        <?php foreach($allStaff as $s): ?>
        <option value="<?=$s["id"]?>" <?=$s["id"]===$selStaff?"selected":""?>><?=htmlspecialchars($s["name"])?></option>
        <?php endforeach; ?>
    </select>
</form>

<!-- Total banner -->
<div class="tot-banner">
    <div>
        <div class="tot-lbl">Total Monthly Allowances</div>
        <div class="tot-val">₭ <?=number_format($total,0)?></div>
    </div>
    <span style="font-size:36px;opacity:.6">🎁</span>
</div>

<!-- Current allowances -->
<?php if(empty($allows)): ?>
<div class="empty" style="background:var(--s);border-radius:var(--rad);box-shadow:var(--sh);margin-bottom:20px">No allowances yet. Add one below.</div>
<?php else: ?>
<div class="allow-grid">
<?php foreach($allows as $a): ?>
<div class="acard">
    <div class="acard-top">
        <div class="atype"><?=htmlspecialchars($a["type"])?></div>
        <?php if($a["is_recurring"]): ?><span style="font-size:11px;color:var(--p);font-weight:700;background:#ccfbf1;padding:2px 8px;border-radius:999px">🔄 Monthly</span><?php endif; ?>
    </div>
    <div class="amount">₭ <?=number_format((float)$a["amount"],0)?></div>
    <?php if($a["effective_from"]): ?><div class="acard-sub">From <?=date("d M Y",strtotime($a["effective_from"]))?></div><?php endif; ?>
    <div class="acard-actions">
        <button class="bs be" onclick='editAllow(<?=htmlspecialchars(json_encode($a))?>)'>✏️ Edit</button>
        <form method="POST" onsubmit="return confirm('Delete this allowance?')" style="display:inline">
            <input type="hidden" name="del_allow" value="1">
            <input type="hidden" name="allow_id"  value="<?=$a["id"]?>">
            <input type="hidden" name="staff_id"  value="<?=$selStaff?>">
            <button class="bs bd" type="submit">🗑️</button>
        </form>
    </div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>

<!-- Add / Edit form -->
<div class="add-card">
    <h3 id="formTitle">➕ Add Allowance</h3>
    <form method="POST">
        <input type="hidden" name="save_allow" value="1">
        <input type="hidden" name="staff_id"   value="<?=$selStaff?>">
        <input type="hidden" name="edit_id"    id="editId" value="0">

        <div class="fg">
            <label>Quick type</label>
            <div class="quick-types">
                <?php foreach($commonTypes as $ct): ?>
                <button type="button" class="qt" onclick="document.getElementById('ftype').value='<?=$ct?>'"><?=$ct?></button>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="fr2">
            <div class="fg">
                <label>Type / Name</label>
                <input type="text" name="type" id="ftype" placeholder="e.g. Transport" required>
            </div>
            <div class="fg">
                <label>Amount (₭)</label>
                <input type="number" name="amount" id="famount" min="0" step="1000" required>
            </div>
        </div>
        <div class="fr2">
            <div class="fg">
                <label>Effective From</label>
                <input type="date" name="effective_from" id="feff">
            </div>
            <div class="fg" style="display:flex;align-items:center;gap:10px;padding-top:24px">
                <input type="checkbox" name="is_recurring" id="frec" checked style="width:auto">
                <label for="frec" style="margin:0;font-size:13px;font-weight:600">Monthly recurring</label>
            </div>
        </div>
        <div style="display:flex;gap:10px">
            <button class="btn btn-p" type="submit">💾 Save Allowance</button>
            <button class="btn" type="button" style="background:#f1f5f9;color:var(--m);border:1.5px solid var(--b)" onclick="resetForm()">Reset</button>
        </div>
    </form>
</div>

</div>
<script>
function editAllow(a){
    document.getElementById('formTitle').textContent='✏️ Edit Allowance';
    document.getElementById('editId').value=a.id;
    document.getElementById('ftype').value=a.type;
    document.getElementById('famount').value=a.amount;
    document.getElementById('feff').value=a.effective_from||'';
    document.getElementById('frec').checked=!!a.is_recurring;
    document.querySelector('.add-card').scrollIntoView({behavior:'smooth'});
}
function resetForm(){
    document.getElementById('formTitle').textContent='➕ Add Allowance';
    document.getElementById('editId').value='0';
    document.getElementById('ftype').value='';
    document.getElementById('famount').value='';
    document.getElementById('feff').value='';
    document.getElementById('frec').checked=true;
}
</script>
</body>
</html>