<?php
/* ============================================================================
 *  setup_pay_id.php  —  ONE-TIME migration (admin only).
 *  Open it once in the browser while logged in as admin:
 *      https://7d-lao.com/seven-credit-system/admin/setup_pay_id.php
 *
 *  It (1) adds the `pay_id` column to `customers` if missing, and
 *      (2) gives every existing customer a unique 7-digit Pay ID.
 *  Safe to run more than once — it only fills in customers that don't have one.
 * ==========================================================================*/

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 {
    /* 1) add the column if it isn't there yet */
    $hasCol = $pdo->query("SHOW COLUMNS FROM customers LIKE 'pay_id'")->fetch();
    if (!$hasCol) {
        $pdo->exec("ALTER TABLE customers ADD COLUMN pay_id VARCHAR(12) NULL");
        try {
            $pdo->exec("ALTER TABLE customers ADD UNIQUE KEY uniq_pay_id (pay_id)");
        } catch (Throwable $e) {
            echo "Note: could not add unique index (" . $e->getMessage() . ")\n";
        }
        echo "Added pay_id column.\n";
    } else {
        echo "pay_id column already exists.\n";
    }

    /* Optional: re-issue ALL Pay IDs in the new short format.
       Run with ?reissue=1 to convert existing (e.g. 7-digit) codes to 4-digit. */
    if (isset($_GET['reissue']) && $_GET['reissue'] === '1') {
        $pdo->exec("UPDATE customers SET pay_id = NULL");
        echo "Cleared all Pay IDs for re-issue (new short format).\n";
    }

    /* 2) (re)fill every customer that doesn't have a Pay ID */
    $ids = $pdo->query("SELECT id FROM customers WHERE pay_id IS NULL OR pay_id = ''")
               ->fetchAll(PDO::FETCH_COLUMN);

    $done = 0;
    foreach ($ids as $cid) {
        $pid = generate_unique_pay_id($pdo);
        $up  = $pdo->prepare("UPDATE customers SET pay_id = ? WHERE id = ?");
        $up->execute([$pid, (int) $cid]);
        $done++;
    }

    echo "Assigned a Pay ID to $done customer(s).\n";
    echo "Done. You can now use the Pay ID everywhere.\n";
} catch (Throwable $e) {
    echo "Error: " . $e->getMessage() . "\n";
}