<?php
require_once __DIR__ . '/../config/master_database.php';
require_once __DIR__ . '/../includes/license_helpers.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'];

    $licenseDuration = $_POST['license_duration'] ?? 'keep';
    if ($licenseDuration === 'keep') {
        $licenseExpiry = $company['license_expiry'];
    } else {
        // Recalculates from TODAY (a fresh renewal), not stacked on the old expiry.
        $licenseExpiry = calculateLicenseExpiry($licenseDuration, $_POST['license_custom_date'] ?? null);
    }

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

    if (empty($errors)) {
        try {
            // Update master DB
            $pdoMaster->prepare("UPDATE tenants SET license_count = ?, license_expiry = ? WHERE id = ?")
                ->execute([$licenseCount, $licenseExpiry, $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: $licenseCount users, expiry " . licenseExpiryLabel($licenseExpiry) . '.';
            $company['license_count'] = $licenseCount;
            $company['license_expiry'] = $licenseExpiry;
        } 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>
        <div class="form-group">
            <label>Current License Expiry</label><br>
            <span class="badge <?= (!$company['license_expiry'] || strtotime($company['license_expiry']) >= strtotime('today')) ? 'badge-success' : 'badge-danger' ?>">
                <?= htmlspecialchars(licenseExpiryLabel($company['license_expiry'])) ?>
            </span>
        </div>
        <div class="form-group">
            <label>Renew / Change Duration</label><br>
            <select name="license_duration" id="license_duration" onchange="document.getElementById('custom_date_row').style.display = this.value==='custom' ? 'block' : 'none';">
                <option value="keep">Don't change</option>
                <option value="1y">Renew for 1 Year (from today)</option>
                <option value="2y">Renew for 2 Years (from today)</option>
                <option value="3y">Renew for 3 Years (from today)</option>
                <option value="lifetime">Make Lifetime (no expiry)</option>
                <option value="custom">Custom date</option>
            </select>
            <div id="custom_date_row" style="margin-top:8px;display:none;">
                <input type="date" name="license_custom_date">
            </div>
        </div>
        <button type="submit" class="btn btn-primary">Save</button>
    </form>
</body>
</html>