<?php include ADMIN_PATH . '/templates/header.php'; ?>

<div class="content-wrapper">
<section class="content pt-3">

<?php
$cronLastRun = $basicSettings['cron_last_run'] ?? null;
$languages = [];
$langDir = ROOT_PATH . '/lang/';
if (is_dir($langDir)) {
    foreach (glob($langDir . '*.json') as $file) {
        $code = basename($file, '.json');
        $data = json_decode(file_get_contents($file), true) ?: [];
        $languages[$code] = $data['language.name'] ?? strtoupper($code);
    }
}

$countries = [
    "Afghanistan","Albania","Algeria","Andorra","Angola","Argentina","Australia",
    "Austria","Bahrain","Bangladesh","Belgium","Brazil","Canada","China","Egypt",
    "France","Germany","India","Indonesia","Italy","Japan","Jordan","Kuwait",
    "Lebanon","Malaysia","Morocco","Netherlands","Qatar","Saudi Arabia","Spain",
    "Sweden","Switzerland","Tunisia","Turkey","UAE","UK","USA"
];


$isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
           || (!empty($_SERVER['SERVER_PORT']) && (int)$_SERVER['SERVER_PORT'] === 443);
$scheme = $isHttps ? 'https' : 'http';
$host   = $_SERVER['HTTP_HOST'] ?? '';
$baseUrl = $host ? rtrim($scheme . '://' . $host, '/') : '';
$sitemapUrl = $baseUrl ? ($baseUrl . '/sitemap.xml') : '';
$robotsUrl  = $baseUrl ? ($baseUrl . '/robots.txt') : '';
$defaultRobotsText = __('settings.robots_default', "User-agent: *\nAllow: /\n\nDisallow: /admin/\nDisallow: /api/\nDisallow: /uploads/tmp/\nDisallow: /cron/\n\nSitemap: {BASE_URL}/sitemap.xml");
$robotsEditorValue = trim((string)($basicSettings['robots_txt_content'] ?? ''));
if ($robotsEditorValue === '') {
    $robotsEditorValue = $defaultRobotsText;
}
?>

<style>
.settings-card { border-radius: 14px; }
.highlight {
    background: rgba(13,110,253,.05);
    border: 1px solid rgba(13,110,253,.25);
    padding: 16px;
    border-radius: 12px;
}
.form-group-box {
    background: #f8fafc;
    border-radius: 14px;
    padding: 18px;
}
.input-group-text {
    background: transparent;
    border-inline-end: 0;
}
.form-control,
.form-select {
    border-inline-start: 0;
}
.save-bar {
    position: sticky;
    bottom: 0;
    z-index: 1050;
    background: #fff;
    border-top: 1px solid rgba(0,0,0,.1);
    padding: 14px 24px;
}
.smtp-fields { display: none; }
</style>

