<?php
/**
 * Create Test Account for App Reviewers
 */

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

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

try {
    $db = Database::getInstance();
    $db->beginTransaction();

    // 1. Generate UUIDs
    $tenantId = 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)
    );

    $userId = 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)
    );

    // 2. Test Account Data
    $tenantName = "مكتب المراجعة التجريبي";
    $tenantEmail = "reviewer@musadaq.jo";
    
    $userName = "App Reviewer";
    $userEmail = "reviewer@musadaq.jo";
    $userPassword = "Reviewer2026!";

    // 3. Encrypt data
    $encryptedTenantName = Encryption::encrypt($tenantName);
    $encryptedTenantEmail = Encryption::encrypt($tenantEmail);
    
    $encryptedUserName = Encryption::encrypt($userName);
    $encryptedUserEmail = Encryption::encrypt($userEmail);
    $emailHash = hash('sha256', strtolower($userEmail));
    $passwordHash = password_hash($userPassword, PASSWORD_DEFAULT);

    // 4. Delete existing if any (prevent duplicates on re-run)
    $stmt = $db->prepare("DELETE FROM users WHERE email_hash = ?");
    $stmt->execute([$emailHash]);

    // 5. Insert Tenant
    $stmt = $db->prepare("INSERT INTO tenants (id, name, email, status, created_at) VALUES (?, ?, ?, 'active', NOW())");
    $stmt->execute([
        $tenantId,
        $encryptedTenantName,
        $encryptedTenantEmail
    ]);

    // 6. Insert User (Manager)
    $stmtUser = $db->prepare("INSERT INTO users (id, tenant_id, name, email, email_hash, password_hash, role, created_at) VALUES (?, ?, ?, ?, ?, ?, 'admin', NOW())");
    $stmtUser->execute([
        $userId,
        $tenantId,
        $encryptedUserName,
        $encryptedUserEmail,
        $emailHash,
        $passwordHash
    ]);

    $db->commit();
    echo "<h3 style='color:green'>✅ تم إنشاء الحساب التجريبي بنجاح!</h3>";
    echo "<p><b>البريد الإلكتروني:</b> $userEmail</p>";
    echo "<p><b>كلمة المرور:</b> $userPassword</p>";
    
    // Delete this file for security
    @unlink(__FILE__);

} catch (\Exception $e) {
    $db->rollBack();
    echo "<h3 style='color:red'>❌ Error: " . htmlspecialchars($e->getMessage()) . "</h3>";
}
