<?php
/* ============================================================================
 *  admin/backfill_staff_wallets.php — run once.
 *  Creates a customer wallet (customers row) for every company staff member
 *  who doesn't have one yet, so they can use the wallet + HR dashboard.
 *  Open: /seven-credit-system/admin/backfill_staff_wallets.php
 * ==========================================================================*/
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
require_once '../config/database.php';
require_once '../config/pay_id.php';

if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'admin') {
    http_response_code(403);
    die('Admin only. Please log in as an administrator.');
}
header('Content-Type: text/plain; charset=utf-8');

try {
    /* staff (and company admins) who have no customers wallet */
    $rows = $pdo->query("
        SELECT DISTINCT cs.user_id, cs.company_id, u.name, u.phone, u.email
        FROM company_staff cs
        JOIN users u ON u.id = cs.user_id
        LEFT JOIN customers c ON c.user_id = cs.user_id
        WHERE c.id IS NULL
    ")->fetchAll(PDO::FETCH_ASSOC);

    if (!$rows) { echo "Every staff member already has a wallet. Nothing to do.\n"; exit; }

    /* phone/email left NULL on the wallet — customers.phone is UNIQUE and the
       real phone lives on the users row, so we avoid duplicate-phone clashes. */
    $ins = $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())");
    $made = 0;
    foreach ($rows as $r) {
        $uid  = (int)$r['user_id'];
        $code = "ST" . str_pad((string)$uid, 6, "0", STR_PAD_LEFT);
        $payId = generate_unique_pay_id($pdo);
        try {
            $ins->execute([$uid, $code, $payId, $r['name']]);
            $made++;
            echo "Wallet created for: {$r['name']} (user {$uid}) — code {$code}, Pay ID {$payId}\n";
        } catch (Throwable $e) {
            echo "SKIP {$r['name']} (user {$uid}): {$e->getMessage()}\n";
        }
    }
    echo "\nDone. Wallets created: {$made}\n";
} catch (Throwable $e) {
    echo "Error: " . $e->getMessage() . "\n";
}