<div class="container-fluid py-4">

    <h3 class="mb-4">
        <i class="bi bi-gear-fill me-2"></i>
        <?= __('sidebar.basic_settings','Basic Settings') ?>
    </h3>

    <?php if (isset($_GET['saved'])): ?>
        <div class="alert alert-success">
            <?= __('ui.success','Settings saved successfully!') ?>
        </div>
    <?php endif; ?>

    <?php if (isset($_GET['mail_test'])): ?>
        <?php if ($_GET['mail_test'] === 'success'): ?>
            <div class="alert alert-success">
                <?= __('settings.mail_test_success','Test email sent successfully.') ?>
            </div>
        <?php else: ?>
            <div class="alert alert-danger">
                <?= __('settings.mail_test_error','Test email failed. Please check your mail settings.') ?>
            </div>
        <?php endif; ?>
    <?php endif; ?>

    <ul class="nav nav-tabs mb-4">
        <li class="nav-item">
            <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab-site">
                <i class="bi bi-globe me-1"></i>
                <?= __('settings.site_information','Site') ?>
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-local">
                <i class="bi bi-geo-alt me-1"></i>
                <?= __('settings.localization','Localization') ?>
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-contact">
                <i class="bi bi-telephone me-1"></i>
                <?= __('settings.contact','Contact') ?>
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-social">
                <i class="bi bi-share me-1"></i>
                <?= __('settings.social_links','Social') ?>
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-advanced">
                <i class="bi bi-sliders me-1"></i>
                <?= __('settings.other','Advanced') ?>
            </button>
        </li>
    </ul>

    <form method="POST" action="/admin/settings/save" novalidate>
        <?= \Core\System\Csrf::field(); ?>
        <input type="hidden" name="_mail_test" value="0">

        <div class="tab-content">

            <!-- SITE -->
            <div class="tab-pane fade show active" id="tab-site">
                <div class="form-group-box mb-4">
                    <div class="row g-4">

                        <div class="col-lg-6">
                            <div class="highlight">
                                <label class="form-label"><?= __('settings.site_name','Site Name') ?></label>
                                <input required type="text" name="site_name" class="form-control"
                                       value="<?= $basicSettings['site_name'] ?? '' ?>">
                            </div>
                        </div>

                        <div class="col-lg-6">
                            <div class="highlight">
                                <label class="form-label"><?= __('settings.admin_email','Admin Email') ?></label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="bi bi-envelope"></i></span>
                                    <input required type="email" name="admin_email" class="form-control"
                                           value="<?= $basicSettings['admin_email'] ?? '' ?>">
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-12">
                            <label class="form-label">
                                <?= __('settings.site_description','Site Description') ?>
                            </label>
                            <textarea name="site_description"
                                      class="form-control"
                                      rows="4"
                                      placeholder="<?= __('settings.site_description_placeholder','Write a short description about the site') ?>"><?= $basicSettings['site_description'] ?? '' ?></textarea>
                        </div>

                        <div class="col-12">
                            <label class="form-label"><?= __('settings.copyright','Copyright') ?></label>
                            <input type="text" name="copyright_text" class="form-control"
                                   value="<?= $basicSettings['copyright_text'] ?? '' ?>">
                        </div>

                    </div>
                </div>
            </div>

            <!-- LOCAL -->
            <div class="tab-pane fade" id="tab-local">
                <div class="card shadow-sm">
                    <div class="card-body row g-4">

                        <div class="col-md-4">
                            <label class="form-label"><?= __('settings.country','Country') ?></label>
                            <input list="countries" name="country" class="form-control"
                                   value="<?= $basicSettings['country'] ?? '' ?>">
                        </div>

                        <div class="col-md-4">
                            <label class="form-label"><?= __('settings.default_language','Language') ?></label>
                            <select name="default_language" class="form-select">
                                <?php foreach ($languages as $code => $name): ?>
                                    <option value="<?= $code ?>" <?= ($basicSettings['default_language'] ?? '') === $code ? 'selected' : '' ?>>
                                        <?= $name ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label"><?= __('settings.currency','Currency') ?></label>
                            <input type="text" name="currency" class="form-control"
                                   value="<?= $basicSettings['currency'] ?? '' ?>">
                        </div>
                        <div class="col-md-4">
    <label class="form-label">
        <?= __('settings.timezone_offset','Time Zone (GMT Offset)') ?>
    </label>
    <select name="timezone_offset" class="form-select">
        <?php
        for ($i = -12; $i <= 14; $i++):
            $label = ($i >= 0 ? '+' : '') . $i;
        ?>
            <option value="<?= $i ?>"
                <?= (string)($basicSettings['timezone_offset'] ?? '') === (string)$i ? 'selected' : '' ?>>
                GMT <?= $label ?>
            </option>
        <?php endfor; ?>
    </select>
    <small class="text-muted">
        <?= __('settings.timezone_hint','Used to display correct dates and statistics for your country.') ?>
    </small>
