<?php
// Admin Configuration - INATOGEL
// File ini berisi konfigurasi khusus untuk area admin

// Keamanan
if (!defined('ADMIN_ACCESS')) {
    die('Direct access not allowed');
}

// Database config (sama dengan main site)
require_once '../includes/database.php';

// Admin security settings
define('ADMIN_SESSION_TIMEOUT', 3600); // 1 jam
define('ADMIN_MAX_LOGIN_ATTEMPTS', 3);
define('ADMIN_LOCKOUT_TIME', 900); // 15 menit

// Admin constants
define('ADMIN_TITLE', 'Togel Admin Panel');
define('ADMIN_VERSION', '1.0.0');

// Fungsi keamanan admin
class AdminSecurity {
    private static $db;
    
    public static function init() {
        self::$db = new Database();
        
        // Start secure session
        if (session_status() === PHP_SESSION_NONE) {
            session_start([
                'cookie_lifetime' => ADMIN_SESSION_TIMEOUT,
                'cookie_secure' => isset($_SERVER['HTTPS']),
                'cookie_httponly' => true,
                'cookie_samesite' => 'Strict'
            ]);
        }
        
        // Regenerate session ID untuk keamanan
        if (!isset($_SESSION['admin_session_started'])) {
            session_regenerate_id(true);
            $_SESSION['admin_session_started'] = time();
        }
        
        // Check session timeout
        if (isset($_SESSION['admin_last_activity']) && 
            (time() - $_SESSION['admin_last_activity'] > ADMIN_SESSION_TIMEOUT)) {
            self::logout();
            return false;
        }
        
        $_SESSION['admin_last_activity'] = time();
        return true;
    }
    
    public static function isLoggedIn() {
        return isset($_SESSION['admin_logged_in']) && 
               $_SESSION['admin_logged_in'] === true &&
               isset($_SESSION['admin_user_id']) &&
               isset($_SESSION['admin_username']);
    }
    
    public static function requireLogin() {
        if (!self::isLoggedIn()) {
            header('Location: login.php');
            exit;
        }
    }
    
    public static function login($username, $password) {
        // Check login attempts
        $attempts = self::getLoginAttempts();
        if ($attempts >= ADMIN_MAX_LOGIN_ATTEMPTS) {
            $lastAttempt = self::getLastAttemptTime();
            if (time() - $lastAttempt < ADMIN_LOCKOUT_TIME) {
                return ['success' => false, 'message' => 'Terlalu banyak percobaan login. Coba lagi dalam 15 menit.'];
            } else {
                self::resetLoginAttempts();
            }
        }
        
        $user = self::$db->authenticateAdmin($username, $password);
        if ($user) {
            // Reset login attempts
            self::resetLoginAttempts();
            
            // Set session
            $_SESSION['admin_logged_in'] = true;
            $_SESSION['admin_user_id'] = $user['id'];
            $_SESSION['admin_username'] = $user['username'];
            $_SESSION['admin_login_time'] = time();
            
            // Log successful login
            self::logActivity('login_success', $username);
            
            return ['success' => true, 'message' => 'Login berhasil'];
        } else {
            // Increment login attempts
            self::incrementLoginAttempts();
            
            // Log failed login
            self::logActivity('login_failed', $username);
            
            return ['success' => false, 'message' => 'Username atau password salah'];
        }
    }
    
    public static function logout() {
        if (self::isLoggedIn()) {
            self::logActivity('logout', $_SESSION['admin_username'] ?? 'unknown');
        }
        
        // Destroy session
        $_SESSION = array();
        if (isset($_COOKIE[session_name()])) {
            setcookie(session_name(), '', time()-3600, '/');
        }
        session_destroy();
        
        header('Location: login.php');
        exit;
    }
    
    private static function getLoginAttempts() {
        return $_SESSION['admin_login_attempts'] ?? 0;
    }
    
    private static function getLastAttemptTime() {
        return $_SESSION['admin_last_attempt'] ?? 0;
    }
    
    private static function incrementLoginAttempts() {
        $_SESSION['admin_login_attempts'] = self::getLoginAttempts() + 1;
        $_SESSION['admin_last_attempt'] = time();
    }
    
    private static function resetLoginAttempts() {
        unset($_SESSION['admin_login_attempts']);
        unset($_SESSION['admin_last_attempt']);
    }
    
    private static function logActivity($action, $username) {
        try {
            $stmt = self::$db->getConnection()->prepare("
                INSERT INTO admin_activity_log (username, action, ip_address, user_agent, created_at) 
                VALUES (?, ?, ?, ?, NOW())
            ");
            $stmt->execute([
                $username,
                $action,
                $_SERVER['REMOTE_ADDR'] ?? 'unknown',
                $_SERVER['HTTP_USER_AGENT'] ?? 'unknown'
            ]);
        } catch (Exception $e) {
            // Buat tabel jika belum ada
            self::createActivityLogTable();
        }
    }
    
    private static function createActivityLogTable() {
        $sql = "CREATE TABLE IF NOT EXISTS admin_activity_log (
            id INT PRIMARY KEY AUTO_INCREMENT,
            username VARCHAR(100),
            action VARCHAR(50),
            ip_address VARCHAR(45),
            user_agent TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )";
        
        self::$db->getConnection()->exec($sql);
    }
    
    public static function getCurrentAdmin() {
        if (self::isLoggedIn()) {
            return [
                'id' => $_SESSION['admin_user_id'] ?? null,
                'username' => $_SESSION['admin_username'] ?? 'Unknown',
                'login_time' => $_SESSION['admin_login_time'] ?? time()
            ];
        }
        return null;
    }
}

// Initialize admin security
AdminSecurity::init();
?>