<?php
require_once '../includes/config.php';
requireAdmin();

$msg = '';
$msgType = 'success';

// Handle POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'toggle_maintenance') {
        $cur = $pdo->query("SELECT setting_value FROM site_settings WHERE setting_key='maintenance_mode'")->fetchColumn();
        $new = ($cur === '1') ? '0' : '1';
        $pdo->prepare("INSERT INTO site_settings (setting_key,setting_value) VALUES ('maintenance_mode',?) ON DUPLICATE KEY UPDATE setting_value=?")->execute([$new,$new]);
        $msg = $new === '1' ? '🔧 Maintenance mode ENABLED.' : '✅ Maintenance mode DISABLED.';
    }

    if ($action === 'save_registration') {
        $reg = isset($_POST['registration_open']) ? '1' : '0';
        $max = (int)($_POST['max_users'] ?? 0);
        $pdo->prepare("INSERT INTO site_settings (setting_key,setting_value) VALUES ('registration_open',?) ON DUPLICATE KEY UPDATE setting_value=?")->execute([$reg,$reg]);
        $pdo->prepare("INSERT INTO site_settings (setting_key,setting_value) VALUES ('max_users',?) ON DUPLICATE KEY UPDATE setting_value=?")->execute([$max,$max]);
        $msg = 'Registration settings saved.';
    }

    if ($action === 'save_telegram') {
        $token = sanitize($_POST['telegram_bot_token'] ?? '');
        $chat  = sanitize($_POST['telegram_chat_id'] ?? '');
        $pdo->prepare("INSERT INTO site_settings (setting_key,setting_value) VALUES ('telegram_bot_token',?) ON DUPLICATE KEY UPDATE setting_value=?")->execute([$token,$token]);
        $pdo->prepare("INSERT INTO site_settings (setting_key,setting_value) VALUES ('telegram_chat_id',?) ON DUPLICATE KEY UPDATE setting_value=?")->execute([$chat,$chat]);
        $msg = 'Telegram settings saved.';
    }

    if ($action === 'test_telegram') {
        $token = $pdo->query("SELECT setting_value FROM site_settings WHERE setting_key='telegram_bot_token'")->fetchColumn();
        $chat  = $pdo->query("SELECT setting_value FROM site_settings WHERE setting_key='telegram_chat_id'")->fetchColumn();
        if ($token && $chat) {
            $r = @file_get_contents("https://api.telegram.org/bot$token/sendMessage?chat_id=$chat&text=StudyTrack+Admin+test+message+✅");
            $msg = $r ? '✅ Telegram test message sent!' : '❌ Telegram test failed. Check token/chat ID.';
            $msgType = $r ? 'success' : 'error';
        } else { $msg = '❌ Telegram not configured yet.'; $msgType='error'; }
    }

    if ($action === 'save_smtp') {
        foreach(['smtp_host','smtp_port','smtp_user','smtp_pass','smtp_from','smtp_from_name'] as $k) {
            $v = sanitize($_POST[$k] ?? '');
            $pdo->prepare("INSERT INTO site_settings (setting_key,setting_value) VALUES (?,?) ON DUPLICATE KEY UPDATE setting_value=?")->execute([$k,$v,$v]);
        }
        $msg = 'SMTP settings saved.';
    }

    if ($action === 'save_site_info') {
        foreach(['site_name','site_tagline','contact_email'] as $k) {
            $v = sanitize($_POST[$k] ?? '');
            $pdo->prepare("INSERT INTO site_settings (setting_key,setting_value) VALUES (?,?) ON DUPLICATE KEY UPDATE setting_value=?")->execute([$k,$v,$v]);
        }
        $msg = 'Site info saved.';
    }

    if ($action === 'save_api') {
        $key = sanitize($_POST['claude_api_key'] ?? '');
        $enabled = isset($_POST['ai_enabled']) ? '1' : '0';
        $pdo->prepare("INSERT INTO site_settings (setting_key,setting_value) VALUES ('claude_api_key',?) ON DUPLICATE KEY UPDATE setting_value=?")->execute([$key,$key]);
        $pdo->prepare("INSERT INTO site_settings (setting_key,setting_value) VALUES ('ai_enabled',?) ON DUPLICATE KEY UPDATE setting_value=?")->execute([$enabled,$enabled]);
        $msg = 'API settings saved.';
    }

    if ($action === 'save_rate_limits') {
        foreach(['max_api_calls_per_day','max_study_sessions_per_day','max_tasks_per_user'] as $k) {
            $v = (int)($_POST[$k] ?? 0);
            $pdo->prepare("INSERT INTO site_settings (setting_key,setting_value) VALUES (?,?) ON DUPLICATE KEY UPDATE setting_value=?")->execute([$k,$v,$v]);
        }
        $msg = 'Rate limit settings saved.';
    }
}

