<?php
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/pay_id.php';

$companyId = (int)$_SESSION["company_id"];
$editId    = isset($_GET["id"]) ? (int)$_GET["id"] : 0;
$isEdit    = $editId > 0;
$errors    = [];

$d = [
    'name'=>'', 'full_name_lo'=>'', 'nickname'=>'', 'username'=>'', 'status'=>'active',
    'staff_code'=>'', 'phone'=>'', 'email'=>'', 'dob'=>'', 'staff_role'=>'staff',
    'position'=>'', 'department'=>'', 'joined_date'=>date('Y-m-d'),
    'base_salary'=>'', 'bank_name'=>'', 'bank_account'=>'',
    'photo'=>'', 'contract_file'=>'', 'cv_file'=>'',
];

if ($isEdit) {
    $row = $pdo->prepare("
        SELECT u.id, u.name, u.username, u.status, u.phone, u.email,
               cs.staff_role, cs.position, cs.department, cs.joined_date,
               cs.full_name_lo, cs.nickname, cs.staff_code, cs.dob, cs.photo,
               cs.contract_file, cs.cv_file, cs.bank_name, cs.bank_account, cs.base_salary
        FROM company_staff cs JOIN users u ON u.id = cs.user_id
        WHERE cs.company_id = ? AND u.id = ?");
    $row->execute([$companyId, $editId]);
    $data = $row->fetch(PDO::FETCH_ASSOC);
    if (!$data) { header("Location: staff.php"); exit; }
    foreach ($d as $k=>$_) if (array_key_exists($k,$data) && $data[$k]!==null) $d[$k]=$data[$k];
}

/* ── Departments (per-company, manageable) ── */
$pdo->exec("CREATE TABLE IF NOT EXISTS company_departments (
    id INT AUTO_INCREMENT PRIMARY KEY, company_id INT NOT NULL, name VARCHAR(100) NOT NULL,
    UNIQUE KEY uq_company_dept (company_id, name)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
$cnt = $pdo->prepare("SELECT COUNT(*) FROM company_departments WHERE company_id=?");
$cnt->execute([$companyId]);
if (!$cnt->fetchColumn()) {
    $seed = ["Management","HR","Finance","IT","Sales","Marketing","Operations","Logistics","Customer Service","Other"];
    $ins = $pdo->prepare("INSERT IGNORE INTO company_departments (company_id,name) VALUES (?,?)");
    foreach ($seed as $s) $ins->execute([$companyId,$s]);
}

/* AJAX: manage departments */
if (isset($_POST['dept_action'])) {
    header('Content-Type: application/json; charset=utf-8');
    try {
        $a = $_POST['dept_action'];
        if ($a === 'add') {
            $n = trim($_POST['name'] ?? ''); if ($n==='') throw new Exception('Name required.');
            $pdo->prepare("INSERT IGNORE INTO company_departments (company_id,name) VALUES (?,?)")->execute([$companyId,$n]);
        } elseif ($a === 'rename') {
            $id=(int)$_POST['id']; $n=trim($_POST['name'] ?? ''); if ($n==='') throw new Exception('Name required.');
            $pdo->prepare("UPDATE company_departments SET name=? WHERE id=? AND company_id=?")->execute([$n,$id,$companyId]);
        } elseif ($a === 'delete') {
            $pdo->prepare("DELETE FROM company_departments WHERE id=? AND company_id=?")->execute([(int)$_POST['id'],$companyId]);
        }
        $r=$pdo->prepare("SELECT id,name FROM company_departments WHERE company_id=? ORDER BY name"); $r->execute([$companyId]);
        echo json_encode(['ok'=>true,'depts'=>$r->fetchAll(PDO::FETCH_ASSOC)]);
    } catch (Throwable $e) { echo json_encode(['ok'=>false,'msg'=>$e->getMessage()]); }
    exit;
}

$dr = $pdo->prepare("SELECT id,name FROM company_departments WHERE company_id=? ORDER BY name");
$dr->execute([$companyId]);
$departments = $dr->fetchAll(PDO::FETCH_ASSOC);

/* ── compress an uploaded image to a small JPEG (saves server space) ── */
function compressToJpeg($srcTmp, $ext, $dest, $maxW, $quality) {
    if (!function_exists('imagecreatetruecolor')) return false;   // GD not available
    switch ($ext) {
        case 'jpg': case 'jpeg': $img = @imagecreatefromjpeg($srcTmp); break;
        case 'png':              $img = @imagecreatefrompng($srcTmp);  break;
        case 'webp':             $img = function_exists('imagecreatefromwebp') ? @imagecreatefromwebp($srcTmp) : false; break;
        default: return false;
    }
    if (!$img) return false;
    $w = imagesx($img); $h = imagesy($img);
    $scale = ($maxW > 0 && $w > $maxW) ? $maxW / $w : 1;
    $nw = max(1, (int)round($w * $scale)); $nh = max(1, (int)round($h * $scale));
    $out = imagecreatetruecolor($nw, $nh);
    imagefill($out, 0, 0, imagecolorallocate($out, 255, 255, 255)); // flatten transparency
    imagecopyresampled($out, $img, 0,0,0,0, $nw,$nh, $w,$h);
    $ok = imagejpeg($out, $dest, $quality);
    imagedestroy($img); imagedestroy($out);
    return $ok;
}

/* ── file upload helper (compresses images) ── */
function saveUpload($field, $prefix, $uid, $allowed, $maxBytes, &$err, $imgMaxW = 0, $quality = 55) {
    if (empty($_FILES[$field]) || $_FILES[$field]['error'] === UPLOAD_ERR_NO_FILE) return null;
    if ($_FILES[$field]['error'] !== UPLOAD_ERR_OK) { $err[] = "Upload error on $field."; return null; }
    if ($_FILES[$field]['size'] > $maxBytes) { $err[] = ucfirst($field)." is too large (max ".round($maxBytes/1048576)." MB)."; return null; }
    $ext = strtolower(pathinfo($_FILES[$field]['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowed)) { $err[] = ucfirst($field).": .$ext not allowed."; return null; }
    $dir = __DIR__ . '/../uploads/staff';
    if (!is_dir($dir)) @mkdir($dir, 0775, true);

    $isImg = in_array($ext, ['jpg','jpeg','png','webp']);
    if ($isImg && $imgMaxW > 0) {
        $name = $prefix.'_'.$uid.'_'.time().'.jpg';
        if (compressToJpeg($_FILES[$field]['tmp_name'], $ext, $dir.'/'.$name, $imgMaxW, $quality))
            return 'uploads/staff/'.$name;
        /* fall through to plain move if GD unavailable */
    }
    $name = $prefix.'_'.$uid.'_'.time().'.'.$ext;
    if (!move_uploaded_file($_FILES[$field]['tmp_name'], $dir.'/'.$name)) { $err[] = "Could not save $field."; return null; }
    return 'uploads/staff/'.$name;
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $f = [
        'name'=>trim($_POST['name']??''), 'full_name_lo'=>trim($_POST['full_name_lo']??''),
        'nickname'=>trim($_POST['nickname']??''), 'username'=>trim($_POST['username']??''),
        'status'=>($_POST['status']??'active')==='inactive'?'inactive':'active',
        'staff_code'=>trim($_POST['staff_code']??''), 'phone'=>trim($_POST['phone']??''),
        'email'=>trim($_POST['email']??''), 'dob'=>trim($_POST['dob']??''),
        'staff_role'=>($_POST['staff_role']??'staff')==='admin'?'admin':'staff',
        'position'=>trim($_POST['position']??''), 'department'=>trim($_POST['department']??''),
        'joined_date'=>$_POST['joined_date']??date('Y-m-d'),
        'base_salary'=>($_POST['base_salary']??'')!==''?(float)str_replace(',','',$_POST['base_salary']):null,
        'bank_name'=>trim($_POST['bank_name']??''), 'bank_account'=>trim($_POST['bank_account']??''),
    ];
    $password = $_POST['password'] ?? '';
    foreach ($f as $k=>$val) if (array_key_exists($k,$d)) $d[$k]=$val;

    if ($f['name']==='') $errors[]="Full name (English) is required.";
    if ($f['username']==='') $errors[]="Username is required.";
    elseif (strlen($f['username'])<3) $errors[]="Username must be at least 3 characters.";
    if (!$isEdit && $password==='') $errors[]="Password is required.";

    /* username unique */
    if (empty($errors)) {
        $q=$isEdit?"SELECT id FROM users WHERE username=? AND id!=?":"SELECT id FROM users WHERE username=?";
        $p=$isEdit?[$f['username'],$editId]:[$f['username']];
        $st=$pdo->prepare($q); $st->execute($p);
        if ($st->fetch()) $errors[]="Username \"{$f['username']}\" is already taken.";
    }
    /* staff_code unique within company */
    if (empty($errors) && $f['staff_code']!=='') {
        $q=$isEdit?"SELECT user_id FROM company_staff WHERE company_id=? AND staff_code=? AND user_id!=?"
                  :"SELECT user_id FROM company_staff WHERE company_id=? AND staff_code=?";
        $p=$isEdit?[$companyId,$f['staff_code'],$editId]:[$companyId,$f['staff_code']];
        $st=$pdo->prepare($q); $st->execute($p);
        if ($st->fetch()) $errors[]="Staff ID \"{$f['staff_code']}\" is already used.";
    }

    if (empty($errors)) {
        /* email is UNIQUE — store NULL (not '') when blank so multiple staff can
           be saved without an email. phone may also be blank -> NULL. */
        $emailVal = trim($f['email']) !== '' ? $f['email'] : null;
        $phoneVal = trim($f['phone']) !== '' ? $f['phone'] : null;
        $pdo->beginTransaction();
        try {
            if ($isEdit) {
                $uid = $editId;
                /* keep the LOGIN role in sync: Admin Staff => company_admin (sees the
                   manager dashboard + approvals); plain Staff => customer (wallet/HR). */
                $userRole = $f['staff_role']==='admin' ? 'company_admin' : 'customer';
                $pdo->prepare("UPDATE users SET name=?, username=?, status=?, phone=?, email=?, role=? WHERE id=?")
                    ->execute([$f['name'],$f['username'],$f['status'],$phoneVal,$emailVal,$userRole,$uid]);
            } else {
                $hash = password_hash($password, PASSWORD_DEFAULT);
                $userRole = $f['staff_role']==='admin'?'company_admin':'customer';
                $pdo->prepare("INSERT INTO users (name, username, email, phone, password, role, status, created_at) VALUES (?,?,?,?,?,?,?,NOW())")
                    ->execute([$f['name'],$f['username'],$emailVal,$phoneVal,$hash,$userRole,$f['status']]);
                $uid = (int)$pdo->lastInsertId();
                $pdo->prepare("INSERT INTO company_staff (user_id, company_id, staff_role, position, department, joined_date) VALUES (?,?,?,?,?,?)")
                    ->execute([$uid,$companyId,$f['staff_role'],$f['position'],$f['department'],$f['joined_date']]);
                /* Always give every staff member (and company admin) a wallet so
                   they can use the wallet + HR dashboard. Unique code by user id. */
                $customerCode = "ST".str_pad((string)$uid, 6, "0", STR_PAD_LEFT);
                $payId = generate_unique_pay_id($pdo);
                /* phone/email kept NULL on the wallet — customers.phone is UNIQUE
                   and the real phone lives on the users row. */
                $pdo->prepare("INSERT INTO customers (user_id, customer_code, pay_id, full_name, phone, email, balance, status, created_at)
                               VALUES (?,?,?,?,NULL,NULL,0,'active',NOW())")
                    ->execute([$uid,$customerCode,$payId,$f['name']]);
            }

            /* uploads (after we have a uid) */
            $imgExt = ['jpg','jpeg','png','webp'];
            $docExt = ['pdf','doc','docx','jpg','jpeg','png'];
            /* photo -> small square-ish JPEG; document images -> compressed but readable */
            $photo    = saveUpload('photo','photo',$uid,$imgExt,8*1048576,$errors, 500, 50)        ?? $d['photo'];
            $contract = saveUpload('contract','contract',$uid,$docExt,12*1048576,$errors, 1280, 60) ?? $d['contract_file'];
            $cv       = saveUpload('cv','cv',$uid,$docExt,12*1048576,$errors, 1280, 60)             ?? $d['cv_file'];

            $dobVal = ($f['dob']!=='' && preg_match('/^\d{4}-\d{2}-\d{2}$/',$f['dob'])) ? $f['dob'] : null;

            $pdo->prepare("UPDATE company_staff SET staff_role=?, position=?, department=?, joined_date=?,
                           full_name_lo=?, nickname=?, staff_code=?, dob=?, photo=?, contract_file=?, cv_file=?,
                           bank_name=?, bank_account=?, base_salary=? WHERE user_id=? AND company_id=?")
                ->execute([$f['staff_role'],$f['position'],$f['department'],$f['joined_date'],
                           $f['full_name_lo']?:null,$f['nickname']?:null,$f['staff_code']?:null,$dobVal,
                           $photo,$contract,$cv,$f['bank_name']?:null,$f['bank_account']?:null,$f['base_salary'],
                           $uid,$companyId]);

            $pdo->commit();
            header("Location: staff.php?msg=saved"); exit;
        } catch (Throwable $e) {
            $pdo->rollBack();
            $errors[]="Database error: ".$e->getMessage();
        }
    }
}

$val = fn($k) => htmlspecialchars((string)($d[$k] ?? ""));
function fileLink($path, $labelEn, $labelLo){
    if (!$path) return '<span class="hint" data-lo="ຍັງບໍ່ມີໄຟລ໌" data-en="No file yet">No file yet</span>';
    return '<a class="filelink" href="../'.htmlspecialchars($path).'" target="_blank">📎 <span data-lo="'.$labelLo.'" data-en="'.$labelEn.'">'.$labelEn.'</span></a>';
}
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $isEdit ? "Edit" : "Add" ?> Staff</title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;600;700;800&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.13/flatpickr.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.13/flatpickr.min.js"></script>
    <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;
            --red:#dc2626;--red-lt:#fee2e2;--green:#16a34a;--green-lt:#dcfce7;--radius:14px;--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:12px 24px;display:flex;align-items:center;gap:14px;justify-content:space-between;position:sticky;top:0;z-index:100;box-shadow:0 1px 6px rgba(15,23,42,.06);}
        .back-link{display:inline-flex;align-items:center;gap:6px;color:var(--muted);text-decoration:none;font-size:13px;font-weight:700;padding:6px 12px;border-radius:8px;border:1.5px solid var(--border);}
        .top-bar h1{font-size:17px;font-weight:800;}
        .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-body{padding:28px 16px;max-width:760px;margin:auto;}
        .form-card{background:var(--surface);border-radius:var(--radius);box-shadow:var(--shadow);border:1px solid var(--border);padding:28px;}
        .section-head{font-size:12px;font-weight:800;color:var(--muted);text-transform:uppercase;letter-spacing:.5px;margin:26px 0 14px;padding-bottom:8px;border-bottom:1px solid var(--border);}
        .section-head:first-of-type{margin-top:0;}
        .form-row{display:grid;grid-template-columns:1fr 1fr;gap:16px;}
        .form-group{margin-bottom:16px;}
        label{display:block;font-size:13px;font-weight:700;color:var(--text);margin-bottom:6px;}
        input,select{width:100%;padding:11px 14px;border:1.5px solid var(--border);border-radius:10px;font-size:14px;font-family:inherit;color:var(--text);background:#f8fafc;outline:none;}
        input:focus,select:focus{border-color:var(--primary);background:#fff;box-shadow:0 0 0 3px rgba(15,118,110,.1);}
        input[type=file]{padding:8px;background:#fff;}
        .input-prefix{display:flex;align-items:center;border:1.5px solid var(--border);border-radius:10px;overflow:hidden;background:#f8fafc;}
        .prefix-label{padding:11px 12px;background:#f1f5f9;border-right:1.5px solid var(--border);font-size:13px;color:var(--muted);font-weight:700;}
        .input-prefix input{border:none;border-radius:0;background:transparent;}
        .hint{font-size:12px;color:var(--muted);margin-top:5px;line-height:1.5;}
        .error-list{background:var(--red-lt);border:1.5px solid #fca5a5;border-radius:10px;padding:14px 16px;margin-bottom:20px;}
        .error-list li{color:var(--red);font-size:13px;font-weight:600;margin-bottom:3px;list-style:none;}
        .photo-wrap{display:flex;align-items:center;gap:16px;margin-bottom:6px;}
        .photo-prev{width:74px;height:74px;border-radius:14px;object-fit:cover;border:1.5px solid var(--border);background:#f1f5f9;display:flex;align-items:center;justify-content:center;font-size:30px;color:var(--muted);}
        .filelink{display:inline-flex;align-items:center;gap:6px;color:var(--primary);font-weight:700;font-size:13px;text-decoration:none;background:#f0fdfa;border:1.5px solid #99f6e4;padding:7px 12px;border-radius:9px;margin-top:6px;}
        .form-actions{display:flex;gap:10px;justify-content:flex-end;margin-top:24px;padding-top:20px;border-top:1px solid var(--border);}
        .btn{display:inline-flex;align-items:center;gap:7px;padding:11px 22px;border-radius:10px;font-size:14px;font-weight:700;font-family:inherit;cursor:pointer;border:none;text-decoration:none;}
        .btn-primary{background:linear-gradient(135deg,#084740,#0f766e);color:#fff;box-shadow:0 3px 10px rgba(15,118,110,.3);}
        .btn-cancel{background:#f1f5f9;color:var(--muted);border:1.5px solid var(--border);}
        .dept-panel{margin-top:10px;border:1.5px dashed var(--border);border-radius:10px;padding:12px;background:#f8fafc;}
        .dp-title{font-size:12px;font-weight:800;color:var(--muted);margin-bottom:10px;text-transform:uppercase;letter-spacing:.4px;}
        .dp-item{display:flex;gap:8px;margin-bottom:8px;align-items:center;}
        .dp-item input{flex:1;padding:8px 10px;font-size:13px;}
        .dp-btn{padding:8px 12px;border-radius:8px;border:none;font-size:12px;font-weight:700;cursor:pointer;font-family:inherit;}
        .dp-btn.save{background:var(--green-lt);color:#15803d;border:1.5px solid #86efac;}
        .dp-btn.del{background:var(--red-lt);color:var(--red);border:1.5px solid #fca5a5;}
        .dp-btn.add{background:var(--primary);color:#fff;}
        .dp-add{display:flex;gap:8px;margin-top:10px;padding-top:10px;border-top:1px solid var(--border);}
        .dp-add input{flex:1;padding:8px 10px;font-size:13px;}
        @media(max-width:600px){.form-row{grid-template-columns:1fr;}.page-body{padding:14px;}.form-card{padding:18px;}}
    </style>
</head>
<body>

<div class="top-bar">
    <a class="back-link" href="staff.php">← <span data-lo="ລາຍຊື່ພະນັກງານ" data-en="Staff List">Staff List</span></a>
    <h1><?= $isEdit ? "✏️ Edit Staff" : "👤 Add Staff" ?></h1>
    <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-body">
<div class="form-card">

    <?php if (!empty($errors)): ?>
    <ul class="error-list">
        <?php foreach ($errors as $e): ?><li>⚠️ <?= htmlspecialchars($e) ?></li><?php endforeach; ?>
    </ul>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data" id="staffForm">

        <div class="section-head" data-lo="ຂໍ້ມູນສ່ວນຕົວ" data-en="Personal Information">Personal Information</div>

        <!-- photo -->
        <div class="form-group">
            <label data-lo="ຮູບພະນັກງານ" data-en="Photo">Photo</label>
            <div class="photo-wrap">
                <?php if ($d['photo']): ?>
                    <img class="photo-prev" src="../<?= htmlspecialchars($d['photo']) ?>" alt="">
                <?php else: ?>
                    <div class="photo-prev">👤</div>
                <?php endif; ?>
                <input type="file" name="photo" accept="image/*">
            </div>
            <div class="hint" data-lo="JPG/PNG, ສູງສຸດ 4MB" data-en="JPG/PNG, max 4MB">JPG/PNG, max 4MB</div>
        </div>

        <div class="form-row">
            <div class="form-group">
                <label data-lo="ຊື່ເຕັມ (ອັງກິດ)" data-en="Full Name (English)">Full Name (English) <span style="color:var(--red)">*</span></label>
                <input type="text" name="name" value="<?= $val('name') ?>" required oninput="suggestUsername(this.value)">
            </div>
            <div class="form-group">
                <label data-lo="ຊື່ເຕັມ (ລາວ)" data-en="Full Name (Lao)">Full Name (Lao)</label>
                <input type="text" name="full_name_lo" value="<?= $val('full_name_lo') ?>" placeholder="ຊື່ ແລະ ນາມສະກຸນ">
            </div>
        </div>

        <div class="form-row">
            <div class="form-group">
                <label data-lo="ຊື່ຫຼິ້ນ" data-en="Nickname">Nickname</label>
                <input type="text" name="nickname" value="<?= $val('nickname') ?>">
            </div>
            <div class="form-group">
                <label data-lo="ລະຫັດພະນັກງານ (ບໍ່ຊ້ຳ)" data-en="Staff ID (unique)">Staff ID (unique)</label>
                <input type="text" name="staff_code" value="<?= $val('staff_code') ?>" placeholder="e.g. SD-001">
            </div>
        </div>

        <div class="form-row">
            <div class="form-group">
                <label data-lo="ຊື່ຜູ້ໃຊ້ (Username)" data-en="Username">Username <span style="color:var(--red)">*</span></label>
                <div class="input-prefix">
                    <span class="prefix-label">@</span>
                    <input type="text" id="username" name="username" value="<?= $val('username') ?>" minlength="3" required>
                </div>
                <div class="hint" data-lo="ໃຊ້ສຳລັບເຂົ້າສູ່ລະບົບ. ຢ່າງໜ້ອຍ 3 ຕົວ, ບໍ່ຊ້ຳ." data-en="Used to log in. Min 3 chars, unique.">Used to log in. Min 3 chars, unique.</div>
            </div>
            <?php if (!$isEdit): ?>
            <div class="form-group">
                <label data-lo="ລະຫັດຜ່ານ" data-en="Password">Password <span style="color:var(--red)">*</span></label>
                <input type="text" name="password" placeholder="Enter any password">
                <div class="hint" data-lo="ສະແດງໃຫ້ເຫັນ ເພື່ອບອກພະນັກງານ." data-en="Shown so you can share it with staff.">Shown so you can share it.</div>
            </div>
            <?php endif; ?>
        </div>

        <div class="form-row">
            <div class="form-group">
                <label data-lo="ເບີໂທ" data-en="Phone Number">Phone Number</label>
                <input type="text" name="phone" value="<?= $val('phone') ?>" placeholder="e.g. 2055xxxxxx">
            </div>
            <div class="form-group">
                <label data-lo="ອີເມວ" data-en="Email">Email</label>
                <input type="email" name="email" value="<?= $val('email') ?>">
            </div>
        </div>

        <div class="form-row">
            <div class="form-group">
                <label data-lo="ວັນເດືອນປີເກີດ" data-en="Date of Birth">Date of Birth</label>
                <input type="text" class="fp-date" name="dob" value="<?= $val('dob') ?>" placeholder="dd/mm/yyyy" autocomplete="off">
            </div>
            <div class="form-group">
                <label data-lo="ສະຖານະ" data-en="Status">Status</label>
                <select name="status">
                    <option value="active" <?= $d['status']==='active'?'selected':'' ?>>✅ Active</option>
                    <option value="inactive" <?= $d['status']==='inactive'?'selected':'' ?>>⛔ Inactive</option>
                </select>
            </div>
        </div>

        <div class="form-group">
            <label data-lo="ບົດບາດໃນບໍລິສັດ" data-en="Role in Company">Role in Company</label>
            <select name="staff_role">
                <option value="staff" <?= $d['staff_role']==='staff'?'selected':'' ?>>👤 Staff</option>
                <option value="admin" <?= $d['staff_role']==='admin'?'selected':'' ?>>👑 Company Admin</option>
            </select>
        </div>

        <!-- work -->
        <div class="section-head" data-lo="ຂໍ້ມູນວຽກ" data-en="Work Information">Work Information</div>
        <div class="form-row">
            <div class="form-group">
                <label data-lo="ຕຳແໜ່ງ" data-en="Position / Job Title">Position / Job Title</label>
                <input type="text" name="position" value="<?= $val('position') ?>" placeholder="e.g. Senior Developer">
            </div>
            <div class="form-group">
                <label style="display:flex;justify-content:space-between;align-items:center;">
                    <span data-lo="ພະແນກ" data-en="Department">Department</span>
                    <a href="javascript:void(0)" onclick="toggleDeptPanel()" style="font-size:12px;color:var(--primary);font-weight:700;text-decoration:none;" data-lo="⚙ ຈັດການ" data-en="⚙ Manage">⚙ Manage</a>
                </label>
                <select name="department" id="deptSelect" data-current="<?= htmlspecialchars($d['department']) ?>">
                    <option value="">— Select —</option>
                    <?php foreach ($departments as $dep): ?>
                        <option value="<?= htmlspecialchars($dep['name']) ?>" <?= $d['department']===$dep['name']?'selected':'' ?>><?= htmlspecialchars($dep['name']) ?></option>
                    <?php endforeach; ?>
                </select>

                <div class="dept-panel" id="deptPanel" style="display:none;">
                    <div class="dp-title" data-lo="ຈັດການພະແນກ" data-en="Manage departments">Manage departments</div>
                    <div id="deptList"></div>
                    <div class="dp-add">
                        <input type="text" id="deptNew" placeholder="New department…" data-lo-placeholder="ພະແນກໃໝ່…" data-en-placeholder="New department…">
                        <button type="button" class="dp-btn add" onclick="deptAdd()" data-lo="ເພີ່ມ" data-en="Add">Add</button>
                    </div>
                </div>
            </div>
        </div>
        <div class="form-row">
            <div class="form-group">
                <label data-lo="ວັນທີເລີ່ມວຽກ" data-en="Date Joined">Date Joined</label>
                <input type="text" class="fp-date" name="joined_date" value="<?= $val('joined_date') ?>" placeholder="dd/mm/yyyy" autocomplete="off">
            </div>
            <div class="form-group">
                <label data-lo="ເງິນເດືອນພື້ນຖານ (₭)" data-en="Base Salary (₭)">Base Salary (₭)</label>
                <input type="text" inputmode="numeric" id="base_salary" name="base_salary"
                    value="<?= ($d['base_salary']!=='' && $d['base_salary']!==null) ? number_format((float)$d['base_salary']) : '' ?>"
                    placeholder="e.g. 3,000,000" oninput="formatMoney(this)" autocomplete="off">
                <div class="hint" data-lo="ສາມາດປ່ຽນໄດ້. ໃຊ້ເປັນຄ່າເລີ່ມຕົ້ນຕອນຄິດໄລ່ເງິນເດືອນ." data-en="Editable. Used as the default base when generating payroll.">Editable. Used as payroll default.</div>
            </div>
        </div>

        <!-- bank -->
        <div class="section-head" data-lo="ຂໍ້ມູນທະນາຄານ" data-en="Bank Information">Bank Information</div>
        <div class="form-row">
            <div class="form-group">
                <label data-lo="ຊື່ທະນາຄານ" data-en="Bank Name">Bank Name</label>
                <input type="text" name="bank_name" value="<?= $val('bank_name') ?>" placeholder="e.g. BCEL">
            </div>
            <div class="form-group">
                <label data-lo="ເລກບັນຊີ" data-en="Account No.">Account No.</label>
                <input type="text" name="bank_account" value="<?= $val('bank_account') ?>">
            </div>
        </div>

        <!-- documents -->
        <div class="section-head" data-lo="ເອກະສານ" data-en="Documents">Documents</div>
        <div class="form-row">
            <div class="form-group">
                <label data-lo="ສັນຍາ (Contract)" data-en="Contract">Contract</label>
                <input type="file" name="contract" accept=".pdf,.doc,.docx,image/*">
                <div><?= fileLink($d['contract_file'],'View contract','ເບິ່ງສັນຍາ') ?></div>
                <div class="hint" data-lo="PDF/DOC/ຮູບ, ສູງສຸດ 10MB" data-en="PDF/DOC/image, max 10MB">PDF/DOC/image, max 10MB</div>
            </div>
            <div class="form-group">
                <label data-lo="ປະຫວັດ (CV)" data-en="CV / Resume">CV / Resume</label>
                <input type="file" name="cv" accept=".pdf,.doc,.docx,image/*">
                <div><?= fileLink($d['cv_file'],'View CV','ເບິ່ງ CV') ?></div>
                <div class="hint" data-lo="PDF/DOC/ຮູບ, ສູງສຸດ 10MB" data-en="PDF/DOC/image, max 10MB">PDF/DOC/image, max 10MB</div>
            </div>
        </div>

        <div class="form-actions">
            <a class="btn btn-cancel" href="staff.php" data-lo="ຍົກເລີກ" data-en="Cancel">Cancel</a>
            <button class="btn btn-primary" type="submit"><?= $isEdit ? "💾 Save Changes" : "👤 Add Staff" ?></button>
        </div>
    </form>
</div>
</div>

<script>
function suggestUsername(name){
    const el=document.getElementById('username');
    if(!el || el.dataset.manuallyEdited || el.value) return;
    el.value = name.trim().replace(/\s+/g,'.').substring(0,30);
}
document.getElementById('username')?.addEventListener('input',function(){this.dataset.manuallyEdited='1';});

/* ── Flatpickr dates (show dd/mm/yyyy, submit yyyy-mm-dd) ── */
document.addEventListener('DOMContentLoaded',function(){
    if (typeof flatpickr !== 'undefined') {
        document.querySelectorAll('.fp-date').forEach(function(el){
            flatpickr(el, { altInput:true, altFormat:'d/m/Y', dateFormat:'Y-m-d', allowInput:true });
        });
    }
});

/* ── Money formatting with thousands separators ── */
function formatMoney(el){
    const raw = el.value.replace(/[^\d]/g,'');
    el.value = raw ? Number(raw).toLocaleString('en-US') : '';
}

/* ── Manage departments ── */
function toggleDeptPanel(){
    const p=document.getElementById('deptPanel');
    const show = p.style.display==='none';
    p.style.display = show ? 'block' : 'none';
    if (show) deptRefresh();
}
function deptApi(data){
    const body=new URLSearchParams(data);
    return fetch('staff_form.php', {method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body})
        .then(r=>r.json());
}
function renderDepts(depts){
    const sel=document.getElementById('deptSelect');
    const current=sel.value || sel.dataset.current || '';
    sel.innerHTML='<option value="">— Select —</option>';
    depts.forEach(d=>{
        const o=document.createElement('option'); o.value=d.name; o.textContent=d.name;
        if(d.name===current) o.selected=true; sel.appendChild(o);
    });
    const list=document.getElementById('deptList'); list.innerHTML='';
    depts.forEach(d=>{
        const row=document.createElement('div'); row.className='dp-item';
        const inp=document.createElement('input'); inp.type='text'; inp.value=d.name;
        const save=document.createElement('button'); save.type='button'; save.className='dp-btn save'; save.textContent='✓';
        save.onclick=()=>deptApi({dept_action:'rename',id:d.id,name:inp.value}).then(r=>r.ok?renderDepts(r.depts):alert(r.msg));
        const del=document.createElement('button'); del.type='button'; del.className='dp-btn del'; del.textContent='🗑';
        del.onclick=()=>{ if(confirm('Delete this department?')) deptApi({dept_action:'delete',id:d.id}).then(r=>r.ok&&renderDepts(r.depts)); };
        row.appendChild(inp); row.appendChild(save); row.appendChild(del); list.appendChild(row);
    });
}
function deptRefresh(){ deptApi({dept_action:'list'}).then(r=>{ if(r.ok) renderDepts(r.depts); }); }
function deptAdd(){
    const inp=document.getElementById('deptNew'); const n=inp.value.trim(); if(!n) return;
    deptApi({dept_action:'add',name:n}).then(r=>{ if(r.ok){ inp.value=''; renderDepts(r.depts);} else alert(r.msg); });
}
</script>

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