<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
date_default_timezone_set('Asia/Jakarta'); // Di config.php// Konfigurasi Database
define('DB_HOST', 'localhost');
define('DB_NAME', 'erniinrk_bekasi');
define('DB_USER', 'erniinrk_bekasi');
define('DB_PASS', 'Kelentit123@');

// Koneksi PDO
try {
    $db = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Koneksi database gagal: " . $e->getMessage());
}

// Fungsi untuk redirect
function redirect($url) {
    header("Location: $url");
    exit();
}


// Fungsi untuk cek login
function checkLogin() {
    if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
        header('Location: login.php');
        exit;
    }
}
function logAdminActivity($action, $details = null) {
    global $db;
    
    try {
        $admin_id = $_SESSION['admin_id'] ?? 0;
        $admin_username = $_SESSION['username'] ?? 'Unknown';
        $ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
        $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        
        $stmt = $db->prepare("INSERT INTO admin_activity_logs 
                            (admin_id, admin_username, action, details, ip_address, user_agent) 
                            VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$admin_id, $admin_username, $action, $details, $ip_address, $user_agent]);
        return true;
    } catch (Exception $e) {
        error_log("Error logging admin activity: " . $e->getMessage());
        return false;
    }
}

// Fungsi untuk sanitasi input
function sanitizeInput($data) {
    return htmlspecialchars(strip_tags(trim($data)));
}

// Function to format date
function formatDate($date) {
    return date('Y-m-d', strtotime($date));
}

// Function to check if it's result time
function isResultTime($result_time_start, $result_time_end) {
    $currentTime = date('H:i');
    return ($currentTime >= $result_time_start && $currentTime <= $result_time_end);
}
// Fungsi untuk mengecek apakah sedang dalam waktu generate
function isAutoGenerateTime($market_name) {
    global $db;
    
    $stmt = $db->prepare("SELECT auto_generate_start, auto_generate_end, auto_generate_active 
                         FROM markets WHERE market_name = ?");
    $stmt->execute([$market_name]);
    $market = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$market) return false;
    
    $now = new DateTime();
    $start = new DateTime($now->format('Y-m-d') . ' ' . $market['auto_generate_start']);
    $end = new DateTime($now->format('Y-m-d') . ' ' . $market['auto_generate_end']);
    
    // Handle jika melewati midnight
    if ($end < $start) {
        $end->modify('+1 day');
    }
    
    return ($now >= $start && $now <= $end) || $market['auto_generate_active'];
}

// Fungsi untuk mendapatkan nomor draw berikutnya
function getNextDrawNumber($market_id) {
    global $db;
    
    $stmt = $db->prepare("SELECT MAX(draw_number) FROM lottery_results WHERE market_id = ?");
    $stmt->execute([$market_id]);
    $last_number = $stmt->fetchColumn();
    
    return $last_number ? $last_number + 1 : 1;
}
function updateMarketTimesCache() {
    global $db;
    
    try {
        $stmt = $db->prepare("SELECT market_name, result_time, result_end_time FROM markets");
        $stmt->execute();
        $markets = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $cache_data = [
            'timestamp' => time(),
            'markets' => $markets
        ];
        
        // Pastikan folder cache ada
        if (!file_exists(__DIR__ . '/cache')) {
            mkdir(__DIR__ . '/cache', 0755, true);
        }
        
        file_put_contents(__DIR__ . '/cache/market_times.json', json_encode($cache_data));
        return true;
    } catch (Exception $e) {
        error_log("Error updating cache: " . $e->getMessage());
        return false;
    }
}