</div>
                    </div>
                </div>
            </div>

            <!-- CONTACT -->
            <div class="tab-pane fade" id="tab-contact">
                <div class="form-group-box mb-4">
                    <div class="row g-4">
                        <div class="col-lg-4">
                            <label class="form-label"><?= __('settings.phone','Phone') ?></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="bi bi-telephone"></i></span>
                                <input type="text" name="contact_phone" class="form-control"
                                       value="<?= $basicSettings['contact_phone'] ?? '' ?>">
                            </div>
                        </div>

                        <div class="col-lg-4">
                            <label class="form-label"><?= __('settings.whatsapp','WhatsApp') ?></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="bi bi-whatsapp"></i></span>
                                <input type="text" name="contact_whatsapp" class="form-control"
                                       value="<?= $basicSettings['contact_whatsapp'] ?? '' ?>">
                            </div>
                        </div>

                        <div class="col-lg-4">
                            <label class="form-label"><?= __('settings.email','Contact Email') ?></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="bi bi-envelope-at"></i></span>
                                <input type="email" name="contact_email" class="form-control"
                                       value="<?= $basicSettings['contact_email'] ?? '' ?>">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- ========================= -->
                <!-- Email Settings (Mailer) -->
                <!-- ========================= -->
                <!-- Email Settings -->
                <div class="card shadow-sm mt-4">
                    <div class="card-header fw-bold">
                        <i class="bi bi-envelope-paper me-1"></i>
                        <?= __('settings.mailer','Email Settings') ?>
                    </div>

                    <div class="card-body row g-4">

                        <div class="col-md-4">
                            <label class="form-label"><?= __('settings.mail_driver','Mail Driver') ?></label>
                            <select name="mail_driver" id="mail_driver" class="form-select">
                                <option value="mail" <?= ($basicSettings['mail_driver'] ?? '') === 'mail' ? 'selected' : '' ?>>PHP mail()</option>
                                <option value="smtp" <?= ($basicSettings['mail_driver'] ?? '') === 'smtp' ? 'selected' : '' ?>>SMTP</option>
                            </select>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label"><?= __('settings.mail_from_email','From Email') ?></label>
                            <input type="email" name="mail_from_email" class="form-control"
                                   value="<?= $basicSettings['mail_from_email'] ?? '' ?>">
                        </div>

                        <div class="col-md-4">
                            <label class="form-label"><?= __('settings.mail_from_name','From Name') ?></label>
                            <input type="text" name="mail_from_name" class="form-control"
                                   value="<?= $basicSettings['mail_from_name'] ?? '' ?>">
                        </div>

                        <!-- SMTP Fields -->
                        <div class="smtp-fields row g-4">

                            <div class="col-md-4">
                                <label class="form-label">SMTP Host</label>
                                <input type="text" name="mail_host" class="form-control"
                                       value="<?= $basicSettings['mail_host'] ?? '' ?>">
                            </div>

                            <div class="col-md-2">
                                <label class="form-label">SMTP Port</label>
                                <input type="text" name="mail_port" class="form-control"
                                       value="<?= $basicSettings['mail_port'] ?? '' ?>">
                            </div>

                            <div class="col-md-3">
                                <label class="form-label">SMTP Username</label>
                                <input type="text" name="mail_username" class="form-control"
                                       value="<?= $basicSettings['mail_username'] ?? '' ?>">
                            </div>

                            <div class="col-md-3">
                                <label class="form-label">SMTP Password</label>
                                <input type="password" name="mail_password" class="form-control"
                                       value="<?= $basicSettings['mail_password'] ?? '' ?>">
                            </div>

                            <div class="col-md-3">
                                <label class="form-label">Encryption</label>
                                <select name="mail_encryption" class="form-select">
                                    <?php foreach (['none','tls','ssl'] as $enc): ?>
                                        <option value="<?= $enc ?>" <?= ($basicSettings['mail_encryption'] ?? '') === $enc ? 'selected' : '' ?>>
                                            <?= strtoupper($enc) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                        </div>

                        <div class="col-12 d-flex justify-content-end mt-2">
                            <button type="submit"
                                    class="btn btn-outline-primary"
                                    onclick="this.form._mail_test.value=1">
                                <i class="bi bi-envelope-check me-1"></i>
                                <?= __('settings.test_email','Test Email Configuration') ?>
                            </button>
                        </div>

                    </div>
                </div>

            </div>

            <!-- SOCIAL -->
            <div class="tab-pane fade" id="tab-social">
                <div class="form-group-box mb-4">
                    <div class="row g-4">
                        <?php foreach (['facebook','instagram','twitter','tiktok','youtube','linkedin','snapchat','telegram'] as $s): ?>
                            <div class="col-lg-6">
                                <label class="form-label"><?= ucfirst($s) ?></label>
                                <div class="input-group">
                                    <span class="input-group-text">
                                        <i class="bi bi-<?= $s === 'youtube' ? 'youtube' : $s ?>"></i>
                                    </span>
                                    <input type="text" name="social_<?= $s ?>" class="form-control"
                                           value="<?= $basicSettings['social_'.$s] ?? '' ?>">
                                </div>
                            </div>
                        <?php endforeach; ?>

                        <div class="col-lg-6">
                            <label class="form-label"><?= __('settings.facebook_app_id', 'Facebook App ID') ?></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="bi bi-meta"></i></span>
                                <input type="text" name="facebook_app_id" class="form-control"
                                       placeholder="123456789012345"
                                       value="<?= htmlspecialchars($basicSettings['facebook_app_id'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                            </div>
                            <div class="form-text"><?= __('settings.facebook_app_id_help', 'Used to remove the fb:app_id warning and improve Facebook link previews.') ?></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- ADVANCED -->
            <div class="tab-pane fade" id="tab-advanced">
                <div class="card shadow-sm mb-4">
                    <div class="card-body">
                        <label class="form-label">
                            <i class="bi bi-bar-chart-line me-1"></i>
                            <?= __('settings.google_analytics','Google Analytics') ?>
                        </label>
                        <textarea name="google_analytics" class="form-control font-monospace"
                                  rows="4"><?= $basicSettings['google_analytics'] ?? '' ?></textarea>
                    </div>
                </div>

                <div class="card shadow-sm mb-4">
                    <div class="card-body row g-4">
                        <div class="col-lg-6">
                            <label class="form-label">
                                <i class="bi bi-diagram-3 me-1"></i>
                                <?= __('settings.sitemap_link','Sitemap Link') ?>
                            </label>
                            <div class="input-group mb-2">
                                <input type="text" id="sitemap-link" class="form-control" value="<?= htmlspecialchars($sitemapUrl) ?>" readonly>
                                <button type="button" class="btn btn-outline-secondary" data-copy-target="sitemap-link" title="<?= __('actions.copy', 'Copy') ?>">
                                    <i class="bi bi-clipboard"></i>
                                </button>
                                <a href="<?= htmlspecialchars($sitemapUrl) ?>" target="_blank" rel="noopener" class="btn btn-outline-primary">
                                    <i class="bi bi-box-arrow-up-right me-1"></i><?= __('settings.open_sitemap','Open sitemap') ?>
                                </a>
                            </div>
                            <small class="text-muted"><?= __('settings.sitemap_link_help','Copy this link and submit it to search engines.') ?></small>
                        </div>

                        <div class="col-lg-6">
                            <label class="form-label">
                                <i class="bi bi-file-earmark-code me-1"></i>
                                <?= __('settings.robots_editor','Robots.txt Editor') ?>
                            </label>
                            <div class="d-flex justify-content-end mb-2">
                                <a href="<?= htmlspecialchars($robotsUrl) ?>" target="_blank" rel="noopener" class="btn btn-sm btn-outline-primary">
                                    <i class="bi bi-box-arrow-up-right me-1"></i><?= __('settings.open_robots','Open robots.txt') ?>
                                </a>
                            </div>
                            <textarea name="robots_txt_content" class="form-control font-monospace" rows="10" spellcheck="false"><?= htmlspecialchars($robotsEditorValue) ?></textarea>
                            <small class="text-muted d-block mt-2"><?= __('settings.robots_editor_help','Use {BASE_URL} as a placeholder for your current site URL. If the field is empty, the default robots.txt content will be used.') ?></small>
                        </div>
                    </div>
                </div>
                                <div class="card shadow-sm mb-4">
                    <div class="card-body">
                        <input type="hidden" name="product_image_autorotate" value="0">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="product_image_autorotate" value="1" <?= !empty($basicSettings['product_image_autorotate']) ? 'checked' : '' ?>>
                            <label class="form-check-label"><?= __('settings.product_image_autorotate','Auto-rotate product card images') ?></label>
                            <div class="text-muted small mt-1"><?= __('settings.product_image_autorotate_help','On the home page, products with extra images will rotate automatically inside their cards.') ?></div>
                        </div>
                    </div>
                </div>

                <hr class="my-4">

