<?php
require_once __DIR__ . '/../config/master_database.php';
require_once __DIR__ . '/../includes/CpanelProvisioner.php';
require_once __DIR__ . '/../includes/license_helpers.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));
    $licenseDuration = in_array($_POST['license_duration'] ?? '', ['1y','2y','3y','lifetime','custom']) ? $_POST['license_duration'] : 'lifetime';
    $licenseExpiry = calculateLicenseExpiry($licenseDuration, $_POST['license_custom_date'] ?? null);

    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 ($licenseDuration === 'custom' && !$licenseExpiry) $errors[] = 'Pick a valid custom expiry date.';

    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)) {
        $provisioner = new CpanelProvisioner();
        $dbInfo = null;
        try {
            // 1) Provision a brand-new database + db user via cPanel
            $dbPassword = bin2hex(random_bytes(12));
            $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);
            // Strip whole-line "-- comment" lines BEFORE splitting on ';' - if a
            // comment line ever contains a semicolon (e.g. "Nos; Box; Kg"), a naive
            // split on ';' alone would cut a CREATE TABLE statement in half.
            $cleanLines = array_filter(
                explode("\n", $schemaSql),
                function ($line) { return strpos(trim($line), '--') !== 0; }
            );
            $schemaSql = implode("\n", $cleanLines);
            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, license_expiry, status)
                 VALUES (?,?,?,?,?,?,?,?,?, 'active')"
            )->execute([$companyName, $companyCode, 'localhost', $dbInfo['db_name'], $dbInfo['db_user'], $dbPassword, $edition, $licenseCount, $licenseExpiry]);
            $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';
            $expiryLabel = licenseExpiryLabel($licenseExpiry);
            $success = "Company '{$companyName}' created on the <strong>$editionLabel</strong> (license: $licenseCount users, expiry: $expiryLabel). "
                     . "Admin login: {$adminEmail}<br>Login URL: <a href=\"{$successUrl}/login.php\" target=\"_blank\">{$successUrl}/login.php</a>";
        } catch (Exception $e) {
            // Roll back the database/user we just created (if we got that far)
            // so a retry with the same company code doesn't hit "already exists".
            $provisioner->dropDatabase('sx_' . strtolower($companyCode));

            $msg = $e->getMessage();
            if (stripos($msg, 'already exists') !== false) {
                $errors[] = "That company code was used in an earlier attempt that didn't finish (its database has now been cleaned up). Please submit the form again.";
            } else {
                $errors[] = 'Setup failed: ' . $msg;
            }
        }
    }
}
?>
<!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>

        <div class="form-group">
            <label>License Duration</label><br>
            <?php $selDur = $_POST['license_duration'] ?? 'lifetime'; ?>
            <select name="license_duration" id="license_duration" onchange="document.getElementById('custom_date_row').style.display = this.value==='custom' ? 'block' : 'none';">
                <option value="1y" <?= $selDur==='1y'?'selected':'' ?>>1 Year</option>
                <option value="2y" <?= $selDur==='2y'?'selected':'' ?>>2 Years</option>
                <option value="3y" <?= $selDur==='3y'?'selected':'' ?>>3 Years</option>
                <option value="lifetime" <?= $selDur==='lifetime'?'selected':'' ?>>Lifetime (no expiry)</option>
                <option value="custom" <?= $selDur==='custom'?'selected':'' ?>>Custom date</option>
            </select>
            <div id="custom_date_row" style="margin-top:8px;display:<?= $selDur==='custom'?'block':'none' ?>;">
                <input type="date" name="license_custom_date" value="<?= htmlspecialchars($_POST['license_custom_date'] ?? '') ?>">
            </div>
        </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>