<?php
/**
 * StudyTrack — Telegram Link Page
 * File: /studytrack/telegram-link.php  (REPLACE existing file)
 *
 * Fixed: auto-creates telegram_id column if missing
 */

require_once 'includes/config.php';

$tgId   = (int)($_GET['tg']   ?? 0);
$tgName = htmlspecialchars($_GET['name'] ?? '', ENT_QUOTES);
$hash   = $_GET['hash'] ?? '';

// ── HMAC validate ─────────────────────────────────────────────────────────────
$expectedHash = hash_hmac('sha256', "tg_link:{$tgId}", BOT_TOKEN);
if (!$tgId || !hash_equals($expectedHash, $hash)) {
    die(renderPage('Invalid Link',
        'This link is invalid or expired. Please tap <b>Link Account</b> in the bot again.',
        'error'));
}

// ── Auto-create telegram_id column if it doesn't exist ───────────────────────
try {
    $col = $pdo->query("SHOW COLUMNS FROM users LIKE 'telegram_id'");
    if ($col->rowCount() === 0) {
        $pdo->exec("ALTER TABLE users ADD COLUMN telegram_id BIGINT DEFAULT NULL");
        try {
            $pdo->exec("ALTER TABLE users ADD INDEX idx_telegram_id (telegram_id)");
        } catch (Exception $e) { /* index may already exist */ }
    }
} catch (Exception $e) {
    die(renderPage('Database Error',
        'Could not prepare the database. Please contact support. Error: ' . htmlspecialchars($e->getMessage()),
        'error'));
}

// ── Login check ───────────────────────────────────────────────────────────────
if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
    $returnUrl = urlencode(SITE_URL . "/telegram-link.php?tg={$tgId}&name={$tgName}&hash={$hash}");
    header("Location: " . SITE_URL . "/login.php?return={$returnUrl}");
    exit;
}

$uid  = (int)$_SESSION['user_id'];
$name = $_SESSION['user_name'] ?? 'User';

// ── Already linked to this same account? ─────────────────────────────────────
$q = $pdo->prepare("SELECT telegram_id FROM users WHERE id = ?");
$q->execute([$uid]);
$existingTgId = $q->fetchColumn();

if ((int)$existingTgId === $tgId) {
    sendBotMessage($tgId,
        "✅ <b>{$name}</b>, your account is already connected!\n\nUse the menu below to get started. 👇");
    die(renderPage('Already Connected ✅',
        "<strong>{$name}</strong>, your account is already linked to the bot!",
        'success'));
}

// ── Unlink from any other account that had this tg_id ────────────────────────
$pdo->prepare("UPDATE users SET telegram_id = NULL WHERE telegram_id = ?")
    ->execute([$tgId]);

// ── LINK ─────────────────────────────────────────────────────────────────────
$stmt = $pdo->prepare("UPDATE users SET telegram_id = ? WHERE id = ?");
$stmt->execute([$tgId, $uid]);

if ($stmt->rowCount() === 0) {
    die(renderPage('Link Failed',
        'Could not link your account. Please try again or contact support.',
        'error'));
}

// ── Verify it actually saved ──────────────────────────────────────────────────
$verify = $pdo->prepare("SELECT telegram_id FROM users WHERE id = ?");
$verify->execute([$uid]);
$savedId = (int)$verify->fetchColumn();

if ($savedId !== $tgId) {
    die(renderPage('Link Failed',
        'Account link could not be saved. The telegram_id column may be missing. Please run the SQL fix.',
        'error'));
}

// ── Send confirmation message to bot ─────────────────────────────────────────
$botMsg = "✅ <b>Account Linked!</b>\n\n"
    . "👤 <b>{$name}</b>'s StudyTrack account is now connected.\n\n"
    . "You can now use:\n"
    . "📊 Summary — Today's study\n"
    . "📝 Log Study — Record sessions\n"
    . "✅ Tasks — Manage tasks\n"
    . "📚 Marks — Exam results\n"
    . "🎯 Goals — Track goals\n\n"
    . "Use the menu below 👇";

