<?php
session_start();
require_once 'config.php';

// Cek login
function isAdminLoggedIn() {
    return isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true;
}

// Login handler
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'login') {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    
    if ($username === ADMIN_USER && password_verify($password, ADMIN_PASS_HASH)) {
        $_SESSION['admin_logged_in'] = true;
        $_SESSION['admin_username'] = $username;
        $_SESSION['login_time'] = time();
        
        // Log aktivitas login ke Telegram
        sendTelegram("🔐 *Admin Login*\n" . 
                    "👤 User: $username\n" . 
                    "🕐 Waktu: " . date('d/m/Y H:i:s') . "\n" .
                    "🌐 IP: " . ($_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR']));
        
        header('Location: index.html');
        exit;
    } else {
        $error = "Username atau password salah!";
    }
}

// Logout handler
if (isset($_GET['logout'])) {
    sendTelegram("🔓 *Admin Logout*\n" . 
                "👤 User: " . ($_SESSION['admin_username'] ?? 'Unknown') . "\n" .
                "🕐 Waktu: " . date('d/m/Y H:i:s'));
    session_destroy();
    header('Location: login.html');
    exit;
}

// Proteksi halaman admin
function requireAuth() {
    if (!isAdminLoggedIn()) {
        header('Location: login.html');
        exit;
    }
    // Session timeout: 4 jam
    if (time() - ($_SESSION['login_time'] ?? 0) > 14400) {
        session_destroy();
        header('Location: login.html?timeout=1');
        exit;
    }
}
?>