<?php
/* ============================================================================
 *  customer/company_home.php
 *  Company HR landing page for a logged-in staff member.
 *  Shows the company name + HR functions (Check In, Salary, Attendance, Leave,
 *  Allowances, Payslips). No wallet info (no Pay ID / balance / QR).
 *  Opened by tapping the company name on the wallet dashboard.
 * ==========================================================================*/
session_start();
if (!isset($_SESSION["user_id"]) || empty($_SESSION["company_id"])) {
    header("Location: dashboard.php"); exit;
}
require_once '../config/database.php';
require_once '../config/modules.php';
require_once '../config/module_access.php';
date_default_timezone_set('Asia/Vientiane');

$userId    = (int)$_SESSION["user_id"];
$companyId = (int)$_SESSION["company_id"];
$roleKey   = $_SESSION["role"] ?? '';
$enabledModules = company_enabled_modules($pdo, $companyId);
$mod = fn($k) => module_on($enabledModules, $k);
// module is visible to this staff only if enabled AND they have access (admin always)
$canSee    = fn($k) => module_on($enabledModules, $k) && mod_can_view($pdo, $companyId, $userId, $roleKey, $k);
$canManage = fn($k) => module_on($enabledModules, $k) && mod_can_edit($pdo, $companyId, $userId, $roleKey, $k);
$canAdmin  = fn($k) => module_on($enabledModules, $k) && mod_can_admin($pdo, $companyId, $userId, $roleKey, $k);