sendBotMessage($tgId, $botMsg);

die(renderPage('Connected! 🎉',
    "<strong>{$name}</strong>, your Telegram bot is now connected!<br><br>"
    . "Check the bot for a confirmation message. ✅<br><br>"
    . "<em>You can close this window.</em>",
    'success'));


// ── Send message via Telegram Bot API ────────────────────────────────────────
function sendBotMessage(int $chatId, string $text): void {
    if (!defined('BOT_TOKEN')) return;
    try {
        $ch = curl_init("https://api.telegram.org/bot" . BOT_TOKEN . "/sendMessage");
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 8,
            CURLOPT_POSTFIELDS     => http_build_query([
                'chat_id'    => $chatId,
                'text'       => $text,
                'parse_mode' => 'HTML',
                'reply_markup' => json_encode([
                    'keyboard' => [
                        [['text' => '📊 Summary'],      ['text' => '📝 Log Study']],
                        [['text' => '✅ Tasks'],         ['text' => '📚 Marks']],
                        [['text' => '🎯 Goals'],         ['text' => '🔔 Notifications']],
                        [['text' => '📈 Weekly Stats'], ['text' => '🔥 Streak']],
                        [['text' => '👤 My Profile'],   ['text' => '⚙️ Settings']],
                    ],
                    'resize_keyboard'   => true,
                    'one_time_keyboard' => false,
                ])
            ])
        ]);
        curl_exec($ch);
        curl_close($ch);
    } catch (Exception $e) {
        // Silently fail — link was successful, message is secondary
    }
}


// ── Render helper ─────────────────────────────────────────────────────────────
function renderPage(string $title, string $msg, string $type): string {
    $icon  = $type === 'success' ? '🎉' : '❌';
    $color = $type === 'success' ? '#10b981' : '#ef4444';
    $bg    = $type === 'success' ? 'rgba(16,185,129,.12)' : 'rgba(239,68,68,.12)';
    ob_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title><?= htmlspecialchars($title) ?> — StudyTrack</title>
  <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;600;700&display=swap" rel="stylesheet">
  <style>
    *{margin:0;padding:0;box-sizing:border-box}
    body{font-family:'Outfit',sans-serif;background:#0f172a;color:#f1f5f9;
         min-height:100vh;display:flex;align-items:center;justify-content:center;padding:24px}
    .card{background:#1e293b;border-radius:24px;padding:44px 32px;max-width:400px;width:100%;
          text-align:center;box-shadow:0 32px 80px rgba(0,0,0,.5);border:1px solid rgba(255,255,255,.07);
          animation:pop .35s cubic-bezier(.34,1.56,.64,1) both}
    @keyframes pop{from{opacity:0;transform:scale(.9)}to{opacity:1;transform:scale(1)}}
    .icon{width:80px;height:80px;border-radius:50%;margin:0 auto 24px;
          background:<?= $bg ?>;display:flex;align-items:center;justify-content:center;
          font-size:38px;border:2px solid <?= $color ?>}
    h1{font-size:22px;font-weight:700;margin-bottom:14px;color:#f8fafc}
    p{font-size:14.5px;color:#94a3b8;line-height:1.8}
    strong{color:#e2e8f0}
    .btn{display:inline-block;margin-top:24px;padding:13px 30px;
         background:linear-gradient(135deg,#6366f1,#8b5cf6);color:#fff;
         border-radius:12px;text-decoration:none;font-weight:600;font-size:14px}
  </style>
</head>
<body>
  <div class="card">
    <div class="icon"><?= $icon ?></div>
    <h1><?= htmlspecialchars($title) ?></h1>
    <p><?= $msg ?></p>
    <a href="https://t.me/StudyTrackedurx_bot" class="btn">Open Bot</a>
  </div>
</body>
</html>
    <?php return ob_get_clean();
}
