<?php
require_once __DIR__ . '/../config/master_database.php';
require_once __DIR__ . '/../includes/CpanelProvisioner.php';
session_start();
if (empty($_SESSION['super_admin_id'])) { header('Location: login.php'); exit; }

$errors = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $companyName = trim($_POST['company_name'] ?? '');
    $companyCode = trim($_POST['company_code'] ?? '');
    $adminName   = trim($_POST['admin_name'] ?? '');
    $adminEmail  = trim($_POST['admin_email'] ?? '');
    $adminPass   = $_POST['admin_password'] ?? '';

    if (!$companyName) $errors[] = 'Company name is required.';
    if (!$companyCode || !preg_match('/^[a-zA-Z0-9]{3,20}$/', $companyCode)) $errors[] = 'Company code must be 3-20 letters/numbers, no spaces.';
    if (!$adminName) $errors[] = 'Admin name is required.';
    if (!filter_var($adminEmail, FILTER_VALIDATE_EMAIL)) $errors[] = 'Valid admin email is required.';
    if (strlen($adminPass) < 6) $errors[] = 'Admin password must be at least 6 characters.';

    if (empty($errors)) {
        // company_code must be unique
        $chk = $pdoMaster->prepare("SELECT id FROM tenants WHERE company_code = ?");
        $chk->execute([$companyCode]);
        if ($chk->fetch()) $errors[] = 'That company code is already used. Pick another.';

        $chk2 = $pdoMaster->prepare("SELECT id FROM tenant_user_index WHERE email = ?");
        $chk2->execute([$adminEmail]);
        if ($chk2->fetch()) $errors[] = 'That admin email is already registered to a company.';
    }

    if (empty($errors)) {
        try {
            // 1) Provision a brand-new database + db user via cPanel
            $dbPassword = bin2hex(random_bytes(12));
            $provisioner = new CpanelProvisioner();
            $dbInfo = $provisioner->provisionDatabase('sx_' . strtolower($companyCode), $dbPassword);

            // 2) Connect to the new (empty) database and import the app schema
            $tenantPdo = new PDO(
                "mysql:host=localhost;dbname=" . $dbInfo['db_name'] . ";charset=utf8mb4",
                $dbInfo['db_user'], $dbPassword,
                [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
            );
            $schemaSql = file_get_contents(__DIR__ . '/../database.sql');
            // strip the CREATE DATABASE / USE lines - we already created & connected to the DB
            $schemaSql = preg_replace('/CREATE DATABASE.*?;/is', '', $schemaSql);
            $schemaSql = preg_replace('/USE\s+\w+\s*;/is', '', $schemaSql);
            // strip the template's default admin seed user - we create the real admin below instead
            $schemaSql = preg_replace('/INSERT INTO users.*?;/is', '', $schemaSql);
            foreach (array_filter(array_map('trim', explode(';', $schemaSql))) as $stmt) {
                $tenantPdo->exec($stmt);
            }

            // 3) Create the company's first Admin user inside their new database
            $hash = password_hash($adminPass, PASSWORD_DEFAULT);
            $tenantPdo->prepare("INSERT INTO users (name, email, password, role, status) VALUES (?,?,?,'admin',1)")
                ->execute([$adminName, $adminEmail, $hash]);

            // Seed their settings with the real company name/email instead of the generic placeholder
            $tenantPdo->prepare("UPDATE settings SET setting_value=? WHERE setting_key='company_name'")
                ->execute([$companyName]);
            $tenantPdo->prepare("UPDATE settings SET setting_value=? WHERE setting_key='company_email'")
                ->execute([$adminEmail]);

            // 4) Register the tenant + login index in the master DB
            $pdoMaster->prepare(
                "INSERT INTO tenants (company_name, company_code, db_host, db_name, db_user, db_pass, status)
                 VALUES (?,?,?,?,?,?, 'active')"
            )->execute([$companyName, $companyCode, 'localhost', $dbInfo['db_name'], $dbInfo['db_user'], $dbPassword]);
            $tenantId = $pdoMaster->lastInsertId();

            $pdoMaster->prepare("INSERT INTO tenant_user_index (email, tenant_id) VALUES (?, ?)")
                ->execute([$adminEmail, $tenantId]);

            $success = "Company '{$companyName}' created. Admin login: {$adminEmail}";
        } catch (Exception $e) {
            $errors[] = 'Setup failed: ' . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Company - Super Admin</title>
<link href="https://fonts.googleapis.com/css2?family=Fraunces:wght@600;700&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="../assets/css/style.css?v=5">
</head>
<body style="padding:40px;max-width:600px;margin:0 auto;">
    <h2 style="font-family:var(--font-display);">Create New Company</h2>
    <p><a href="dashboard.php">&larr; Back to companies list</a></p>

    <?php foreach ($errors as $e): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($e) ?></div>
    <?php endforeach; ?>
    <?php if ($success): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <form method="POST">
        <div class="form-group">
            <label>Company Name</label>
            <input type="text" name="company_name" required value="<?= htmlspecialchars($_POST['company_name'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Company Code (short, no spaces, e.g. ABCCORP)</label>
            <input type="text" name="company_code" required value="<?= htmlspecialchars($_POST['company_code'] ?? '') ?>">
        </div>
        <hr>
        <p><strong>First Admin Login for this company:</strong></p>
        <div class="form-group">
            <label>Admin Name</label>
            <input type="text" name="admin_name" required value="<?= htmlspecialchars($_POST['admin_name'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Admin Email</label>
            <input type="email" name="admin_email" required value="<?= htmlspecialchars($_POST['admin_email'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Admin Password</label>
            <input type="text" name="admin_password" required>
        </div>
        <button type="submit" class="btn btn-primary">Create Company</button>
    </form>
</body>
</html>
