<?php
/* ============================================================================
 *  company/reminder_test.php — admin tool to test push reminders per staff.
 *  Shows who has a push subscription and sends a test notification, reporting
 *  the real delivery result (HTTP code) per device. Helps find who didn't
 *  enable alerts / whose subscription expired.
 * ==========================================================================*/
session_start();
if (!isset($_SESSION["user_id"]) || $_SESSION["role"] !== "company_admin") {
    header("Location: ../auth/login.php"); exit;
}
require_once '../config/database.php';
require_once '../config/webpush.php';
date_default_timezone_set('Asia/Vientiane');
$companyId   = (int)$_SESSION["company_id"];
$companyName = $_SESSION["company_name"] ?? "My Company";

/* ── AJAX: send a test push to one staff ── */
if ($_SERVER["REQUEST_METHOD"] === "POST" && ($_POST["action"] ?? "") === "send") {
    header('Content-Type: application/json; charset=utf-8');
    $uid = (int)($_POST["uid"] ?? 0);
    /* staff must belong to this company */
    $chk = $pdo->prepare("SELECT 1 FROM company_staff WHERE user_id=? AND company_id=? LIMIT 1");
    $chk->execute([$uid,$companyId]);
    if (!$chk->fetchColumn()) { echo json_encode(["ok"=>false,"error"=>"not your staff"]); exit; }

    $subs = $pdo->prepare("SELECT id,endpoint,p256dh,auth FROM push_subscriptions WHERE user_id=?");
    $subs->execute([$uid]); $subs = $subs->fetchAll(PDO::FETCH_ASSOC);
    if (!$subs) { echo json_encode(["ok"=>false,"error"=>"no devices — this staff has not enabled alerts"]); exit; }

    $payload = json_encode(["title"=>"⏰ Reminder test","body"=>"Test clock-in reminder — if you see this, alerts work.","url"=>"staff/checkin.php"], JSON_UNESCAPED_UNICODE);
    $codes = []; $ok = 0;
    foreach ($subs as $s) {
        $r = webpush_send($s, $payload);
        $codes[] = $r['code'];
        if ($r['ok']) $ok++;
        if (!empty($r['gone'])) { $pdo->prepare("DELETE FROM push_subscriptions WHERE id=?")->execute([$s['id']]); }
    }
    echo json_encode(["ok"=>$ok>0, "devices"=>count($subs), "sent"=>$ok, "codes"=>$codes]); exit;
}

