<?php
// Run from the command line:
//   php scripts/create_admin.php
// Creates/resets the Admin login (login_id 'admin', password 'Admin@123#')
// and, if requested, creates every missing CLRC login (password 'admin123').
require_once __DIR__ . '/../config/config.php';

$pdo = getPDO();

// ---- Admin ----
$adminHash = password_hash('Admin@123#', PASSWORD_DEFAULT);
$stmt = $pdo->prepare(
    'INSERT INTO users (login_id, password_hash, role, display_name, active, must_change_password)
     VALUES (?, ?, ?, ?, 1, 1)
     ON DUPLICATE KEY UPDATE password_hash = VALUES(password_hash), must_change_password = 1, active = 1'
);
$stmt->execute(['admin', $adminHash, 'admin', 'District Admin']);
echo "Admin ready — login as 'admin', password 'Admin@123#' (must be changed on first login).\n";

// ---- CLRC logins (one per row in clrc, skipping any that already exist) ----
$clrcHash = password_hash('admin123', PASSWORD_DEFAULT);
$clrcs = $pdo->query('SELECT clrccode, clrcname FROM clrc')->fetchAll();
$created = 0;
foreach ($clrcs as $c) {
    $exists = $pdo->prepare('SELECT 1 FROM users WHERE login_id = ?');
    $exists->execute([$c['clrccode']]);
    if ($exists->fetch()) continue;

    $ins = $pdo->prepare(
        'INSERT INTO users (login_id, password_hash, role, clrccode, display_name, active, must_change_password)
         VALUES (?, ?, ?, ?, ?, 1, 1)'
    );
    $ins->execute([$c['clrccode'], $clrcHash, 'clrc', $c['clrccode'], $c['clrcname']]);
    $created++;
}
echo "Created $created new CLRC login(s) with default password 'admin123'.\n";