// Load all settings
$allSettings = $pdo->query("SELECT setting_key, setting_value FROM site_settings")->fetchAll(PDO::FETCH_KEY_PAIR);
$get = fn($k, $def='') => $allSettings[$k] ?? $def;

require_once 'includes/header.php';
renderAdminHeader('Site Settings', 'site-settings');
?>
<style>
.settings-section { background:var(--surface); border:1px solid var(--border); border-radius:12px; padding:24px; margin-bottom:20px; }
.settings-section h3 { margin:0 0 16px; font-size:16px; color:var(--text-primary); display:flex; align-items:center; gap:8px; }
.form-row { display:grid; grid-template-columns:1fr 1fr; gap:16px; }
.form-group { margin-bottom:14px; }
.form-group label { display:block; font-size:13px; color:var(--text-muted); margin-bottom:5px; font-weight:500; }
.form-group input[type=text],.form-group input[type=email],.form-group input[type=number],.form-group input[type=password] {
  width:100%; background:var(--bg); border:1px solid var(--border); border-radius:8px; padding:8px 12px; color:var(--text-primary); font-size:14px; box-sizing:border-box;
}
.toggle-row { display:flex; align-items:center; justify-content:space-between; padding:12px 0; border-bottom:1px solid var(--border); }
.toggle-row:last-child { border-bottom:none; }
.toggle-label { font-size:14px; color:var(--text-primary); font-weight:500; }
.toggle-desc { font-size:12px; color:var(--text-muted); margin-top:2px; }
.badge-on { background:rgba(16,185,129,0.15); color:#10b981; padding:3px 10px; border-radius:12px; font-size:12px; font-weight:600; }
.badge-off { background:rgba(239,68,68,0.15); color:#ef4444; padding:3px 10px; border-radius:12px; font-size:12px; font-weight:600; }
.alert-msg { padding:10px 16px; border-radius:8px; margin-bottom:16px; font-size:14px; }
.alert-success { background:rgba(16,185,129,0.1); border:1px solid rgba(16,185,129,0.3); color:#10b981; }
.alert-error { background:rgba(239,68,68,0.1); border:1px solid rgba(239,68,68,0.3); color:#ef4444; }
</style>

<?php if($msg): ?>
<div class="alert-msg alert-<?= $msgType === 'error' ? 'error' : 'success' ?>"><?= htmlspecialchars($msg) ?></div>
<?php endif; ?>

<!-- Maintenance Mode -->
<div class="settings-section">
  <h3>🔧 Maintenance Mode</h3>
  <div class="toggle-row">
    <div>
      <div class="toggle-label">Maintenance Mode</div>
      <div class="toggle-desc">When ON, students see a "We'll be back soon" page. Admins still have access.</div>
    </div>
    <div style="display:flex;align-items:center;gap:12px">
      <?php $maint = $get('maintenance_mode','0'); ?>
      <span class="<?= $maint==='1' ? 'badge-on' : 'badge-off' ?>"><?= $maint==='1' ? 'ON' : 'OFF' ?></span>
      <form method="POST" style="margin:0">
        <input type="hidden" name="action" value="toggle_maintenance">
        <button class="btn <?= $maint==='1' ? 'btn-secondary' : '' ?>" style="<?= $maint!=='1' ? 'background:rgba(239,68,68,0.15);color:#ef4444;border-color:rgba(239,68,68,0.3)' : '' ?>" type="submit">
          <?= $maint==='1' ? '✅ Disable' : '🔧 Enable Maintenance' ?>
        </button>
      </form>
    </div>
  </div>
</div>

<!-- Registration Control -->
<div class="settings-section">
  <h3>📝 Registration Control</h3>
  <form method="POST">
  <input type="hidden" name="action" value="save_registration">
  <div class="toggle-row">
    <div>
      <div class="toggle-label">Allow New Registrations</div>
      <div class="toggle-desc">If off, new students cannot sign up.</div>
    </div>
    <label style="display:flex;align-items:center;gap:8px;cursor:pointer">
      <input type="checkbox" name="registration_open" <?= $get('registration_open','1')==='1' ? 'checked' : '' ?> style="width:18px;height:18px">
      <span style="font-size:14px;color:var(--text-primary)">Open</span>
    </label>
  </div>
  <div class="form-group" style="margin-top:12px">
    <label>Max Users (0 = unlimited)</label>
    <input type="number" name="max_users" value="<?= htmlspecialchars($get('max_users','0')) ?>" min="0">
  </div>
  <button class="btn" type="submit">💾 Save Registration Settings</button>
  </form>
</div>

<!-- Telegram -->
<div class="settings-section">
  <h3>📱 Telegram Bot Config</h3>
  <form method="POST">
  <input type="hidden" name="action" value="save_telegram">
  <div class="form-row">
    <div class="form-group">
      <label>Bot Token</label>
      <input type="text" name="telegram_bot_token" value="<?= htmlspecialchars($get('telegram_bot_token')) ?>" placeholder="123456789:ABCdef...">
    </div>
    <div class="form-group">
      <label>Chat ID</label>
      <input type="text" name="telegram_chat_id" value="<?= htmlspecialchars($get('telegram_chat_id')) ?>" placeholder="-100123456789">
    </div>
  </div>
  <div style="display:flex;gap:8px">
    <button class="btn" type="submit">💾 Save Telegram Settings</button>
    <button class="btn btn-secondary" formaction="" type="submit" name="action" value="test_telegram">🔔 Test Connection</button>
  </div>
  </form>
</div>

<!-- SMTP Settings -->
<div class="settings-section">
  <h3>📧 SMTP Mail Settings</h3>
  <form method="POST">
  <input type="hidden" name="action" value="save_smtp">
  <div class="form-row">
    <div class="form-group"><label>SMTP Host</label><input type="text" name="smtp_host" value="<?= htmlspecialchars($get('smtp_host',SMTP_HOST)) ?>"></div>
    <div class="form-group"><label>SMTP Port</label><input type="number" name="smtp_port" value="<?= htmlspecialchars($get('smtp_port',SMTP_PORT)) ?>"></div>
  </div>
  <div class="form-row">
    <div class="form-group"><label>SMTP User</label><input type="text" name="smtp_user" value="<?= htmlspecialchars($get('smtp_user',SMTP_USER)) ?>"></div>
    <div class="form-group"><label>SMTP Password</label><input type="password" name="smtp_pass" value="<?= htmlspecialchars($get('smtp_pass','')) ?>" placeholder="••••••••"></div>
  </div>
  <div class="form-row">
    <div class="form-group"><label>From Email</label><input type="email" name="smtp_from" value="<?= htmlspecialchars($get('smtp_from',SMTP_FROM)) ?>"></div>
    <div class="form-group"><label>From Name</label><input type="text" name="smtp_from_name" value="<?= htmlspecialchars($get('smtp_from_name',SMTP_FROM_NAME)) ?>"></div>
  </div>
  <button class="btn" type="submit">💾 Save SMTP Settings</button>
  </form>
</div>

<!-- Site Info -->
<div class="settings-section">
  <h3>🌐 Site Name &amp; Info</h3>
  <form method="POST">
  <input type="hidden" name="action" value="save_site_info">
  <div class="form-row">
    <div class="form-group"><label>Site Name</label><input type="text" name="site_name" value="<?= htmlspecialchars($get('site_name',SITE_NAME)) ?>"></div>
    <div class="form-group"><label>Tagline</label><input type="text" name="site_tagline" value="<?= htmlspecialchars($get('site_tagline','Your study companion')) ?>"></div>
  </div>
  <div class="form-group"><label>Contact Email</label><input type="email" name="contact_email" value="<?= htmlspecialchars($get('contact_email',SMTP_FROM)) ?>"></div>
  <button class="btn" type="submit">💾 Save Site Info</button>
  </form>
</div>

<!-- AI / Claude API -->
<div class="settings-section">
  <h3>🤖 AI / Claude API Config</h3>
  <form method="POST">
  <input type="hidden" name="action" value="save_api">
  <div class="toggle-row" style="margin-bottom:12px">
    <div><div class="toggle-label">Enable AI Features</div><div class="toggle-desc">Toggle AI-powered tips, analysis, and chat globally.</div></div>
    <label style="display:flex;align-items:center;gap:8px;cursor:pointer">
      <input type="checkbox" name="ai_enabled" <?= $get('ai_enabled','1')==='1'?'checked':'' ?> style="width:18px;height:18px">
      <span style="color:var(--text-primary);font-size:14px">Enabled</span>
    </label>
  </div>
  <div class="form-group"><label>Claude / Groq API Key</label><input type="password" name="claude_api_key" value="<?= htmlspecialchars($get('claude_api_key','')) ?>" placeholder="sk-..."></div>
  <button class="btn" type="submit">💾 Save API Settings</button>
  </form>
</div>

<!-- Rate Limiting -->
<div class="settings-section">
  <h3>⚡ Rate Limiting</h3>
  <form method="POST">
  <input type="hidden" name="action" value="save_rate_limits">
  <div class="form-row">
    <div class="form-group"><label>Max API Calls / User / Day</label><input type="number" name="max_api_calls_per_day" value="<?= htmlspecialchars($get('max_api_calls_per_day','50')) ?>" min="0"></div>
    <div class="form-group"><label>Max Study Sessions / User / Day</label><input type="number" name="max_study_sessions_per_day" value="<?= htmlspecialchars($get('max_study_sessions_per_day','20')) ?>" min="0"></div>
  </div>
  <div class="form-group"><label>Max Tasks / User</label><input type="number" name="max_tasks_per_user" value="<?= htmlspecialchars($get('max_tasks_per_user','100')) ?>" min="0"></div>
  <button class="btn" type="submit">💾 Save Rate Limits</button>
  </form>
</div>

<?php require_once 'includes/footer.php'; renderAdminFooter(); ?>
