<?php
/**
 * Self-Onboarding: تسجيل مختبر جديد
 * index.php?page=signup
 */
$config = require __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../src/Core/Database.php';
$db = \App\Core\Database::getInstance($config['db'])->connection();

$error = '';
$success = false;
$planId = (int)($_GET['plan'] ?? 1);

$planIdPost = $planId;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $planIdPost = (int)($_POST['plan_id'] ?? $planId);
    $labName = trim($_POST['lab_name'] ?? '');
    $slug = preg_replace('/[^a-z0-9_-]/', '', strtolower(trim($_POST['slug'] ?? '')));
    $adminName = trim($_POST['admin_name'] ?? '');
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');

    if (strlen($labName) < 2) {
        $error = 'أدخل اسم المختبر.';
    } elseif (strlen($slug) < 2) {
        $error = 'الرابط (slug) قصير جداً. مثال: mylab';
    } elseif (strlen($adminName) < 2) {
        $error = 'أدخل اسم المدير.';
    } elseif (strlen($username) < 3) {
        $error = 'اسم المستخدم 3 أحرف على الأقل.';
    } elseif (strlen($password) < 6) {
        $error = 'كلمة المرور 6 أحرف على الأقل.';
    } else {
        try {
            $db->query('SELECT id FROM tenants LIMIT 1');
            $db->query('SELECT id FROM subscription_plans LIMIT 1');
        } catch (Throwable $e) {
            $error = 'النظام غير مهيأ للتسجيل. راجع مدير النظام.';
        }

        if (!$error) {
            try {
                $db->beginTransaction();

                $stmt = $db->prepare('SELECT id FROM tenants WHERE slug = ?');
                $stmt->execute([$slug]);
                if ($stmt->fetch()) {
                    $error = 'هذا الرابط مستخدم. اختر آخر.';
                    $db->rollBack();
                } else {
                    $stmt = $db->prepare('SELECT id FROM users WHERE username = ?');
                    $stmt->execute([$username]);
                    if ($stmt->fetch()) {
                        $error = 'اسم المستخدم مستخدم. استخدم اسماً مختلفاً (مثل: admin_lab أو مدير_المختبر)';
                        $db->rollBack();
                    } else {
                        $stmt = $db->prepare('INSERT INTO tenants (slug, name, plan_id, status) VALUES (?, ?, ?, ?)');
                        $stmt->execute([$slug, $labName, $planIdPost > 0 ? $planIdPost : 1, 'trial']);
                        $tenantId = (int)$db->lastInsertId();

                        $stmt = $db->prepare('SELECT id FROM roles WHERE name = ? LIMIT 1');
                        $stmt->execute(['Administrator']);
                        $role = $stmt->fetch();
                        $roleId = $role ? (int)$role['id'] : 1;
                        if (!$role) {
                            $db->prepare('INSERT INTO roles (name) VALUES (?)')->execute(['Administrator']);
                            $roleId = (int)$db->lastInsertId();
                        }

                        $hash = password_hash($password, PASSWORD_BCRYPT);
                        $adminUserId = 0;
                        try {
                            $db->prepare('INSERT INTO users (full_name, email, phone, username, password_hash, role_id, tenant_id, is_active) VALUES (?, ?, ?, ?, ?, ?, ?, 1)')->execute([
                                $adminName, $email ?: null, $phone ?: null, $username, $hash, $roleId, $tenantId
                            ]);
                            $adminUserId = (int)$db->lastInsertId();
                        } catch (Throwable $e3) {
                            try {
                                $db->prepare('INSERT INTO users (full_name, username, password_hash, role_id, tenant_id, is_active) VALUES (?, ?, ?, ?, ?, 1)')->execute([
                                    $adminName, $username, $hash, $roleId, $tenantId
                                ]);
                                $adminUserId = (int)$db->lastInsertId();
                            } catch (Throwable $e4) {
                                $db->prepare('INSERT INTO users (full_name, username, password_hash, role_id, is_active) VALUES (?, ?, ?, ?, 1)')->execute([
                                    $adminName, $username, $hash, $roleId
                                ]);
                                $adminUserId = (int)$db->lastInsertId();
                            }
                        }
                        if ($adminUserId <= 0) {
                            $stmt = $db->prepare('SELECT id FROM users WHERE tenant_id = ? AND username = ? LIMIT 1');
                            $stmt->execute([$tenantId, $username]);
                            $au = $stmt->fetch();
                            if ($au) $adminUserId = (int)$au['id'];
                        }

                        $db->prepare('INSERT INTO branches (branch_code, name, tenant_id) VALUES (?, ?, ?)')->execute([strtoupper($slug), $labName, $tenantId]);

                        try {
                            $db->prepare('INSERT INTO lab_signup_requests (tenant_id, admin_user_id, lab_name, slug, admin_name, admin_email, admin_phone, username, plan_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)')->execute([
                                $tenantId, $adminUserId > 0 ? $adminUserId : null, $labName, $slug, $adminName, $email ?: null, $phone ?: null, $username, $planIdPost > 0 ? $planIdPost : 1
                            ]);
                        } catch (Throwable $eSig) {
                            if ($adminUserId <= 0) {
                                $stmt = $db->prepare('SELECT id FROM users WHERE tenant_id = ? ORDER BY id DESC LIMIT 1');
                                $stmt->execute([$tenantId]);
                                $au = $stmt->fetch();
                                $adminUserId = $au ? (int)$au['id'] : 0;
                            }
                            try {
                                $db->prepare('INSERT INTO lab_signup_requests (tenant_id, admin_user_id, lab_name, slug, admin_name, admin_email, admin_phone, username, plan_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)')->execute([
                                    $tenantId, $adminUserId > 0 ? $adminUserId : null, $labName, $slug, $adminName, $email ?: null, $phone ?: null, $username, $planIdPost > 0 ? $planIdPost : 1
                                ]);
                            } catch (Throwable $e2) {}
                        }

                        $db->commit();
                        $success = true;
                    }
                }
            } catch (Throwable $e) {
                if ($db->inTransaction()) $db->rollBack();
                $errMsg = $e->getMessage();
                if (strpos($errMsg, 'Duplicate entry') !== false && strpos($errMsg, 'username') !== false) {
                    $error = 'اسم المستخدم مستخدم. اختر اسماً فريداً (مثل: admin_mylab)';
                } elseif (strpos($errMsg, 'Duplicate entry') !== false && strpos($errMsg, 'branch_code') !== false) {
                    $error = 'الرابط (slug) مستخدم. اختر رابطاً آخر.';
                } else {
                    $error = 'حدث خطأ: ' . $errMsg;
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='12' fill='%230f766e'/%3E%3Ctext x='50%25' y='50%25' font-family='Arial' font-size='28' font-weight='bold' fill='white' text-anchor='middle' dominant-baseline='central'%3ESL%3C/text%3E%3C/svg%3E">
    <title>تسجيل مختبر جديد</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body class="login-page">
    <div class="login-container" style="max-width:420px;">
        <h1>تسجيل مختبر جديد</h1>
        <?php
        $selectedPlanName = '';
        if ($planId > 0) {
            try {
                $sp = $db->prepare('SELECT name FROM subscription_plans WHERE id = ?');
                $sp->execute([$planId]);
                $pr = $sp->fetch();
                if ($pr) $selectedPlanName = $pr['name'] ?? '';
            } catch (Throwable $e) {}
        }
        if ($selectedPlanName && !$success): ?>
        <p style="margin-bottom:16px;padding:10px 14px;background:var(--bg-secondary);border-radius:8px;color:var(--text-muted);"><strong>الخطة المختارة:</strong> <?php echo htmlspecialchars($selectedPlanName, ENT_QUOTES, 'UTF-8'); ?></p>
        <?php endif; ?>
        <?php if ($success):
                $needPayment = false;
                $paymentPlanName = '';
                $paymentAmount = 0;
                try {
                    $sp = $db->prepare('SELECT id, name, price_monthly FROM subscription_plans WHERE id = ?');
                    $sp->execute([$planIdPost ?? $planId]);
                    $planRow = $sp->fetch();
                    if ($planRow && (float)($planRow['price_monthly'] ?? 0) > 0) {
                        $needPayment = true;
                        $paymentPlanName = $planRow['name'] ?? '';
                        $paymentAmount = (float)$planRow['price_monthly'];
                    }
                } catch (Throwable $e) {}
            ?>
            <div class="alert alert-success">
                تم التسجيل بنجاح.
                <?php if ($needPayment): ?>
                <p style="margin:12px 0;">خطة <strong><?php echo htmlspecialchars($paymentPlanName, ENT_QUOTES, 'UTF-8'); ?></strong> — المبلغ: <strong><?php echo number_format($paymentAmount, 2); ?> د.ع/شهر</strong></p>
                <p><a href="index.php?page=subscribe_pay&tenant=<?php echo urlencode($slug ?? ''); ?>&plan=<?php echo (int)($planIdPost ?? $planId); ?>" class="btn-primary" style="display:inline-block;padding:12px 24px;margin-top:8px;">💳 إتمام الدفع بالبطاقة</a></p>
                <p style="margin-top:12px;font-size:0.9rem;"><a href="index.php?page=login&tenant=<?php echo htmlspecialchars($slug ?? '', ENT_QUOTES, 'UTF-8'); ?>">سجّل دخولك الآن</a> — يمكنك الدفع لاحقاً من الإعدادات.</p>
                <?php else: ?>
                <p><a href="index.php?page=login&tenant=<?php echo htmlspecialchars($slug ?? '', ENT_QUOTES, 'UTF-8'); ?>">سجّل دخولك</a> (أو ادخل عبر subdomain: <?php echo htmlspecialchars($slug ?? '', ENT_QUOTES, 'UTF-8'); ?>.yourdomain.com)</p>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <?php if ($error): ?><div class="alert alert-danger"><?php echo htmlspecialchars($error, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
            <form method="post">
                <input type="hidden" name="plan_id" value="<?php echo (int)$planId; ?>">
                <div class="form-group">
                    <label>اسم المختبر</label>
                    <input type="text" name="lab_name" required value="<?php echo htmlspecialchars($_POST['lab_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                </div>
                <div class="form-group">
                    <label>رابط المختبر (slug)</label>
                    <input type="text" name="slug" required pattern="[a-z0-9_-]+" placeholder="mylab" value="<?php echo htmlspecialchars($_POST['slug'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                    <small>سيصبح: mylab.yoursystem.com</small>
                </div>
                <div class="form-group">
                    <label>اسم المدير</label>
                    <input type="text" name="admin_name" required value="<?php echo htmlspecialchars($_POST['admin_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                </div>
                <div class="form-group">
                    <label>البريد الإلكتروني</label>
                    <input type="email" name="email" placeholder="admin@example.com" value="<?php echo htmlspecialchars($_POST['email'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                </div>
                <div class="form-group">
                    <label>رقم الهاتف</label>
                    <input type="tel" name="phone" placeholder="05xxxxxxxx" value="<?php echo htmlspecialchars($_POST['phone'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                </div>
                <div class="form-group">
                    <label>اسم المستخدم</label>
                    <input type="text" name="username" required value="<?php echo htmlspecialchars($_POST['username'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="admin_mylab">
                    <small style="color:var(--text-muted);">يجب أن يكون فريداً (لا يُسمح بتكراره مع أي مختبر آخر)</small>
                </div>
                <div class="form-group">
                    <label>كلمة المرور</label>
                    <input type="password" name="password" required minlength="6">
                </div>
                <button type="submit">تسجيل</button>
            </form>
            <p style="margin-top:20px;">
            <a href="index.php?page=login">لديك حساب؟ دخول</a>
            <span style="margin:0 12px;">|</span>
            <a href="index.php?page=purchase">عرض الخطط</a>
        </p>
        <?php endif; ?>
    </div>
</body>
</html>