/* company membership + HR snapshot */
$info = null; $hr = ["net_pay"=>null,"paid_at"=>null,"pending_leave"=>0,"att_days"=>0];
try {
    $cs = $pdo->prepare("SELECT cs.staff_role, cs.position, cs.department, cs.photo, cs.staff_code,
                                u.name AS full_name, c.name AS company_name
                         FROM company_staff cs
                         JOIN users u ON u.id = cs.user_id
                         JOIN companies c ON c.id=cs.company_id
                         WHERE cs.user_id=? AND cs.company_id=? LIMIT 1");
    $cs->execute([$userId, $companyId]);
    $info = $cs->fetch(PDO::FETCH_ASSOC);
} catch (Throwable $e) {}
$companyName = $info["company_name"] ?? ($_SESSION["company_name"] ?? "My Company");

$m=(int)date('n'); $y=(int)date('Y');
try {
    $s=$pdo->prepare("SELECT net_pay,paid_at FROM hr_salary WHERE staff_id=? AND company_id=? AND month=? AND year=? LIMIT 1");
    $s->execute([$userId,$companyId,$m,$y]); $sr=$s->fetch(PDO::FETCH_ASSOC);
    if($sr){$hr["net_pay"]=(float)$sr["net_pay"];$hr["paid_at"]=$sr["paid_at"];}
    $pl=$pdo->prepare("SELECT COUNT(*) FROM hr_leave WHERE staff_id=? AND status='pending'"); $pl->execute([$userId]);
    $hr["pending_leave"]=(int)$pl->fetchColumn();
    $ad=$pdo->prepare("SELECT COUNT(*) FROM hr_attendance WHERE staff_id=? AND company_id=? AND MONTH(work_date)=? AND YEAR(work_date)=? AND status IN('present','late','half_day')");
    $ad->execute([$userId,$companyId,$m,$y]); $hr["att_days"]=(int)$ad->fetchColumn();
} catch (Throwable $e) {}

$isAdmin = ($_SESSION["role"] ?? '') === 'company_admin';
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <?php $pwaTheme='#0f766e'; include __DIR__.'/../config/pwa_head.php'; ?>
    <title><?= htmlspecialchars($companyName) ?></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>
    <script src="../assets/push.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;
            --blue:#2563eb;--blue-lt:#dbeafe;--radius:16px;--shadow:0 2px 14px rgba(15,23,42,.09);}
        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)) 18px 12px;display:flex;
            justify-content:space-between;align-items:center;gap:12px;position:sticky;top:0;z-index:100;box-shadow:0 1px 6px rgba(15,23,42,.06);}
        .back-link{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{padding:18px 16px;max-width:560px;margin:auto;}
        .hero{background:linear-gradient(135deg,#042f2e,#0f766e);border-radius:20px;padding:24px;color:#fff;margin-bottom:18px;position:relative;overflow:hidden;}
        .hero::before{content:"";position:absolute;width:200px;height:200px;border-radius:50%;background:rgba(255,255,255,.07);right:-50px;top:-60px;}
        .hero-staff{position:relative;z-index:1;display:flex;flex-direction:column;align-items:flex-start;gap:8px;margin-top:14px;}
        .hs-row{display:flex;align-items:center;gap:10px;}
        .hs-photo{width:96px;height:96px;border-radius:18px;object-fit:cover;border:2px solid rgba(255,255,255,.5);background:rgba(255,255,255,.15);}
        .hs-initial{display:flex;align-items:center;justify-content:center;font-size:38px;font-weight:800;color:#fff;}
        .hs-id{font-size:12px;font-weight:800;color:rgba(255,255,255,.9);letter-spacing:.4px;background:rgba(255,255,255,.15);padding:3px 11px;border-radius:999px;}
        .hs-name{font-size:17px;font-weight:800;color:#fff;line-height:1.2;}
        .hero .co{font-size:22px;font-weight:800;line-height:1.2;position:relative;z-index:1;}
        .hero .sal{position:relative;z-index:1;margin-top:16px;}
        .hero .salv{font-size:24px;font-weight:800;}
        .hero .sall{font-size:12px;color:rgba(255,255,255,.7);}
        .stats{display:flex;gap:10px;margin-bottom:18px;}
        .stat{flex:1;background:var(--surface);border:1px solid var(--border);border-radius:14px;padding:14px;box-shadow:var(--shadow);text-align:center;}
        .stat .v{font-size:22px;font-weight:800;}.stat .l{font-size:11px;color:var(--muted);font-weight:600;margin-top:2px;}
        .checkin-btn{display:flex;align-items:center;justify-content:center;gap:10px;background:linear-gradient(135deg,#16a34a,#15803d);
            color:#fff;padding:18px;border-radius:16px;text-decoration:none;font-weight:800;font-size:18px;margin-bottom:18px;box-shadow:0 4px 14px rgba(22,163,74,.32);}
        .menu{display:grid;grid-template-columns:1fr 1fr;gap:12px;}
        .item{background:var(--surface);border:1px solid var(--border);border-radius:16px;padding:18px;text-decoration:none;color:var(--text);
            box-shadow:var(--shadow);display:flex;flex-direction:column;gap:8px;position:relative;}
        .item .ic{width:44px;height:44px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:22px;}
        .ic.teal{background:#ccfbf1;}.ic.blue{background:var(--blue-lt);}.ic.amber{background:var(--amber-lt);}
        .ic.purple{background:#ede9fe;}.ic.pink{background:#fce7f3;}.ic.green{background:var(--green-lt);}.ic.navy{background:#e0e7ff;}
        .item h3{font-size:14px;font-weight:700;}.item p{font-size:11px;color:var(--muted);line-height:1.4;}
        .badge{position:absolute;top:10px;right:10px;background:var(--red);color:#fff;font-size:14px;font-weight:900;min-width:24px;height:24px;line-height:24px;text-align:center;padding:0 7px;border-radius:999px;box-shadow:0 2px 6px rgba(220,38,38,.45);}
        .item.notif{background:#fee2e2;border-color:#fca5a5;}
        .admin-btn{display:flex;align-items:center;gap:12px;background:linear-gradient(135deg,#042f2e,#0f766e);color:#fff;
            padding:16px 18px;border-radius:14px;text-decoration:none;margin-top:14px;}
        .admin-btn .t{font-size:14px;font-weight:800;}.admin-btn .s{font-size:11px;color:rgba(255,255,255,.7);}
    </style>
</head>
<body>

<div class="top-bar">
    <a class="back-link" href="dashboard.php">← <span data-lo="ກະເປົາເງິນ" data-en="Wallet">Wallet</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">

    <div class="hero">
        <div class="co"><?= htmlspecialchars($companyName) ?></div>

        <div class="hero-staff">
            <div class="hs-row">
                <?php if (!empty($info["photo"])): ?>
                    <img class="hs-photo" src="../<?= htmlspecialchars($info["photo"]) ?>" alt="">
                <?php else: ?>
                    <div class="hs-photo hs-initial"><?= strtoupper(mb_substr($_SESSION["name"] ?? "S", 0, 1)) ?></div>
                <?php endif; ?>
                <?php if (!empty($info["staff_code"])): ?>
                    <div class="hs-id"><?= htmlspecialchars($info["staff_code"]) ?></div>
                <?php endif; ?>
            </div>
            <div class="hs-name"><?= htmlspecialchars($info["full_name"] ?? ($_SESSION["name"] ?? "")) ?></div>
        </div>

        <div class="sal">
            <?php if ($hr["net_pay"] !== null): ?>
                <div class="salv">₭ <?= number_format($hr["net_pay"],0) ?></div>
                <div class="sall"><?= $hr["paid_at"] ? "✅ Paid" : "⏳ Pending" ?> · <span data-lo="ເງິນເດືອນເດືອນນີ້" data-en="This month salary">This month salary</span></div>
            <?php else: ?>
                <div class="sall" data-lo="ຍັງບໍ່ມີຂໍ້ມູນເງິນເດືອນ" data-en="No salary record yet">No salary record yet</div>
            <?php endif; ?>
        </div>
    </div>

    <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:16px;">
        <button onclick="sdEnablePush()" style="flex:1;min-width:150px;background:#0f766e;color:#fff;border:none;padding:12px 14px;border-radius:12px;font-weight:800;font-size:14px;cursor:pointer;font-family:inherit;">
            🔔 <span data-lo="ເປີດການແຈ້ງເຕືອນ" data-en="Enable alerts">Enable alerts</span>
        </button>
        <button onclick="sdTestPush()" style="background:#f1f5f9;color:#0f172a;border:1.5px solid #e2e8f0;padding:12px 16px;border-radius:12px;font-weight:700;font-size:14px;cursor:pointer;font-family:inherit;">
            <span data-lo="ທົດສອບ" data-en="Test">Test</span>
        </button>
    </div>

    <div class="stats">
        <div class="stat"><div class="v" style="color:#16a34a"><?= $hr["att_days"] ?></div><div class="l" data-lo="ມາວຽກເດືອນນີ້" data-en="Days present">Days present</div></div>
        <div class="stat"><div class="v" style="color:#d97706"><?= $hr["pending_leave"] ?></div><div class="l" data-lo="ລາພັກລໍຖ້າ" data-en="Leave pending">Leave pending</div></div>
    </div>

    <?php if ($mod('attendance')): ?>
    <a class="checkin-btn" href="../staff/checkin.php">
        🟢 <span data-lo="ລົງເວລາ ເຂົ້າ-ອອກວຽກ" data-en="Check In / Out">Check In / Out</span>
    </a>
    <?php endif; ?>

    <div class="menu">
        <?php if ($mod('staff')): ?>
        <a class="item" href="../staff/my_information.php">
            <div class="ic navy">ℹ️</div>
            <h3 data-lo="ຂໍ້ມູນຂອງຂ້ອຍ" data-en="My Information">My Information</h3>
            <p data-lo="ເບິ່ງຂໍ້ມູນສ່ວນຕົວຂອງຂ້ອຍ" data-en="View your profile details">View your profile details</p>
        </a>
        <?php endif; ?>
        <?php if ($mod('payroll')): ?>
        <a class="item" href="../staff/my_salary.php">
            <div class="ic teal">💵</div>
            <h3 data-lo="ເງິນເດືອນຂ້ອຍ" data-en="My Salary">My Salary</h3>
            <p data-lo="ເບິ່ງເງິນເດືອນ, OT" data-en="Salary and OT history">Salary and OT history</p>
        </a>
        <?php endif; ?>
        <?php if ($mod('attendance')): ?>
        <a class="item" href="../staff/my_attendance.php">
            <div class="ic blue">🕐</div>
            <h3 data-lo="ການມາວຽກ" data-en="My Attendance">My Attendance</h3>
            <p data-lo="ປະຫວັດການລົງເວລາ" data-en="Check-in history">Check-in history</p>
        </a>
        <?php endif; ?>
        <?php if ($mod('leave')): ?>
        <a class="item" href="../staff/leave.php">
            <?php if ($hr["pending_leave"]>0): ?><span class="badge"><?= $hr["pending_leave"] ?></span><?php endif; ?>
            <div class="ic amber">🏖️</div>
            <h3 data-lo="ການລາພັກ" data-en="My Leave">My Leave</h3>
            <p data-lo="ຂໍລາພັກ ແລະ ສະຖານະ" data-en="Request leave and status">Request leave and status</p>
        </a>
        <?php endif; ?>
        <?php if ($mod('payroll')): ?>
        <a class="item" href="../staff/coming_soon.php?f=allowances">
            <div class="ic purple">🎁</div>
            <h3 data-lo="ເບ້ຍຂ້ອຍ" data-en="My Allowances">My Allowances</h3>
            <p data-lo="ເບ້ຍຂົນສົ່ງ, ອາຫານ ແລະ ອື່ນໆ" data-en="Transport, meal and more">Transport, meal and more</p>
        </a>
        <a class="item" href="../staff/my_payslips.php">
            <div class="ic pink">🧾</div>
            <h3 data-lo="ໃບເງິນເດືອນ" data-en="My Payslips">My Payslips</h3>
            <p data-lo="ດາວໂຫລດໃບເງິນເດືອນ" data-en="Download payslips">Download payslips</p>
        </a>
        <a class="item" href="../staff/loan.php">
            <div class="ic amber">💸</div>
            <h3 data-lo="ກູ້ຢືມເງິນ" data-en="Borrow Money">Borrow Money</h3>
            <p data-lo="ຂໍກູ້ ແລະ ເບິ່ງຍອດຄ້າງ" data-en="Request a loan & see balance">Request a loan & see balance</p>
        </a>
        <?php endif; ?>
        <a class="item" href="../staff/change_password.php">
            <div class="ic green">🔑</div>
            <h3 data-lo="ປ່ຽນລະຫັດ" data-en="Password">Password</h3>
            <p data-lo="ປ່ຽນລະຫັດຜ່ານ" data-en="Change your password">Change your password</p>
        </a>
        <?php if ($canSee('customer')): ?>
        <a class="item" href="../company/sp_customers.php">
            <div class="ic blue">👤</div>
            <h3 data-lo="ຈັດການລູກຄ້າ" data-en="Customer Management">Customer Management</h3>
            <p data-lo="ລູກຄ້າ ແລະ ເຄື່ອງຈັກ" data-en="Customers & machines">Customers & machines</p>
        </a>
        <?php endif; ?>
        <?php if ($canSee('stock')): ?>
        <a class="item" href="../company/sp_stock.php">
            <div class="ic purple">📦</div>
            <h3 data-lo="ຈັດການສະຕັອກ" data-en="Stock Management">Stock Management</h3>
            <p data-lo="ສິນຄ້າຄົງຄັງ, ເຂົ້າ-ອອກ" data-en="Inventory & stock in/out">Inventory & stock in/out</p>
        </a>
        <?php endif; ?>
        <?php require_once __DIR__.'/../config/part_request_flow.php'; ?>
        <?php if ($canSee('part_request')): $__ready = function_exists('pr_ready_for_creator') ? pr_ready_for_creator($pdo, $companyId, $userId) : 0; ?>
        <a class="item<?= $__ready>0?' notif':'' ?>" href="../company/sp_part_requests.php?status=ready">
            <div class="ic amber">🧾</div>
            <h3 data-lo="ໃບຂໍ (ສ້າງໃໝ່)" data-en="Request Form">Request Form</h3>
            <p data-lo="ສ້າງໃບຂໍອາໄຫຼ່/ໝຶກ" data-en="Create parts / toner request">Create parts / toner request</p>
            <?php if ($__ready>0): ?><span class="badge" style="background:#16a34a;"><?= $__ready ?></span><?php endif; ?>
        </a>
        <?php endif; ?>
        <?php
        $__prole = pr_role($pdo, $companyId, $userId, $roleKey);
        if (pr_can_queue($__prole)):
            $__newReq = pr_badge_count($pdo, $companyId, $__prole);
        ?>
        <a class="item<?= $__newReq>0?' notif':'' ?>" href="../company/sp_part_request_queue.php">
            <div class="ic pink">📥</div>
            <h3 data-lo="ຄິວໃບຂໍ" data-en="Request Form Queue">Request Form Queue</h3>
            <p data-lo="ເບິ່ງ/ຈັດການໃບຂໍໃໝ່" data-en="View & handle new requests">View & handle new requests</p>
            <?php if ($__newReq>0): ?><span class="badge"><?= $__newReq ?></span><?php endif; ?>
        </a>
        <?php endif; ?>
        <?php if ($canAdmin('jobs')): ?>
        <a class="item" href="../company/sp_jobs_admin.php">
            <div class="ic teal">🛠️</div>
            <h3 data-lo="ຈັດການວຽກ" data-en="Manage Jobs">Manage Jobs</h3>
            <p data-lo="ສ້າງ, ມອບໝາຍ ແລະ ຈັດການວຽກ" data-en="Create, assign & manage jobs">Create, assign & manage jobs</p>
        </a>
        <?php elseif ($canManage('jobs')): ?>
        <a class="item" href="../company/sp_jobs_staff.php">
            <div class="ic green">✅</div>
            <h3 data-lo="ວຽກຂອງຂ້ອຍ" data-en="My Jobs">My Jobs</h3>
            <p data-lo="ເບິ່ງ ແລະ ປິດວຽກຂອງທ່ານ" data-en="View & close your jobs">View & close your jobs</p>
        </a>
        <?php endif; ?>
        <?php
        require_once __DIR__.'/../config/approvals.php';
        if (appr_is_reviewer($pdo, $companyId, $userId)):
            $__apprPending = appr_leave_pending_for($pdo, $companyId, $userId);
        ?>
        <a class="item<?= $__apprPending>0?' notif':'' ?>" href="../company/hr_leave.php">
            <div class="ic teal">🖊️</div>
            <h3 data-lo="ອະນຸມັດການລາພັກ" data-en="Approvals">Approvals</h3>
            <p data-lo="ອະນຸມັດຄຳຂໍລາພັກຂອງທີມ" data-en="Approve your team's leave requests">Approve your team's leave requests</p>
            <?php if ($__apprPending > 0): ?><span class="badge"><?= $__apprPending ?></span><?php endif; ?>
        </a>
        <?php endif; ?>
    </div>

    <?php if ($isAdmin): ?>
    <a class="admin-btn" href="../company/dashboard.php">
        <div class="ic navy" style="background:rgba(255,255,255,.15)">🏢</div>
        <div>
            <div class="t" data-lo="ປະຕູຜູ້ດູແລບໍລິສັດ" data-en="Company Admin Portal">Company Admin Portal</div>
            <div class="s" data-lo="ຈັດການພະນັກງານ, HR, ເງິນເດືອນ" data-en="Manage staff, HR, payroll">Manage staff, HR, payroll</div>
        </div>
    </a>
    <?php endif; ?>

</div>

<script>
/* Auto-refresh so the Request Queue badge stays live (pause while typing) */
setInterval(function(){
    var a=document.activeElement;
    if(a && /^(INPUT|TEXTAREA|SELECT)$/.test(a.tagName)) return;
    if(!document.hidden) location.reload();
}, 20000);
</script>
<?php require __DIR__ . '/../config/auto_update.php'; ?>
</body>
</html>