<div class="card shadow-sm">
    <div class="card-header fw-bold">
        <i class="bi bi-clock-history me-1"></i>
        <?= __('settings.cron', 'Cron Jobs') ?>
    </div>

    <div class="card-body">

        <!-- ENABLE CRON -->
        <div class="form-check form-switch mb-3">
            <input class="form-check-input"
                   type="checkbox"
                   name="cron_enabled"
                   value="1"
                   <?= !empty($basicSettings['cron_enabled']) ? 'checked' : '' ?>>
            <label class="form-check-label">
                <?= __('settings.cron_enabled', 'Enable Cron Jobs') ?>
            </label>
        </div>

         <!-- CRON URL + COMMANDS -->
        <div class="mb-3">
            <label class="form-label">
                <?= __('settings.cron_url', 'Cron URL') ?>
            </label>

            <?php
            $cronToken = $basicSettings['cron_token'] ?? '';

            // Robust scheme detection (cPanel / reverse-proxy safe-ish)
            $isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
                       || (!empty($_SERVER['SERVER_PORT']) && (int)$_SERVER['SERVER_PORT'] === 443);

            $scheme = $isHttps ? 'https' : 'http';
            $host   = $_SERVER['HTTP_HOST'] ?? '';

            $cronUrl = ($cronToken && $host)
                ? rtrim($scheme . '://' . $host, '/') . '/cron/run?token=' . $cronToken
                : '';

            // Ready-to-paste commands for cPanel Cron Jobs
            $cronCurl = $cronUrl
                ? '/usr/bin/curl -fsS "' . $cronUrl . '" > /dev/null 2>&1'
                : '';

            $cronWget = $cronUrl
                ? '/usr/bin/wget -qO- "' . $cronUrl . '" > /dev/null 2>&1'
                : '';
            ?>

            <!-- URL (for manual test) -->
            <div class="input-group mb-2">
                <input type="text"
                       id="cron-url"
                       class="form-control"
                       value="<?= htmlspecialchars($cronUrl) ?>"
                       readonly>
                <button type="button"
                        class="btn btn-outline-secondary"
                        data-copy-target="cron-url"
                        title="<?= __('actions.copy', 'Copy') ?>">
                    <i class="bi bi-clipboard"></i>
                </button>
            </div>

            <small class="text-muted d-block mt-1">
                <?= __('settings.cron_hint','Open this URL in your browser to test the cron manually.') ?>
            </small>

            <hr class="my-3">

            <!-- cPanel command: curl -->
            <label class="form-label mb-1">
                <?= __('settings.cron_command', 'Cron Command (cPanel)') ?> � cURL
            </label>
            <div class="input-group mb-2">
                <input type="text"
                       id="cron-curl"
                       class="form-control font-monospace"
                       value="<?= htmlspecialchars($cronCurl) ?>"
                       readonly>
                <button type="button"
                        class="btn btn-outline-secondary"
                        data-copy-target="cron-curl"
                        title="<?= __('actions.copy', 'Copy') ?>">
                    <i class="bi bi-clipboard"></i>
                </button>
            </div>

            <!-- cPanel command: wget -->
            <label class="form-label mb-1">
                <?= __('settings.cron_command_alt', 'Alternative Command') ?> � wget
            </label>
            <div class="input-group mb-2">
                <input type="text"
                       id="cron-wget"
                       class="form-control font-monospace"
                       value="<?= htmlspecialchars($cronWget) ?>"
                       readonly>
                <button type="button"
                        class="btn btn-outline-secondary"
                        data-copy-target="cron-wget"
                        title="<?= __('actions.copy', 'Copy') ?>">
                    <i class="bi bi-clipboard"></i>
                </button>
            </div>

            <small class="text-muted d-block mt-2">
                <?= __('settings.cron_recommended','Recommended: run this cron every 15 minutes.') ?>
            </small>

            <small class="text-muted d-block mt-1">
                <?= __('settings.cron_note',
                    'Important: In cPanel Cron Jobs you must paste the COMMAND (curl/wget). Pasting the URL alone will not execute anything.'
                ) ?>
            </small>
        </div>
        <!-- REGENERATE TOKEN -->
        <div class="mt-3">
      <button type="button"
        id="regen-cron-token"
        class="btn btn-outline-danger btn-sm">
    <i class="bi bi-arrow-repeat me-1"></i>
    <?= __('settings.cron_regenerate','Regenerate Token') ?>
