<?php
/**
 * إنشاء مختبر تجريبي للاختبار - يُشغّل يدوياً
 */
$config = require __DIR__ . '/../config/config.php';
$pdo = new PDO(
    'mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['name'] . ';charset=utf8mb4',
    $config['db']['user'],
    $config['db']['pass'],
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);

$slug = 'testlab';
$labName = 'مختبر تجريبي';
$username = 'testlab_admin';
$password = '123456';

// حذف إن وُجد (للاختبار فقط)
$tid = $pdo->query("SELECT id FROM tenants WHERE slug = '$slug'")->fetchColumn();
if ($tid) {
    $pdo->exec("DELETE FROM branches WHERE tenant_id = $tid");
    $pdo->exec("DELETE FROM users WHERE tenant_id = $tid");
    $pdo->exec("DELETE FROM tenants WHERE id = $tid");
}

$pdo->beginTransaction();
$pdo->exec("INSERT INTO tenants (slug, name, plan_id, status) VALUES ('$slug', '$labName', 1, 'trial')");
$tenantId = (int)$pdo->lastInsertId();

$stmt = $pdo->query("SELECT id FROM roles WHERE name = 'Administrator' LIMIT 1");
$roleRow = $stmt->fetch(PDO::FETCH_ASSOC);
if ($roleRow) {
    $roleId = (int)$roleRow['id'];
} else {
    $pdo->exec("INSERT INTO roles (name) VALUES ('Administrator')");
    $roleId = (int)$pdo->lastInsertId();
}

$hash = password_hash($password, PASSWORD_BCRYPT);
$pdo->prepare("INSERT INTO users (full_name, username, password_hash, role_id, tenant_id, is_active) VALUES (?, ?, ?, ?, ?, 1)")->execute(['مدير التجربة', $username, $hash, $roleId, $tenantId]);
$pdo->prepare("INSERT INTO branches (branch_code, name, tenant_id) VALUES (?, ?, ?)")->execute([strtoupper($slug), $labName, $tenantId]);

$pdo->commit();

echo "تم إنشاء مختبر تجريبي:\n";
echo "- الرابط: index.php?page=login&tenant=$slug\n";
echo "- اسم المستخدم: $username\n";
echo "- كلمة المرور: $password\n";
