<?php
/**
 * Seed Super Admin Script
 * Run this from CLI: php scripts/seed_super_admin.php
 */

require_once __DIR__ . '/../app/bootstrap/init.php';

use App\Core\Database;
use App\Core\Encryption;

$db = Database::getInstance();

echo "--- Starting Super Admin Seeding ---\n";

try {
    $db->beginTransaction();

    // 1. We must create a "System Tenant" for the Super Admin to satisfy the Foreign Key constraint
    $systemTenantId = '00000000-0000-0000-0000-000000000000';
    
    // Check if system tenant exists
    $stmt = $db->prepare("SELECT id FROM tenants WHERE id = ?");
    $stmt->execute([$systemTenantId]);
    if (!$stmt->fetch()) {
        $stmt = $db->prepare("INSERT INTO tenants (id, name, email, status, created_at) VALUES (?, 'System Administration', 'system@musadaq.com', 'active', NOW())");
        $stmt->execute([$systemTenantId]);
        echo "[OK] System Tenant created.\n";
    }

    // 2. Setup Super Admin details
    $adminEmail = 'admin@musadaq.app';
    $adminName = 'Hamza';
    $adminPassword = env('SEED_ADMIN_PASSWORD', 'password123'); // Default for dev only

    // Check if user already exists
    $emailHash = hash('sha256', strtolower($adminEmail));
    $stmt = $db->prepare("SELECT id FROM users WHERE email_hash = ?");
    $stmt->execute([$emailHash]);
    
    if ($stmt->fetch()) {
        echo "[INFO] Super Admin already exists with this email.\n";
    } else {
        $adminId = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
        );

        $encryptedName = Encryption::encrypt($adminName);
        $encryptedEmail = Encryption::encrypt($adminEmail);
        $passwordHash = password_hash($adminPassword, PASSWORD_DEFAULT);

        $stmt = $db->prepare("INSERT INTO users (id, tenant_id, name, email, email_hash, password_hash, role, is_active, created_at) VALUES (?, ?, ?, ?, ?, ?, 'super_admin', 1, NOW())");
        $stmt->execute([
            $adminId,
            $systemTenantId,
            $encryptedName,
            $encryptedEmail,
            $emailHash,
            $passwordHash
        ]);
        
        echo "[OK] Super Admin created successfully!\n";
        echo "----------------------------------------\n";
        echo "Email: $adminEmail\n";
        echo "Password: [FROM ENV]\n";
        echo "Role: super_admin\n";
        echo "----------------------------------------\n";
    }

    $db->commit();
    echo "--- Seeding Complete ---\n";

} catch (\Exception $e) {
    $db->rollBack();
    echo "[ERROR] Seeding failed: " . $e->getMessage() . "\n";
}
