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

$id = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
$stmt = $pdoMaster->prepare("SELECT * FROM tenants WHERE id = ?");
$stmt->execute([$id]);
$company = $stmt->fetch();
if (!$company) { header('Location: dashboard.php'); exit; }

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $licenseCount = max(1, (int)($_POST['license_count'] ?? 5));
    $newEdition   = in_array($_POST['edition'] ?? '', ['full','limited']) ? $_POST['edition'] : $company['edition'];
    $editionChanged = $newEdition !== $company['edition'];

    if ($editionChanged) {
        // Changing edition does NOT move/re-import their database or data - it only
        // changes which URL they're expected to log in at. Only allow this if you
        // understand their existing data was created for the other edition's schema.
        $errors[] = 'Changing edition after creation is not supported here (their database schema was built for the original edition). Create a new company on the correct edition instead, or contact a developer to migrate their data.';
    }

    if (empty($errors)) {
        try {
            // Update master DB
            $pdoMaster->prepare("UPDATE tenants SET license_count = ? WHERE id = ?")->execute([$licenseCount, $id]);

            // Push the same number into the tenant's own database so their app
            // pages (which never touch the master DB) see the updated limit.
            $tenantPdo = new PDO(
                "mysql:host=" . $company['db_host'] . ";dbname=" . $company['db_name'] . ";charset=utf8mb4",
                $company['db_user'], $company['db_pass'],
                [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
            );
            $tenantPdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = 'license_count'")
                ->execute([$licenseCount]);
            // In case an older tenant DB predates the license_count setting row
            $tenantPdo->prepare("INSERT IGNORE INTO settings (setting_key, setting_value) VALUES ('license_count', ?)")
                ->execute([$licenseCount]);

            $success = "License updated to $licenseCount users.";
            $company['license_count'] = $licenseCount;
        } catch (Exception $e) {
            $errors[] = 'Could not update: ' . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit Company - <?= htmlspecialchars($company['company_name']) ?></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);"><?= htmlspecialchars($company['company_name']) ?></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">
        <input type="hidden" name="id" value="<?= $company['id'] ?>">
        <div class="form-group">
            <label>Edition</label><br>
            <span class="badge <?= $company['edition'] === 'limited' ? 'badge-info' : 'badge-success' ?>">
                <?= $company['edition'] === 'limited' ? 'Limited Edition' : 'Full Edition' ?>
            </span>
            <input type="hidden" name="edition" value="<?= $company['edition'] ?>">
        </div>
        <div class="form-group">
            <label>License Count (max users this company can create)</label>
            <input type="number" name="license_count" min="1" value="<?= (int)$company['license_count'] ?>" required>
        </div>
        <button type="submit" class="btn btn-primary">Save</button>
    </form>
</body>
</html>
