<?php
session_start();
require_once '../config/database.php';

if (!isset($_SESSION["user_id"]) || !in_array($_SESSION["role"], ["customer","company_admin"])) {
    header("Location: ../auth/login.php");
    exit;
}

$userId = (int)$_SESSION["user_id"];

$stmt = $pdo->prepare("SELECT * FROM customers WHERE user_id = ? LIMIT 1");
$stmt->execute([$userId]);
$customer = $stmt->fetch(PDO::FETCH_ASSOC);
$unreadPayments = 0;

if ($customer) {
    $stmt = $pdo->prepare("
        SELECT COUNT(*) FROM transactions
        WHERE to_type = 'customer' AND to_id = ? AND customer_read_at IS NULL
    ");
    $stmt->execute([$customer["id"]]);
    $unreadPayments = $stmt->fetchColumn();
}

/* ── Auto-detect company membership ── */
$companyInfo  = null;
$hrStats      = null;

try {
    $cs = $pdo->prepare("
        SELECT cs.company_id, cs.staff_role, cs.position, cs.department,
               c.name AS company_name
        FROM company_staff cs
        JOIN companies c ON c.id = cs.company_id
        WHERE cs.user_id = ?
        LIMIT 1
    ");
    $cs->execute([$userId]);
    $companyInfo = $cs->fetch(PDO::FETCH_ASSOC);
} catch (Throwable $e) { $companyInfo = null; }

if ($companyInfo) {
    $cid = (int)$companyInfo["company_id"];
    $m   = (int)date('n');
    $y   = (int)date('Y');

    try {
        $sal = $pdo->prepare("SELECT net_pay, paid_at FROM hr_salary WHERE staff_id=? AND company_id=? AND month=? AND year=? LIMIT 1");
        $sal->execute([$userId, $cid, $m, $y]);
        $salRow = $sal->fetch(PDO::FETCH_ASSOC);

        $pendLeave = $pdo->prepare("SELECT COUNT(*) FROM hr_leave WHERE staff_id=? AND status='pending'");
        $pendLeave->execute([$userId]);

        $attDays = $pdo->prepare("SELECT COUNT(*) FROM hr_attendance WHERE staff_id=? AND company_id=? AND MONTH(work_date)=? AND YEAR(work_date)=? AND status='present'");
        $attDays->execute([$userId, $cid, $m, $y]);

        $hrStats = [
            "net_pay"      => $salRow ? (float)$salRow["net_pay"] : null,
            "paid_at"      => $salRow ? $salRow["paid_at"] : null,
            "pending_leave"=> (int)$pendLeave->fetchColumn(),
            "att_days"     => (int)$attDays->fetchColumn(),
        ];
    } catch (Throwable $e) { $hrStats = null; }
}
?>
<!DOCTYPE html>
<html>
<head>
    <script>
    /* If a genuine laptop/desktop lands on the mobile view, switch to the laptop layout.
       Respects an explicit "Mobile View" choice (?m=1 or saved preference). */
    (function(){
        try{
            if (location.search.indexOf('m=1') !== -1) { sessionStorage.setItem('viewPref','mobile'); return; }
            if (sessionStorage.getItem('viewPref') === 'mobile') return;
            var wide  = window.matchMedia('(min-width:1024px)').matches;
            var mouse = window.matchMedia('(hover:hover) and (pointer:fine)').matches;
            if (wide && mouse) { location.replace('desktop.php'); }
        }catch(e){}
    })();
    </script>
    <title>Customer Wallet</title>
    <link rel="manifest" href="/seven-credit-system/manifest.json">
    <link rel="apple-touch-icon" href="/seven-credit-system/assets/icon-192.png">
    <meta name="theme-color" content="#b91c1c">
    <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="Seven Digital">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
    <script src="../assets/push.js" defer></script>
    <style>
        * { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
        html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; font-family: Arial, sans-serif; background: #fff; overscroll-behavior: none; }

        .app { width: 100%; max-width: 480px; height: 100vh; margin: 0 auto; background: #fff; position: relative; overflow: hidden; }

        .top {
            position: fixed; top: 0; left: 50%; transform: translateX(-50%);
            width: 100%; max-width: 480px;
            background: #b91c1c; color: white;
            padding: calc(12px + env(safe-area-inset-top)) 22px 20px;
            border-bottom-left-radius: 24px; border-bottom-right-radius: 24px;
            z-index: 100;
        }
        .top-header { display: flex; justify-content: space-between; align-items: center; gap: 12px; margin-bottom: 14px; }
        .top h2 { margin: 0; font-size: 24px; font-weight: 800; line-height: 1.2; flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .logout-circle { color: white; text-decoration: none; font-size: 32px; line-height: 1; }

        .account-card { background: #fff; color: #111827; border-radius: 20px; padding: 16px 20px; box-shadow: 0 8px 20px rgba(0,0,0,0.16); }
        .account-number, .balance-label { color: #64748b; font-weight: 700; font-size: 13px; }
        .account-row { display: flex; justify-content: space-between; align-items: flex-start; }
        .account-value { margin-top: 4px; font-size: 17px; color: #111827; font-weight: 700; }
        .balance-label { margin-top: 14px; font-weight: 500; }
        .balance { font-size: 34px; line-height: 1.1; font-weight: 800; color: #111827; margin-top: 4px; }
        .customer-code { color: #2563eb; font-size: 16px; font-weight: 800; }

        /* ── My QR on the card ── */
        .acc-left { flex: 1; min-width: 0; }
        .acc-name-label { color: #64748b; font-weight: 700; font-size: 13px; margin-top: 14px; }
        .acc-name-value { margin-top: 4px; font-size: 17px; color: #111827; font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .acc-qr { display: flex; flex-direction: column; align-items: center; gap: 10px; flex-shrink: 0; margin-left: 12px; }
        .acc-qr .qr-box { width: 130px; height: 130px; background: #fff; border: 1px solid #eef0f2; border-radius: 14px; padding: 7px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
        .acc-qr .qr-box canvas, .acc-qr .qr-box img { width: 100% !important; height: 100% !important; display: block; }
        .acc-qr-share { display: inline-flex; align-items: center; justify-content: center; gap: 5px; background: #b91c1c; color: #fff; border: none; border-radius: 10px; padding: 8px 22px; font-size: 13px; font-weight: 800; cursor: pointer; font-family: inherit; }
        .acc-qr-share:active { opacity: .85; }

        .main-scroll {
            position: fixed;
            top: 380px;
            bottom: calc(78px + env(safe-area-inset-bottom));
            left: 50%; transform: translateX(-50%);
            width: 100%; max-width: 480px;
            overflow-y: auto; overflow-x: hidden;
            -webkit-overflow-scrolling: touch;
            background: #fff; z-index: 10;
        }




        /* ── Wallet menu ── */
        .menu { display: grid; grid-template-columns: repeat(3,1fr); gap: 26px 20px; padding: 16px 22px 10px; text-align: center; }
        .menu a { text-decoration: none; color: #64748b; font-size: 16px; }
        .icon { width: 74px; height: 74px; margin: 0 auto 10px; background: #f2f2f2; border-radius: 50%; display: flex; align-items: center; justify-content: center; box-shadow: 0 2px 8px rgba(0,0,0,.18), inset 0 1px 0 rgba(255,255,255,.9); }
        .icon svg { width: 40px; height: 40px; stroke: #c5161d; fill: none; stroke-width: 3; stroke-linecap: round; stroke-linejoin: round; }
        .icon i { font-size: 40px; color: #c5161d; }

        /* ── HR section ── */
        .hr-section { padding: 6px 22px 10px; }

        .hr-divider {
            display: flex; align-items: center; gap: 10px;
            margin-bottom: 14px;
        }
        .hr-divider-line { flex: 1; height: 1px; background: #e2e8f0; }
        .hr-divider-label {
            font-size: 11px; font-weight: 800; color: #64748b;
            text-transform: uppercase; letter-spacing: .6px;
            white-space: nowrap;
        }

        /* Company badge */
        .company-badge {
            background: linear-gradient(135deg,#042f2e,#0f766e);
            border-radius: 16px; padding: 14px 18px;
            color: #fff; margin-bottom: 14px;
            display: flex; align-items: center; justify-content: space-between;
        }
        .company-badge .co-name { font-size: 15px; font-weight: 800; }
        .company-badge .co-role { font-size: 11px; opacity: .75; margin-top: 3px; }
        .company-badge .salary-badge {
            text-align: right;
        }
        .company-badge .salary-val { font-size: 18px; font-weight: 800; }
        .company-badge .salary-lbl { font-size: 10px; opacity: .75; margin-top: 2px; }
        .salary-paid   { color: #4ade80; }
        .salary-pending { color: #fcd34d; }

        /* HR mini stats */
        .hr-stats { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 14px; }
        .hr-stat-card {
            background: #f8fafc; border-radius: 12px; padding: 12px 14px;
            border: 1px solid #e2e8f0;
        }
        .hr-stat-val { font-size: 22px; font-weight: 800; color: #0f172a; }
        .hr-stat-lbl { font-size: 11px; color: #64748b; font-weight: 600; margin-top: 2px; }

        /* HR menu grid */
        .hr-menu { display: grid; grid-template-columns: repeat(3,1fr); gap: 12px; margin-bottom: 120px; }
        .hr-item { text-decoration: none; text-align: center; }
        .hr-icon {
            width: 64px; height: 64px; margin: 0 auto 8px;
            border-radius: 18px; display: flex; align-items: center; justify-content: center;
            font-size: 28px;
            box-shadow: 0 2px 8px rgba(0,0,0,.12);
        }
        .hr-icon.teal   { background: linear-gradient(135deg,#042f2e,#0f766e); }
        .hr-icon.blue   { background: linear-gradient(135deg,#1e3a5f,#2563eb); }
        .hr-icon.amber  { background: linear-gradient(135deg,#92400e,#d97706); }
        .hr-icon.purple { background: linear-gradient(135deg,#4c1d95,#7c3aed); }
        .hr-icon.pink   { background: linear-gradient(135deg,#831843,#db2777); }
        .hr-icon.green  { background: linear-gradient(135deg,#14532d,#16a34a); }
        .hr-icon.navy   { background: linear-gradient(135deg,#0f2444,#2563eb); }
        .admin-portal-btn {
            display: flex; align-items: center; justify-content: space-between;
            background: linear-gradient(135deg,#0f2444,#1d4ed8);
            border-radius: 16px; padding: 16px 20px;
            text-decoration: none; color: #fff;
            margin-bottom: 14px;
            box-shadow: 0 4px 14px rgba(15,23,42,.25);
        }
        .admin-portal-btn .ap-left { display:flex; align-items:center; gap:12px; }
        .admin-portal-btn .ap-icon { width:44px;height:44px;border-radius:12px;background:rgba(255,255,255,.15);display:flex;align-items:center;justify-content:center;font-size:22px; }
        .admin-portal-btn .ap-title { font-size:15px;font-weight:800; }
        .admin-portal-btn .ap-sub { font-size:11px;opacity:.75;margin-top:2px; }
        .admin-portal-btn .ap-arrow { font-size:20px;opacity:.75; }
        .hr-item span { font-size: 13px; color: #64748b; font-weight: 600; }

        /* pending badge on leave */
        .hr-item-wrap { position: relative; display: inline-block; }
        .hr-badge { position: absolute; top: -4px; right: -4px; background: #dc2626; color: #fff; font-size: 10px; font-weight: 800; padding: 2px 6px; border-radius: 999px; }

        .onepay { position: fixed; right: max(22px,calc((100vw - 480px)/2 + 22px)); bottom: calc(106px + env(safe-area-inset-bottom)); background: #b91c1c; color: white; width: 86px; height: 86px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 800; text-decoration: none; box-shadow: 0 8px 22px rgba(0,0,0,.28); border: 6px solid white; font-size: 16px; text-align: center; z-index: 60; }

        .bottom-nav { position: fixed; bottom: 0; left: 50%; transform: translateX(-50%); width: 100%; max-width: 480px; background: #b91c1c; display: flex; justify-content: space-around; padding: 16px 0 calc(16px + env(safe-area-inset-bottom)); z-index: 90; }
        .bottom-nav a { color: white; text-decoration: none; font-size: 15px; text-align: center; }

        .warning { padding: 24px; color: #991b1b; }

        .notification-box { background: #dcfce7; border: 1px solid #86efac; color: #166534; border-radius: 16px; padding: 14px 16px; margin: 10px 22px 0; text-decoration: none; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 4px 14px rgba(0,0,0,.08); }
        .notification-box p { margin: 5px 0 0; color: #15803d; font-size: 13px; }
        .notification-box span { background: #16a34a; color: white; padding: 8px 12px; border-radius: 10px; font-weight: bold; }

        @media (max-width: 390px) {
            .top h2 { font-size: 24px; }
            .balance { font-size: 30px; }
            .main-scroll { top: 360px; }
            .icon { width: 68px; height: 68px; }
            .acc-qr { width: 140px; gap: 7px; margin-left: 8px; }
            .acc-qr .qr-box { width: 120px; height: 120px; }
        }
    </style>
</head>
<body>
<div class="app">

    <!-- ── Top bar ── -->
    <div class="top">
        <div class="top-header">
            <h2><?= htmlspecialchars($customer["full_name"] ?: ($_SESSION["name"] ?? "Seven Digital")) ?></h2>
            <div style="display:flex;align-items:center;gap:10px">
            <?php if ($_SESSION["role"] === "company_admin"): ?>
            <a href="../company/dashboard.php" style="color:#fff;font-size:13px;font-weight:700;text-decoration:none;background:rgba(255,255,255,.2);padding:6px 12px;border-radius:10px;">🖥️ Desktop</a>
            <?php endif; ?>
            <button onclick="sdEnablePush()" aria-label="Enable alerts" style="background:rgba(255,255,255,.2);border:none;color:#fff;font-size:18px;width:38px;height:38px;border-radius:50%;cursor:pointer;line-height:1;">🔔</button>
            <a class="logout-circle" href="../auth/logout.php" aria-label="Logout">⏻</a>
        </div>
        </div>
        <?php if ($customer): ?>
            <div class="account-card">
                <div class="account-row">
                    <div class="acc-left">
                        <?php if (!empty($customer["pay_id"])): ?>
                        <div class="account-number" data-lo="ໄອດີຮັບເງິນ" data-en="Pay ID">Pay ID</div>
                        <div class="account-value" style="font-size:22px;letter-spacing:1px;color:#b91c1c;"><?= htmlspecialchars($customer["pay_id"]) ?></div>
                        <?php endif; ?>
                        <div class="account-number" data-lo="ເລກບັນຊີ" data-en="Account Number">Account Number</div>
                        <div class="account-value"><?= htmlspecialchars($customer["customer_code"]) ?></div>
                        <div class="balance-label" data-lo="ຍອດເງິນຄົງເຫຼືອ" data-en="Current Balance">Current Balance</div>
                        <div class="balance" id="customerBalance">₭ <?= number_format($customer["balance"], 2) ?></div>
                    </div>
                    <div class="acc-qr">
                        <div class="qr-box" id="cardQr"></div>
                        <button type="button" class="acc-qr-share" onclick="shareMyQR()">🔗 <span data-lo="ແບ່ງປັນ" data-en="Share">Share</span></button>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- ── Scrollable content ── -->
    <div class="main-scroll">

        <!-- Payment notification -->
        <a href="wallet_history.php" id="paymentNotification" class="notification-box"
            style="<?= $unreadPayments > 0 ? '' : 'display:none;' ?>">
            <div>
                <strong data-lo="ໄດ້ຮັບເງິນໃໝ່" data-en="New Money Received">New Money Received</strong>
                <p id="paymentNotificationText" data-count="<?= $unreadPayments ?>">You have <?= $unreadPayments ?> unread payment notification(s).</p>
            </div>
            <span data-lo="ເບິ່ງ" data-en="View">View</span>
        </a>



        <?php if ($customer): ?>

            <!-- ── Wallet menu ── -->
            <div class="menu">
                <a href="wallet_history.php">
                    <div class="icon">
                        <svg viewBox="0 0 100 100"><path d="M30 12h34l16 16v60H30z"/><path d="M64 12v18h16"/><path d="M42 46h24"/><path d="M42 58h24"/><path d="M42 70h18"/></svg>
                    </div>
                    <span data-lo="ລາຍການ" data-en="Statement">Statement</span>
                </a>
                <a href="qr_code.php">
                    <div class="icon">
                        <svg viewBox="0 0 100 100"><rect x="10" y="10" width="26" height="26"/><rect x="64" y="10" width="26" height="26"/><rect x="10" y="64" width="26" height="26"/><rect x="18" y="18" width="10" height="10"/><rect x="72" y="18" width="10" height="10"/><rect x="18" y="72" width="10" height="10"/><rect x="60" y="60" width="10" height="10"/><rect x="76" y="60" width="10" height="10"/><rect x="60" y="76" width="10" height="10"/><rect x="76" y="76" width="10" height="10"/></svg>
                    </div>
                    <span data-lo="QR ຂອງຂ້ອຍ" data-en="My QR">My QR</span>
                </a>
                <a href="transfer.php">
                    <div class="icon"><i class="fa-solid fa-money-bill-transfer"></i></div>
                    <span data-lo="ໂອນເງິນ" data-en="Transfer">Transfer</span>
                </a>

            </div>

            <?php if ($companyInfo): ?>
            <!-- ── Company entry: tap to open company HR page (no wallet there) ── -->
            <a href="company_home.php" style="display:flex;align-items:center;justify-content:space-between;gap:12px;
                background:linear-gradient(135deg,#042f2e,#0f766e);color:#fff;border-radius:16px;padding:18px 20px;
                text-decoration:none;margin-top:6px;box-shadow:0 4px 16px rgba(4,47,46,.25);">
                <div style="display:flex;align-items:center;gap:12px;">
                    <div style="width:44px;height:44px;border-radius:12px;background:rgba(255,255,255,.15);
                        display:flex;align-items:center;justify-content:center;font-size:22px;">🏢</div>
                    <div>
                        <div style="font-size:16px;font-weight:800;line-height:1.2;"><?= htmlspecialchars($companyInfo["company_name"]) ?></div>
                        <div style="font-size:12px;color:rgba(255,255,255,.75);margin-top:2px;"
                             data-lo="ກົດເພື່ອເບິ່ງ ລົງເວລາ, ເງິນເດືອນ, ການລາພັກ ແລະ ອື່ນໆ"
                             data-en="Tap for check-in, salary, leave & more">Tap for check-in, salary, leave &amp; more</div>
                    </div>
                </div>
                <div style="font-size:26px;opacity:.7;">›</div>
            </a>
            <?php endif; ?>

        <?php else: ?>
            <div class="warning">No customer wallet connected to this account.</div>
        <?php endif; ?>

    </div>

    <?php if ($customer): ?>
        <a class="onepay" href="scan_qr.php" data-lo="ຈ່າຍ" data-en="Pay">Pay</a>
    <?php endif; ?>

    <div class="bottom-nav">
        <a href="dashboard.php" data-lo="ກະເປົາເງິນ" data-en="Wallet">Wallet</a>
        <a href="wallet_history.php" data-lo="ລາຍການ" data-en="Statement">Statement</a>
        <a href="qr_code.php">QR</a>
        <a href="settings.php">⚙️ <span data-lo="ຕັ້ງຄ່າ" data-en="Settings">Settings</span></a>
    </div>

</div>

<script>
if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/seven-credit-system/service-worker.js', { scope: '/seven-credit-system/' });
}

/* ── Apply the language chosen on the login / settings screen ── */
const LANG_KEY = 'seven_lang';
function getLang(){ return localStorage.getItem(LANG_KEY) || 'lo'; }
function applyLang(lang){
    document.querySelectorAll('[data-lo],[data-en]').forEach(el => {
        const t = el.getAttribute('data-' + lang);
        if (t !== null) el.textContent = t;
    });
}
function notifText(n){
    return getLang() === 'lo'
        ? ('ທ່ານມີ ' + n + ' ການແຈ້ງເຕືອນທີ່ຍັງບໍ່ໄດ້ອ່ານ')
        : ('You have ' + n + ' unread payment notification(s).');
}
/* place the scrollable menu right below the (variable-height) top card so it is
   never covered — adapts to Pay ID, the HR section, or a notification banner */
function fitMainScroll(){
    const top = document.querySelector('.top');
    const scroll = document.querySelector('.main-scroll');
    if (top && scroll) scroll.style.top = top.offsetHeight + 'px';
}
document.addEventListener('DOMContentLoaded', () => {
    applyLang(getLang());
    const pn = document.getElementById('paymentNotificationText');
    if (pn && pn.dataset.count !== undefined) pn.textContent = notifText(pn.dataset.count);
    fitMainScroll();
});
window.addEventListener('load', fitMainScroll);
window.addEventListener('resize', fitMainScroll);
setTimeout(fitMainScroll, 300);

/* ── My QR on the card (others scan this to pay / transfer) ── */
const MY_ACCOUNT = <?= json_encode($customer["customer_code"] ?? "") ?>;
const MY_NAME    = <?= json_encode($customer["full_name"] ?? "") ?>;

(function () {
    const box = document.getElementById('cardQr');
    if (box && MY_ACCOUNT && window.QRCode) {
        new QRCode(box, {
            text: MY_ACCOUNT,
            width: 130, height: 130,
            colorDark: '#111827', colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.H
        });
    }
})();

/* Share QR — opens the share sheet (WhatsApp, Messages, …); shares the QR image when possible */
async function shareMyQR() {
    const text = 'Pay me on Seven Digital Wallet\nAccount: ' + MY_ACCOUNT + (MY_NAME ? '\nName: ' + MY_NAME : '');
    try {
        const canvas = document.querySelector('#cardQr canvas');
        if (canvas && navigator.canShare) {
            const blob = await new Promise(r => canvas.toBlob(r, 'image/png'));
            const file = new File([blob], 'seven-qr.png', { type: 'image/png' });
            if (navigator.canShare({ files: [file] })) {
                await navigator.share({ files: [file], text: text });
                return;
            }
        }
        if (navigator.share) { await navigator.share({ text: text }); return; }
    } catch (e) {
        if (e && e.name === 'AbortError') return;   // user cancelled
    }
    // fallback: open WhatsApp directly
    window.open('https://wa.me/?text=' + encodeURIComponent(text), '_blank');
}

function checkNewPayments() {
    fetch("check_new_payments.php")
        .then(r => r.json())
        .then(data => {
            if (!data.success) return;
            const box  = document.getElementById("paymentNotification");
            const text = document.getElementById("paymentNotificationText");
            const bal  = document.getElementById("customerBalance");
            if (bal && data.balance !== undefined) bal.textContent = "₭ " + data.balance;
            if (data.unread > 0) {
                box.style.display = "flex";
                text.textContent = notifText(data.unread);
            } else {
                box.style.display = "none";
            }
        })
        .catch(() => {});
}
setInterval(checkNewPayments, 5000);
</script>
<?php require __DIR__ . '/../config/auto_update.php'; ?>
</body>
</html>