</button>

        </div>

    </div>
</div>


<hr class="my-4">

<!-- Google Sheets — moved to Integrations -->
<div class="card shadow-sm border-0 bg-light">
    <div class="card-body d-flex align-items-center gap-3 py-3">
        <img src="https://www.gstatic.com/images/branding/product/2x/sheets_2020q4_48dp.png"
             style="width:32px;height:32px" alt="Google Sheets">
        <div class="flex-grow-1">
            <div class="fw-semibold"><?= __('settings.gsheets.title','Google Sheets Export') ?></div>
            <small class="text-muted"><?= __('settings.gsheets.moved','Google Sheets settings have moved to Integrations.') ?></small>
        </div>
        <a href="/admin/integrations?tab=tracking" class="btn btn-outline-primary btn-sm">
            <i class="bi bi-box-arrow-up-right me-1"></i>
            <?= __('settings.gsheets.go_settings','Open in Integrations') ?>
        </a>
    </div>
</div>
<!-- LAST CRON RUN -->
<div class="mt-3">
    <label class="form-label">
        <i class="bi bi-clock me-1"></i>
        <?= __('settings.cron_last_run','Last Cron Run') ?>
    </label>

    <div class="form-control bg-light" readonly>
        <?php if ($cronLastRun): ?>
            <?= date(
                'Y-m-d H:i:s',
                $cronLastRun + ((int)($basicSettings['timezone_offset'] ?? 0) * 3600)
            ) ?>
        <?php else: ?>
            <span class="text-muted">
                <?= __('settings.cron_never_run','Cron has not been executed yet') ?>
            </span>
        <?php endif; ?>
    </div>
