<?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"];
$editId    = isset($_GET["id"]) ? (int)$_GET["id"] : 0;
$isEdit    = $editId > 0;
$errors    = [];

$staffUser = ["name" => "", "username" => "", "status" => "active"];
$staffMeta = ["staff_role" => "staff", "position" => "", "department" => "", "joined_date" => date("Y-m-d")];

if ($isEdit) {
    $row = $pdo->prepare("
        SELECT u.id, u.name, u.username, u.status,
               cs.staff_role, cs.position, cs.department, cs.joined_date
        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; }
    $staffUser = ['name' => $data['name'], 'username' => $data['username'], 'status' => $data['status']];
    $staffMeta = ['staff_role' => $data['staff_role'], 'position' => $data['position'], 'department' => $data['department'], 'joined_date' => $data['joined_date']];
}

$departments = ["Management","HR","Finance","IT","Sales","Marketing","Operations","Logistics","Customer Service","Other"];

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $name       = trim($_POST["name"]       ?? "");
    $username   = trim($_POST["username"] ?? "");
    $password   = $_POST["password"]        ?? "";
    $status     = $_POST["status"] === "inactive" ? "inactive" : "active";
    $staffRole  = $_POST["staff_role"] === "admin" ? "admin" : "staff";
    $position   = trim($_POST["position"]   ?? "");
    $department = trim($_POST["department"] ?? "");
    $joinedDate = $_POST["joined_date"]     ?? date("Y-m-d");

    /* ── Validation ── */
    if ($name === "") $errors[] = "Full name is required.";
    if ($username === "") {
        $errors[] = "Username is required.";
    } elseif (strlen($username) < 3) {
        $errors[] = "Username must be at least 3 characters.";
    }
    if (!$isEdit && $password === "") {
        $errors[] = "Password is required.";
    }

    /* Check username unique */
    if (empty($errors)) {
        $chkQ = $isEdit
            ? "SELECT id FROM users WHERE username = ? AND id != ?"
            : "SELECT id FROM users WHERE username = ?";
        $chkP = $isEdit ? [$username, $editId] : [$username];
        $chk  = $pdo->prepare($chkQ);
        $chk->execute($chkP);
        if ($chk->fetch()) $errors[] = "Username \"$username\" is already taken.";
    }

    if (empty($errors)) {
        $pdo->beginTransaction();
        try {
            if ($isEdit) {
                $pdo->prepare("UPDATE users SET name=?, username=?, status=? WHERE id=?")
                    ->execute([$name, $username, $status, $editId]);
                $pdo->prepare("UPDATE company_staff SET staff_role=?, position=?, department=?, joined_date=? WHERE user_id=? AND company_id=?")
                    ->execute([$staffRole, $position, $department, $joinedDate, $editId, $companyId]);
            } else {
                $hash = password_hash($password, PASSWORD_DEFAULT);
                /* company_admin keeps that role; regular staff use customer role
                   so they can access the customer dashboard + HR section */
                $userRole = $staffRole === "admin" ? "company_admin" : "customer";
                $pdo->prepare("INSERT INTO users (name, username, email, password, role, status, created_at) VALUES (?,?,?,?,?,?,NOW())")
                    ->execute([$name, $username, '', $hash, $userRole, $status]);
                $newId = (int)$pdo->lastInsertId();

                /* Link to company */
                $pdo->prepare("INSERT INTO company_staff (user_id, company_id, staff_role, position, department, joined_date) VALUES (?,?,?,?,?,?)")
                    ->execute([$newId, $companyId, $staffRole, $position, $department, $joinedDate]);

                /* Auto-create customer wallet so they can use wallet + HR dashboard */
                if ($userRole === "customer") {
                    $customerCode = "CO" . str_pad($companyId, 3, "0", STR_PAD_LEFT) . rand(1000, 9999);
                    $pdo->prepare("INSERT INTO customers (user_id, customer_code, full_name, balance, created_at) VALUES (?,?,?,0,NOW())")
                        ->execute([$newId, $customerCode, $name]);
                }
            }
            $pdo->commit();
            header("Location: staff.php?msg=saved"); exit;
        } catch (Throwable $e) {
            $pdo->rollBack();
            $errors[] = "Database error: " . $e->getMessage();
        }
    }

    /* Repopulate on error */
    $staffUser = ['name' => $name, 'username' => $username, 'status' => $status];
    $staffMeta = ['staff_role' => $staffRole, 'position' => $position, 'department' => $department, 'joined_date' => $joinedDate];
}