/* ── staff + subscription counts ── */
$staff = $pdo->prepare("
    SELECT u.id, u.name, cs.staff_code, cs.department
    FROM company_staff cs JOIN users u ON u.id=cs.user_id AND u.status='active'
    WHERE cs.company_id=?
    ORDER BY (cs.staff_code IS NULL OR cs.staff_code=''), cs.staff_code, u.name");
$staff->execute([$companyId]); $staff = $staff->fetchAll(PDO::FETCH_ASSOC);

$subCount = [];
try {
    $sc = $pdo->query("SELECT user_id, COUNT(*) c FROM push_subscriptions GROUP BY user_id");
    foreach ($sc->fetchAll(PDO::FETCH_ASSOC) as $r) $subCount[(int)$r['user_id']] = (int)$r['c'];
} catch (Throwable $e) {}

$withDevice = 0; foreach ($staff as $s) if (!empty($subCount[(int)$s['id']])) $withDevice++;
$total = count($staff);
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <?php $pwaTheme='#0f766e'; include __DIR__.'/../config/pwa_head.php'; ?>
    <title><?= htmlspecialchars($companyName) ?> — Reminder Test</title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;500;600;700;800&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <script src="../assets/lang.js" defer></script>
    <style>
        *,*::before,*::after{box-sizing:border-box;margin:0;padding:0;}
        :root{--primary:#0f766e;--surface:#fff;--bg:#f0f4f8;--border:#e2e8f0;--text:#0f172a;--muted:#64748b;--green:#16a34a;--green-lt:#dcfce7;--red:#dc2626;--red-lt:#fee2e2;--amber:#d97706;--amber-lt:#fef3c7;--radius:14px;--shadow:0 2px 14px rgba(15,23,42,.07);}
        body{font-family:"Noto Sans Lao","Inter",Arial,sans-serif;background:var(--bg);color:var(--text);min-height:100vh;}
        .top-bar{background:var(--surface);border-bottom:1px solid var(--border);padding:calc(12px + env(safe-area-inset-top,0px)) 24px 12px;display:flex;justify-content:space-between;align-items:center;gap:14px;position:sticky;top:0;z-index:100;box-shadow:0 1px 6px rgba(15,23,42,.06);flex-wrap:wrap;}
        .back-link{display:inline-flex;align-items:center;gap:6px;background:#f1f5f9;color:var(--text);border:1.5px solid var(--border);padding:7px 13px;border-radius:8px;text-decoration:none;font-size:13px;font-weight:700;}
        .lang-bar{display:flex;gap:7px;}
        .lang-btn{padding:4px 11px;border-radius:999px;border:1.5px solid var(--border);background:var(--surface);font-size:11px;font-weight:700;color:var(--muted);cursor:pointer;font-family:inherit;}
        .lang-btn.active{background:var(--primary);border-color:var(--primary);color:#fff;}
        .page{max-width:940px;margin:auto;padding:22px 18px;}
        h1{font-size:21px;font-weight:800;}
        .sub{color:var(--muted);font-size:13px;margin:4px 0 16px;}
        .stats{display:flex;gap:12px;flex-wrap:wrap;margin-bottom:16px;}
        .sb{background:var(--surface);border:1px solid var(--border);border-radius:12px;padding:12px 18px;box-shadow:var(--shadow);}
        .sb .v{font-size:22px;font-weight:800;}.sb .l{font-size:11px;color:var(--muted);font-weight:700;text-transform:uppercase;}
        .card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow);overflow:hidden;}
        .tbl-wrap{overflow-x:auto;}
        table{width:100%;border-collapse:collapse;font-size:14px;min-width:620px;}
        th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.3px;color:var(--muted);padding:11px;border-bottom:2px solid var(--border);background:#f8fafc;}
        td{padding:10px 11px;border-bottom:1px solid var(--border);vertical-align:middle;}
        tr:last-child td{border-bottom:none;}
        .nm{font-weight:700;}.sc{font-size:11px;color:var(--muted);}
        .tag{display:inline-block;padding:3px 10px;border-radius:999px;font-size:11px;font-weight:800;}
        .tag.on{background:var(--green-lt);color:#15803d;}.tag.off{background:var(--red-lt);color:#b91c1b;}
        .btn{background:var(--primary);color:#fff;border:none;padding:8px 14px;border-radius:8px;font-weight:800;font-size:12px;cursor:pointer;font-family:inherit;}
        .btn:disabled{opacity:.5;cursor:default;}
        .btn.all{background:#1e40af;}
        .res{font-size:12px;font-weight:700;}
        .res.ok{color:#15803d;}.res.bad{color:#b91c1b;}.res.mut{color:var(--muted);}
    </style>
</head>
<body>

<div class="top-bar">
    <a class="back-link" href="dashboard.php">← <span data-lo="ກັບຄືນ" data-en="Back">Back</span></a>
    <div class="lang-bar">
        <button class="lang-btn" id="btn-lo" onclick="setLang('lo')">🇱🇦 ລາວ</button>
        <button class="lang-btn" id="btn-en" onclick="setLang('en')">🇬🇧 EN</button>
    </div>
</div>

<div class="page">
    <h1 data-lo="ທົດສອບການແຈ້ງເຕືອນ" data-en="Reminder Test">Reminder Test</h1>
    <div class="sub" data-lo="ສົ່ງການແຈ້ງເຕືອນທົດສອບຫາພະນັກງານ ເພື່ອກວດວ່າໄດ້ຮັບ ຫຼື ບໍ່." data-en="Send a test notification to each staff to check who receives it. 'No device' means they never tapped Enable alerts.">Send a test notification to each staff to check who actually receives it. "No device" means they never enabled alerts on their phone.</div>

    <div class="stats">
        <div class="sb"><div class="v"><?= $total ?></div><div class="l" data-lo="ພະນັກງານ" data-en="Staff">Staff</div></div>
        <div class="sb"><div class="v" style="color:#16a34a"><?= $withDevice ?></div><div class="l" data-lo="ເປີດແຈ້ງເຕືອນ" data-en="Alerts on">Alerts on</div></div>
        <div class="sb"><div class="v" style="color:#dc2626"><?= $total-$withDevice ?></div><div class="l" data-lo="ຍັງບໍ່ເປີດ" data-en="No device">No device</div></div>
        <div class="sb" style="display:flex;align-items:center;"><button class="btn all" onclick="sendAll()">📤 <span data-lo="ສົ່ງໃຫ້ທຸກຄົນ" data-en="Test all">Test all</span></button></div>
    </div>

    <div class="card">
        <div class="tbl-wrap">
        <table>
            <thead><tr>
                <th data-lo="ພະນັກງານ" data-en="Staff">Staff</th>
                <th data-lo="ອຸປະກອນ" data-en="Devices">Devices</th>
                <th data-lo="ຜົນ" data-en="Result">Result</th>
                <th></th>
            </tr></thead>
            <tbody>
            <?php foreach ($staff as $s): $uid=(int)$s['id']; $dev=(int)($subCount[$uid]??0); ?>
                <tr>
                    <td><div class="nm"><?= htmlspecialchars($s['name']) ?></div>
                        <div class="sc"><?= htmlspecialchars($s['staff_code'] ?: '') ?><?php if($s['department']): ?> · <?= htmlspecialchars($s['department']) ?><?php endif; ?></div></td>
                    <td><?php if($dev>0): ?><span class="tag on"><?= $dev ?> 📱</span><?php else: ?><span class="tag off" data-lo="ບໍ່ມີ" data-en="None">None</span><?php endif; ?></td>
                    <td><span class="res mut" id="res-<?= $uid ?>">—</span></td>
                    <td style="text-align:right;">
                        <button class="btn" id="btn-<?= $uid ?>" onclick="sendOne(<?= $uid ?>)" <?= $dev>0?'':'disabled' ?>>
                            📤 <span data-lo="ສົ່ງທົດສອບ" data-en="Send test">Send test</span></button>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        </div>
    </div>
    <p style="font-size:12px;color:var(--muted);margin-top:12px;" data-lo="ລະຫັດ 201 = ສົ່ງສຳເລັດ. ຖ້າ 'ບໍ່ມີ' ໃຫ້ພະນັກງານກົດ 🔔 ເປີດການແຈ້ງເຕືອນ (iPhone ຕ້ອງ Add to Home Screen ກ່ອນ)."
       data-en="Code 201 = delivered. If 'None', ask the staff to tap 🔔 Enable alerts on their phone (iPhone must Add to Home Screen first).">Code 201 = delivered. If "None", the staff must tap 🔔 Enable alerts on their phone (iPhone: Add to Home Screen first).</p>
</div>

<script>
async function sendOne(uid){
    var btn=document.getElementById('btn-'+uid), res=document.getElementById('res-'+uid);
    btn.disabled=true; res.className='res mut'; res.textContent='…';
    try{
        var body=new URLSearchParams(); body.set('action','send'); body.set('uid',uid);
        var r=await fetch('reminder_test.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body});
        var d=await r.json();
        if(d.ok){ res.className='res ok'; res.textContent='✅ '+(window._lang==='en'?'sent':'ສົ່ງແລ້ວ')+' ('+d.sent+'/'+d.devices+' · '+d.codes.join(',')+')'; }
        else { res.className='res bad'; res.textContent='❌ '+(d.error||('codes '+((d.codes||[]).join(',')))); }
    }catch(e){ res.className='res bad'; res.textContent='❌ network'; }
    btn.disabled=false;
}
async function sendAll(){
    var ids=[<?php echo implode(',', array_map(fn($s)=>(int)$s['id'], array_filter($staff, fn($s)=>!empty($subCount[(int)$s['id']])))); ?>];
    for(const id of ids){ await sendOne(id); }
}
</script>

<?php require __DIR__ . '/../config/auto_update.php'; ?>
</body>
</html>