<?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 = '';
$successUrl = '';

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'] ?? '';
    $edition     = in_array($_POST['edition'] ?? '', ['full','limited']) ? $_POST['edition'] : 'full';
    $licenseCount = max(1, (int)($_POST['license_count'] ?? 5));

    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
            //    for whichever edition this company was created as.
            $tenantPdo = new PDO(
                "mysql:host=localhost;dbname=" . $dbInfo['db_name'] . ";charset=utf8mb4",
                $dbInfo['db_user'], $dbPassword,
                [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
            );
            $schemaFile = $edition === 'limited'
                ? __DIR__ . '/../database_limited_edition.sql'
                : __DIR__ . '/../database.sql';
            $schemaSql = file_get_contents($schemaFile);
            // 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/license 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]);
            $tenantPdo->prepare("UPDATE settings SET setting_value=? WHERE setting_key='license_count'")
                ->execute([$licenseCount]);

            // 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, edition, license_count, status)
                 VALUES (?,?,?,?,?,?,?,?, 'active')"
            )->execute([$companyName, $companyCode, 'localhost', $dbInfo['db_name'], $dbInfo['db_user'], $dbPassword, $edition, $licenseCount]);
            $tenantId = $pdoMaster->lastInsertId();

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

            $successUrl = $edition === 'limited' ? OTHER_URL_LIMITED : OTHER_URL_FULL;
            $editionLabel = $edition === 'limited' ? 'Limited Edition' : 'Full Edition';
            $success = "Company '{$companyName}' created on the <strong>$editionLabel</strong> (license: $licenseCount users). "
                     . "Admin login: {$adminEmail}<br>Login URL: <a href=\"{$successUrl}/login.php\" target=\"_blank\">{$successUrl}/login.php</a>";
        } 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"><?= $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>

        <div class="form-group">
            <label>Edition</label><br>
            <label style="font-weight:400;margin-right:16px;">
                <input type="radio" name="edition" value="full" <?= ($_POST['edition'] ?? 'full') === 'full' ? 'checked' : '' ?>>
                Full Edition <span class="text-faint">(includes Item Master, Purchase Vendors & Stock modules)</span>
            </label><br>
            <label style="font-weight:400;">
                <input type="radio" name="edition" value="limited" <?= ($_POST['edition'] ?? '') === 'limited' ? 'checked' : '' ?>>
                Limited Edition <span class="text-faint">(no Item Master/Stock — quotation items typed manually)</span>
            </label>
        </div>

        <div class="form-group">
            <label>License Count (max users this company can create)</label>
            <input type="number" name="license_count" min="1" value="<?= htmlspecialchars($_POST['license_count'] ?? '5') ?>" required>
        </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>