$v = fn($key, $arr) => htmlspecialchars($arr[$key] ?? "");
?>
<!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">
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        :root {
            --primary: #0f766e; --surface: #ffffff; --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 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-link { display: inline-flex; align-items: center; gap: 6px; color: var(--muted); text-decoration: none; font-size: 13px; font-weight: 600; padding: 6px 12px; border-radius: 8px; border: 1.5px solid var(--border); transition: all .15s; }
        .back-link:hover { border-color: var(--primary); color: var(--primary); }
        .top-bar h1 { font-size: 17px; font-weight: 800; }
        .page-body { padding: 32px; max-width: 680px; margin: auto; }
        .form-card { background: var(--surface); border-radius: var(--radius); box-shadow: var(--shadow); border: 1px solid var(--border); padding: 32px; }
        .section-head { font-size: 12px; font-weight: 700; color: var(--muted); text-transform: uppercase; letter-spacing: .5px; margin: 24px 0 14px; padding-bottom: 8px; border-bottom: 1px solid var(--border); }
        .section-head:first-child { margin-top: 0; }
        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
        .form-group { margin-bottom: 18px; }
        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; transition: border-color .15s, box-shadow .15s; outline: none; }
        input:focus, select:focus { border-color: var(--primary); background: #fff; box-shadow: 0 0 0 3px rgba(15,118,110,.1); }
        input.error-field { border-color: var(--red); }

        /* username prefix */
        .input-prefix { display: flex; align-items: center; border: 1.5px solid var(--border); border-radius: 10px; overflow: hidden; background: #f8fafc; transition: border-color .15s, box-shadow .15s; }
        .input-prefix:focus-within { border-color: var(--primary); background: #fff; box-shadow: 0 0 0 3px rgba(15,118,110,.1); }
        .prefix-label { padding: 11px 12px; background: #f1f5f9; border-right: 1.5px solid var(--border); font-size: 13px; color: var(--muted); font-weight: 700; white-space: nowrap; flex-shrink: 0; }
        .input-prefix input { border: none; border-radius: 0; background: transparent; box-shadow: none; padding: 11px 12px; flex: 1; }
        .input-prefix input:focus { box-shadow: none; border: none; background: transparent; }

        .hint { font-size: 12px; color: var(--muted); margin-top: 5px; line-height: 1.5; }
        .hint.valid { color: var(--green); }

        .error-list { background: var(--red-lt); border: 1.5px solid #fca5a5; border-radius: 10px; padding: 14px 16px; margin-bottom: 22px; }
        .error-list li { color: var(--red); font-size: 13px; font-weight: 600; margin-bottom: 3px; }

        /* login preview box */
        .login-preview { background: #f0fdf4; border: 1.5px solid #86efac; border-radius: 10px; padding: 14px 16px; margin-bottom: 18px; }
        .login-preview .lp-label { font-size: 11px; font-weight: 700; color: var(--green); text-transform: uppercase; letter-spacing: .4px; margin-bottom: 8px; }
        .login-preview .lp-row { display: flex; align-items: center; gap: 10px; font-size: 13px; margin-bottom: 4px; }
        .login-preview .lp-key { color: var(--muted); font-weight: 600; min-width: 80px; }
        .login-preview .lp-val { font-weight: 800; color: var(--text); font-family: monospace; }

        .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: 10px 22px; border-radius: 10px; font-size: 14px; font-weight: 700; font-family: inherit; cursor: pointer; border: none; text-decoration: none; transition: all .15s; }
        .btn-primary { background: linear-gradient(135deg,#084740,#0f766e); color: #fff; box-shadow: 0 3px 10px rgba(15,118,110,.3); }
        .btn-primary:hover { opacity: .9; }
        .btn-cancel { background: #f1f5f9; color: var(--muted); border: 1.5px solid var(--border); }

        @media (max-width: 600px) { .form-row { grid-template-columns: 1fr; } .page-body { padding: 16px; } .form-card { padding: 20px; } }
    </style>
</head>
<body>

<div class="top-bar">
    <a class="back-link" href="staff.php">← Staff List</a>
    <h1><?= $isEdit ? "✏️ Edit Staff" : "👤 Add Staff Member" ?></h1>
</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" id="staffForm">

        <!-- ── Personal info ── -->
        <div class="section-head">Personal Information</div>

        <div class="form-row">
            <div class="form-group">
                <label for="name">Full Name <span style="color:var(--red)">*</span></label>
                <input type="text" id="name" name="name"
                    value="<?= $v('name', $staffUser) ?>"
                    placeholder="e.g. Somchai Phommasack" required
                    oninput="suggestUsername(this.value)">
            </div>
            <div class="form-group">
                <label for="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="<?= $v('username', $staffUser) ?>"
                        placeholder="e.g. somchai or ສົມໄຊ"
                        minlength="3"
                        required
                        oninput="validateUsername(this)">
                </div>
                <div class="hint" id="usernameHint">Any characters allowed. Min 3 characters. Must be unique.</div>
            </div>
        </div>

        <?php if (!$isEdit): ?>
        <!-- Login preview -->
        <div class="login-preview" id="loginPreview" style="display:none">
            <div class="lp-label">🔐 Staff login credentials</div>
            <div class="lp-row">
                <span class="lp-key">Username:</span>
                <span class="lp-val" id="previewUsername">—</span>
            </div>
            <div class="lp-row">
                <span class="lp-key">Password:</span>
                <span class="lp-val" id="previewPassword">—</span>
            </div>
            <div class="hint" style="margin-top:6px">Share these credentials with the staff member after saving.</div>
        </div>

        <div class="form-group">
            <label for="password">Password <span style="color:var(--red)">*</span></label>
            <input type="text" id="password" name="password"
                placeholder="Enter any password"
                oninput="updatePreview()">
            <div class="hint">Visible so you can share it easily with the staff member.</div>
        </div>
        <?php endif; ?>

        <div class="form-row">
            <div class="form-group">
                <label>Status</label>
                <select name="status">
                    <option value="active"   <?= ($staffUser['status'] ?? 'active') === 'active'   ? 'selected' : '' ?>>✅ Active</option>
                    <option value="inactive" <?= ($staffUser['status'] ?? 'active') === 'inactive' ? 'selected' : '' ?>>⛔ Inactive</option>
                </select>
            </div>
            <div class="form-group">
                <label>Role in Company</label>
                <select name="staff_role">
                    <option value="staff" <?= ($staffMeta['staff_role'] ?? 'staff') === 'staff' ? 'selected' : '' ?>>👤 Staff</option>
                    <option value="admin" <?= ($staffMeta['staff_role'] ?? 'staff') === 'admin' ? 'selected' : '' ?>>👑 Company Admin</option>
                </select>
            </div>
        </div>

        <!-- ── Work info ── -->
        <div class="section-head">Work Information</div>

        <div class="form-row">
            <div class="form-group">
                <label>Position / Job Title</label>
                <input type="text" name="position"
                    value="<?= $v('position', $staffMeta) ?>"
                    placeholder="e.g. Senior Developer">
            </div>
            <div class="form-group">
                <label>Department</label>
                <select name="department">
                    <option value="">— Select —</option>
                    <?php foreach ($departments as $d): ?>
                        <option value="<?= $d ?>" <?= ($staffMeta['department'] ?? '') === $d ? 'selected' : '' ?>><?= $d ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>

        <div class="form-group">
            <label>Date Joined</label>
            <input type="date" name="joined_date" value="<?= $v('joined_date', $staffMeta) ?>">
        </div>

        <div class="form-actions">
            <a class="btn btn-cancel" href="staff.php">Cancel</a>
            <button class="btn btn-primary" type="submit">
                <?= $isEdit ? "💾 Save Changes" : "👤 Add Staff Member" ?>
            </button>
        </div>

    </form>
</div>
</div>

<script>
/* ── Auto-suggest username from full name ── */
function suggestUsername(name) {
    const el = document.getElementById('username');
    if (el.dataset.manuallyEdited) return;
    // Just use the name trimmed, spaces replaced with dots, max 30 chars
    const slug = name.trim().replace(/\s+/g, '.').substring(0, 30);
    el.value = slug;
    validateUsername(el);
    updatePreview();
}

document.getElementById('username')?.addEventListener('input', function() {
    this.dataset.manuallyEdited = '1';
});

/* ── Validate username — length only ── */
function validateUsername(el) {
    const hint = document.getElementById('usernameHint');
    const val  = el.value;
    if (!val) {
        hint.textContent = 'Any characters allowed. Min 3 characters. Must be unique.';
        hint.className = 'hint';
        el.classList.remove('error-field');
        return;
    }
    if (val.length < 3) {
        hint.textContent = '⚠️ Too short — minimum 3 characters.';
        hint.className = 'hint';
        el.classList.add('error-field');
        return;
    }
    hint.textContent = '✅ Username looks good.';
    hint.className = 'hint valid';
    el.classList.remove('error-field');
    updatePreview();
}

/* ── Login credentials preview ── */
function updatePreview() {
    const preview  = document.getElementById('loginPreview');
    const pwEl     = document.getElementById('password');
    const unEl     = document.getElementById('username');
    const prevUN   = document.getElementById('previewUsername');
    const prevPW   = document.getElementById('previewPassword');
    if (!preview || !pwEl || !unEl) return;

    const un = unEl.value.trim();
    const pw = pwEl.value;

    if (un || pw) {
        preview.style.display = 'block';
        prevUN.textContent = un || '—';
        prevPW.textContent = pw || '—';
    } else {
        preview.style.display = 'none';
    }
}
</script>

</body>
</html>