<?php
/* ============================================================================
 *  company/staff_repair.php — recover orphaned staff (company_staff rows whose
 *  users account was deleted). Recreates the users login row with the SAME id
 *  so the existing company_staff record reconnects, and rebuilds the wallet.
 *  Admin-only. Safe to delete after use.
 * ==========================================================================*/
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';
date_default_timezone_set('Asia/Vientiane');
$companyId = (int)$_SESSION["company_id"];
$msg = '';

/* ── handle repair submit ── */
if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action']??'')==='repair') {
    $uid      = (int)$_POST['user_id'];
    $name     = trim($_POST['name'] ?? '');
    $username = trim($_POST['username'] ?? '');
    $email    = trim($_POST['email'] ?? '');
    $phone    = trim($_POST['phone'] ?? '');
    $pass     = $_POST['password'] ?? '';
    $role     = ($_POST['staff_role'] ?? 'staff')==='admin' ? 'company_admin' : 'customer';

    /* the orphan row must exist for THIS company and still have no user */
    $chk = $pdo->prepare("SELECT cs.user_id FROM company_staff cs LEFT JOIN users u ON u.id=cs.user_id
                          WHERE cs.user_id=? AND cs.company_id=? AND u.id IS NULL LIMIT 1");
    $chk->execute([$uid,$companyId]);
    if (!$chk->fetchColumn()) {
        $msg = "<div class='flash err'>That row is no longer orphaned (or not in your company).</div>";
    } elseif ($name==='' || $username==='' || $pass==='') {
        $msg = "<div class='flash err'>Name, username and a temporary password are required.</div>";
    } else {
        try {
            $pdo->beginTransaction();
            $hash = password_hash($pass, PASSWORD_DEFAULT);
            /* email is UNIQUE — store NULL when blank (run setup_user_nullable.php first). */
            $emailVal = $email !== '' ? $email : null;
            $phoneVal = $phone !== '' ? $phone : null;
            /* recreate the users row with the ORIGINAL id so company_staff reconnects */
            $pdo->prepare("INSERT INTO users (id, name, username, email, phone, password, role, status, created_at)
                           VALUES (?,?,?,?,?,?,?,'active',NOW())")
                ->execute([$uid,$name,$username,$emailVal,$phoneVal,$hash,$role]);
            /* keep company_staff role in sync */
            $pdo->prepare("UPDATE company_staff SET staff_role=? WHERE user_id=? AND company_id=?")
                ->execute([($role==='company_admin'?'admin':'staff'),$uid,$companyId]);
            /* rebuild wallet if missing */
            $hasW = $pdo->prepare("SELECT id FROM customers WHERE user_id=? LIMIT 1");
            $hasW->execute([$uid]);
            if (!$hasW->fetchColumn()) {
                $code  = "ST".str_pad((string)$uid,6,"0",STR_PAD_LEFT);
                $payId = generate_unique_pay_id($pdo);
                $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,$code,$payId,$name]);
            }
            $pdo->commit();
            $msg = "<div class='flash ok'>Recovered <b>".htmlspecialchars($name)."</b>. They now appear in the Staff list — open <b>Edit</b> to fill in remaining details. Temp password set.</div>";
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            $msg = "<div class='flash err'>Error: ".htmlspecialchars($e->getMessage())."</div>";
        }
    }
}