</div>

            </div>

        </div>

        <div class="save-bar d-flex justify-content-between align-items-center mt-4">
            <small class="text-muted">
                <i class="bi bi-shield-check me-1"></i>
                <?= __('settings.auto_safe','Your changes are safe until saved') ?>
            </small>
            <button type="submit" class="btn btn-primary btn-lg px-5">
                <i class="bi bi-save me-1"></i>
                <?= __('actions.save','Save Changes') ?>
            </button>
        </div>

    </form>

    <datalist id="countries">
        <?php foreach ($countries as $country): ?>
            <option value="<?= htmlspecialchars($country, ENT_QUOTES, 'UTF-8') ?>"></option>
        <?php endforeach; ?>
    </datalist>

</div>

</section>
</div>


<script>
document.addEventListener('click', function (e) {
    const btn = e.target.closest('[data-copy-target]');
    if (!btn) return;
    const target = document.getElementById(btn.getAttribute('data-copy-target'));
    if (!target) return;
    const value = target.value || target.textContent || '';
    if (!value) return;
    navigator.clipboard.writeText(value).then(() => {
        btn.classList.remove('btn-outline-secondary');
        btn.classList.add('btn-success');
        setTimeout(() => {
            btn.classList.add('btn-outline-secondary');
            btn.classList.remove('btn-success');
        }, 1200);
    }).catch(() => {});
});
</script>

<?php include ADMIN_PATH . '/templates/footer.php'; ?>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const driver = document.getElementById('mail_driver');
    const smtpFields = document.querySelector('.smtp-fields');

    function toggleSMTP() {
        smtpFields.style.display = (driver.value === 'smtp') ? 'flex' : 'none';
    }

    driver.addEventListener('change', toggleSMTP);
    toggleSMTP();
});
</script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const driver = document.getElementById('mail_driver');
    const smtpFields = document.querySelector('.smtp-fields');

    function toggleSMTP() {
        if (!smtpFields || !driver) return;
        smtpFields.style.display = (driver.value === 'smtp') ? 'flex' : 'none';
    }

    if (driver) {
        driver.addEventListener('change', toggleSMTP);
        toggleSMTP();
    }
});
</script>

<script>
(function () {

    const cronInput = document.getElementById('cron-url');
    const btnRegen  = document.getElementById('regen-cron-token');

    /* =========================
       COPY (ANY FIELD)
       Uses: <button data-copy-target="input-id">
    ========================= */
    async function copyFromInputId(inputId) {
        const el = document.getElementById(inputId);
        const text = el ? (el.value || '') : '';
        if (!el || !text) return;

        try {
            if (navigator.clipboard && window.isSecureContext) {
                await navigator.clipboard.writeText(text);
                return;
            }
        } catch (e) {}

        // Fallback
        try {
            el.removeAttribute('readonly');
            el.select();
            el.setSelectionRange(0, 99999);
            document.execCommand('copy');
        } catch (e) {
        } finally {
            el.setAttribute('readonly', 'readonly');
            if (window.getSelection) window.getSelection().removeAllRanges();
        }
    }

    document.addEventListener('click', function (e) {
        const btn = e.target.closest('[data-copy-target]');
        if (!btn) return;
        const target = btn.getAttribute('data-copy-target');
        if (!target) return;
        copyFromInputId(target);
    });

    /* =========================
       REGENERATE CRON TOKEN (CSRF)
    ========================= */
    if (btnRegen) {
        btnRegen.addEventListener('click', function () {

            const csrfToken = '<?= \Core\System\Csrf::token() ?>';

            const params = new URLSearchParams();
            params.append('_csrf', csrfToken);

            fetch('/admin/cron/regenerate', {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                body: params.toString()
            })
            .then(response => {
                const type = response.headers.get('content-type') || '';
                if (!type.includes('application/json')) {
                    throw new Error('Invalid response');
                }
                return response.json();
            })
            .then(data => {
                if (!data || data.success !== true) {
                    alert(data && data.message ? data.message : 'Error');
                    return;
                }

                // Update URL input
                if (cronInput) cronInput.value = data.url || '';

                // Also update commands (if they exist)
                const curl = document.getElementById('cron-curl');
                const wget = document.getElementById('cron-wget');
                if (curl) curl.value = data.url ? ('/usr/bin/curl -fsS "' + data.url + '" > /dev/null 2>&1') : '';
                if (wget) wget.value = data.url ? ('/usr/bin/wget -qO- "' + data.url + '" > /dev/null 2>&1') : '';

                alert(data.message || 'OK');
            })
            .catch(() => {
                alert('Error');
            });
        });
    }

})();
</script>