/* ── find current orphans (recoverable data from company_staff) ── */
$orphans = $pdo->prepare("
    SELECT cs.user_id, cs.staff_code, cs.full_name_lo, cs.nickname, cs.position, cs.department,
           cs.joined_date, cs.base_salary
    FROM company_staff cs
    LEFT JOIN users u ON u.id = cs.user_id
    WHERE cs.company_id = ? AND u.id IS NULL
    ORDER BY cs.user_id ASC");
$orphans->execute([$companyId]);
$orphans = $orphans->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Recover staff</title>
<style>
*{box-sizing:border-box;margin:0;padding:0;font-family:Arial,Helvetica,sans-serif;}
body{background:#f0f4f8;color:#0f172a;padding:24px;}
.wrap{max-width:760px;margin:auto;}
h1{font-size:22px;margin-bottom:6px;}
.sub{color:#64748b;font-size:14px;margin-bottom:18px;}
.flash{padding:12px 15px;border-radius:9px;margin-bottom:16px;font-size:14px;font-weight:600;}
.flash.ok{background:#dcfce7;color:#15803d;}.flash.err{background:#fee2e2;color:#b91c1c;}
.card{background:#fff;border:1px solid #e2e8f0;border-radius:14px;padding:18px;margin-bottom:16px;box-shadow:0 2px 12px rgba(15,23,42,.06);}
.rec{font-size:13px;color:#475569;background:#f8fafc;border:1px solid #e2e8f0;border-radius:9px;padding:10px 12px;margin-bottom:14px;}
.rec b{color:#0f172a;}
label{display:block;font-size:12px;font-weight:700;color:#374151;margin:10px 0 4px;}
input,select{width:100%;padding:9px 11px;border:1.5px solid #e2e8f0;border-radius:9px;font-size:14px;}
.row{display:flex;gap:12px;flex-wrap:wrap;}.row>div{flex:1;min-width:200px;}
.btn{margin-top:14px;background:#0f766e;color:#fff;border:none;padding:11px 18px;border-radius:9px;font-weight:800;font-size:14px;cursor:pointer;}
.none{background:#fff;border-radius:14px;padding:30px;text-align:center;color:#16a34a;font-weight:700;}
a.back{display:inline-block;margin-top:8px;color:#0f766e;font-weight:700;text-decoration:none;}
</style>
</head>
<body>
<div class="wrap">
<h1>Recover missing staff</h1>
<div class="sub">These staff records lost their login account. Recreate it below — the staff code, Lao name, position and salary are restored automatically. Fill the English name and a temporary password; refine the rest later via <b>Edit</b>.</div>

<?= $msg ?>

<?php if (!$orphans): ?>
    <div class="none">✅ No orphaned staff. Total Staff and the Staff List now match.</div>
    <div style="text-align:center"><a class="back" href="staff.php">← Back to Staff</a></div>
<?php else: foreach ($orphans as $o): ?>
    <div class="card">
        <div class="rec">
            Recoverable &nbsp;·&nbsp; <b>Staff ID:</b> <?= htmlspecialchars($o['staff_code'] ?: '—') ?>
            &nbsp;·&nbsp; <b>Lao name:</b> <?= htmlspecialchars($o['full_name_lo'] ?: '—') ?>
            &nbsp;·&nbsp; <b>Position:</b> <?= htmlspecialchars($o['position'] ?: '—') ?>
            &nbsp;·&nbsp; <b>Dept:</b> <?= htmlspecialchars($o['department'] ?: '—') ?>
            <?php if ($o['base_salary']!==null): ?>&nbsp;·&nbsp; <b>Base salary:</b> ₭<?= number_format((float)$o['base_salary']) ?><?php endif; ?>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="repair">
            <input type="hidden" name="user_id" value="<?= (int)$o['user_id'] ?>">
            <div class="row">
                <div>
                    <label>Full name (English) *</label>
                    <input type="text" name="name" value="<?= htmlspecialchars($o['full_name_lo'] ?: ($o['staff_code'] ?: '')) ?>" required>
                </div>
                <div>
                    <label>Username (for login) *</label>
                    <input type="text" name="username" value="<?= htmlspecialchars($o['staff_code'] ?: '') ?>" required>
                </div>
            </div>
            <div class="row">
                <div><label>Email</label><input type="email" name="email" placeholder="optional"></div>
                <div><label>Phone</label><input type="text" name="phone" placeholder="optional"></div>
            </div>
            <div class="row">
                <div>
                    <label>Role</label>
                    <select name="staff_role">
                        <option value="staff">👤 Staff</option>
                        <option value="admin">👑 Company Admin</option>
                    </select>
                </div>
                <div><label>Temporary password *</label><input type="text" name="password" value="seven123" required></div>
            </div>
            <button class="btn" type="submit">♻️ Recover this staff</button>
        </form>
    </div>
<?php endforeach; ?>
    <div style="text-align:center"><a class="back" href="staff.php">← Back to Staff</a></div>
<?php endif; ?>
</div>
</body>
</html>