<?php
define('ADMIN_ACCESS', true);
require_once 'config.php';
require_once '../includes/database.php';
require_once '../includes/site-manager.php';
require_once '../includes/multi-tenant-auth.php';
require_once '../includes/integrated-admin-auth.php';
require_once '../includes/permission-middleware.php';

// Check integrated authentication
$integratedAuth = new IntegratedAdminAuth();
if (!isset($_SESSION['integrated_admin_session_id'])) {
    header('Location: login.php');
    exit;
}

$adminData = $integratedAuth->validateSession($_SESSION['integrated_admin_session_id']);
if (!$adminData) {
    session_destroy();
    header('Location: login.php');
    exit;
}

// Update session data
$_SESSION['admin_data'] = $adminData;

// Handle logout
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    $integratedAuth->logout($_SESSION['integrated_admin_session_id']);
    session_destroy();
    header('Location: login.php');
    exit;
}

$db = new Database();
$message = '';
$messageType = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $action = $_POST['action'] ?? '';
        
        if ($action === 'update_result') {
            $marketCode = $_POST['market_code'] ?? '';
            $marketName = $_POST['market_name'] ?? '';
            $result4d = $_POST['result_4d'] ?? '';
            $drawDate = $_POST['draw_date'] ?? date('Y-m-d');
            
            // Validate result - check if it's TotoMacau 5D or regular 4D  
            // Improved detection for TotoMacau (support various name formats)
            $marketLower = strtolower($marketName);
            $isTotoMacau5D = (
                (strpos($marketLower, 'totomacau') !== false || 
                 strpos($marketLower, 'toto macau') !== false ||
                 strpos($marketLower, 'macau') !== false) && 
                (strpos($marketLower, '15') !== false || 
                 strpos($marketLower, '21') !== false ||
                 strpos($marketLower, '5d') !== false)
            );
            
            $isValidResult = false;
            if ($isTotoMacau5D) {
                $isValidResult = preg_match('/^\d{5}$/', $result4d); // 5 digit for TotoMacau 5D
            } else {
                $isValidResult = preg_match('/^\d{4}$/', $result4d); // 4 digit for regular markets
            }
            
            if ($isValidResult) {
                // Generate 3D and 2D from result
                if ($isTotoMacau5D) {
                    // For 5D: keep full 5D in result_4d column, extract 3D and 2D from last digits
                    $result4d_toSave = $result4d; // Save full 5D number
                    $result3d = substr($result4d, 2, 3); // Last 3 digits
                    $result2d = substr($result4d, 3, 2); // Last 2 digits
                    error_log("5D Processing - Full: $result4d, 3D: $result3d, 2D: $result2d");
                } else {
                    // For 4D: regular extraction
                    $result4d_toSave = $result4d;
                    $result3d = substr($result4d, 1, 3);
                    $result2d = substr($result4d, 2, 2);
                    error_log("4D Processing - Full: $result4d, 3D: $result3d, 2D: $result2d");
                }
                
                // Check if result already exists for this market and date
                $stmt = $db->getConnection()->prepare("
                    SELECT id FROM " . SiteConfig::getTableName('live_draw_results') . " 
                    WHERE market = ? AND draw_date = ?
                ");
                $stmt->execute([$marketCode, $drawDate]);
                $existingResult = $stmt->fetch();
                
                if ($existingResult) {
                    // Update existing result - try with updated_at first
                    try {
                        $stmt = $db->getConnection()->prepare("
                            UPDATE " . SiteConfig::getTableName('live_draw_results') . " 
                            SET result_4d = ?, result_3d = ?, result_2d = ?, draw_time = CURTIME(), updated_at = NOW()
                            WHERE market = ? AND draw_date = ?
                        ");
                        $stmt->execute([$result4d_toSave, $result3d, $result2d, $marketCode, $drawDate]);
                    } catch (Exception $e) {
                        // Fallback without updated_at if column doesn't exist
                        $stmt = $db->getConnection()->prepare("
                            UPDATE " . SiteConfig::getTableName('live_draw_results') . " 
                            SET result_4d = ?, result_3d = ?, result_2d = ?, draw_time = CURTIME()
                            WHERE market = ? AND draw_date = ?
                        ");
                        $stmt->execute([$result4d_toSave, $result3d, $result2d, $marketCode, $drawDate]);
                    }
                    $message = "Result berhasil diupdate untuk " . ($isTotoMacau5D ? "5D" : "4D") . "!";
                } else {
                    // Insert new result - try with timestamp columns first
                    try {
                        $stmt = $db->getConnection()->prepare("
                            INSERT INTO " . SiteConfig::getTableName('live_draw_results') . " (market, result_4d, result_3d, result_2d, draw_date, draw_time, created_at, updated_at) 
                            VALUES (?, ?, ?, ?, ?, CURTIME(), NOW(), NOW())
                        ");
                        $stmt->execute([$marketCode, $result4d_toSave, $result3d, $result2d, $drawDate]);
                    } catch (Exception $e) {
                        // Fallback to basic columns if timestamp columns don't exist
                        $stmt = $db->getConnection()->prepare("
                            INSERT INTO " . SiteConfig::getTableName('live_draw_results') . " (market, result_4d, result_3d, result_2d, draw_date, draw_time) 
                            VALUES (?, ?, ?, ?, ?, CURTIME())
                        ");
                        $stmt->execute([$marketCode, $result4d_toSave, $result3d, $result2d, $drawDate]);
                    }
                    $message = "Result " . ($isTotoMacau5D ? "5D" : "4D") . " berhasil ditambahkan!";
                }
                $messageType = 'success';
            } else {
                if ($isTotoMacau5D) {
                    $message = "Format result harus 5 digit angka untuk TotoMacau (contoh: 12345)";
                } else {
                    $message = "Format result harus 4 digit angka (contoh: 1234)";
                }
                $messageType = 'error';
            }
        }

        if ($action === 'bulk_update_results') {
            $successCount = 0;
            $errorCount = 0;
            $errors = [];
            $drawDate = $_POST['draw_date'] ?? date('Y-m-d');
            
            foreach ($_POST['markets'] ?? [] as $marketCode => $resultData) {
                $marketName = $resultData['market_name'] ?? '';
                $result4d = trim($resultData['result_4d'] ?? '');
                
                if (empty($result4d)) {
                    continue; // Skip empty results
                }
                
                // Validate result format
                $marketLower = strtolower($marketName);
                $isTotoMacau5D = (
                    (strpos($marketLower, 'totomacau') !== false || 
                     strpos($marketLower, 'toto macau') !== false ||
                     strpos($marketLower, 'macau') !== false) && 
                    (strpos($marketLower, '15') !== false || 
                     strpos($marketLower, '21') !== false ||
                     strpos($marketLower, '5d') !== false)
                );
                
                $isValidResult = false;
                if ($isTotoMacau5D) {
                    $isValidResult = preg_match('/^\d{5}$/', $result4d);
                } else {
                    $isValidResult = preg_match('/^\d{4}$/', $result4d);
                }
                
                if (!$isValidResult) {
                    $errorCount++;
                    $errors[] = "Format result salah untuk {$marketName} ({$marketCode})";
                    continue;
                }
                
                // Generate 3D and 2D from result
                if ($isTotoMacau5D) {
                    $result4d_toSave = $result4d;
                    $result3d = substr($result4d, 2, 3);
                    $result2d = substr($result4d, 3, 2);
                } else {
                    $result4d_toSave = $result4d;
                    $result3d = substr($result4d, 1, 3);
                    $result2d = substr($result4d, 2, 2);
                }
                
                try {
                    // Check if result already exists
                    $stmt = $db->getConnection()->prepare("
                        SELECT id FROM " . SiteConfig::getTableName('live_draw_results') . " 
                        WHERE market = ? AND draw_date = ?
                    ");
                    $stmt->execute([$marketCode, $drawDate]);
                    $existingResult = $stmt->fetch();
                    
                    if ($existingResult) {
                        // Update existing result
                        try {
                            $stmt = $db->getConnection()->prepare("
                                UPDATE " . SiteConfig::getTableName('live_draw_results') . " 
                                SET result_4d = ?, result_3d = ?, result_2d = ?, draw_time = CURTIME(), updated_at = NOW()
                                WHERE market = ? AND draw_date = ?
                            ");
                            $stmt->execute([$result4d_toSave, $result3d, $result2d, $marketCode, $drawDate]);
                        } catch (Exception $e) {
                            $stmt = $db->getConnection()->prepare("
                                UPDATE " . SiteConfig::getTableName('live_draw_results') . " 
                                SET result_4d = ?, result_3d = ?, result_2d = ?, draw_time = CURTIME()
                                WHERE market = ? AND draw_date = ?
                            ");
                            $stmt->execute([$result4d_toSave, $result3d, $result2d, $marketCode, $drawDate]);
                        }
                    } else {
                        // Insert new result
                        try {
                            $stmt = $db->getConnection()->prepare("
                                INSERT INTO " . SiteConfig::getTableName('live_draw_results') . " (market, result_4d, result_3d, result_2d, draw_date, draw_time, created_at, updated_at) 
                                VALUES (?, ?, ?, ?, ?, CURTIME(), NOW(), NOW())
                            ");
                            $stmt->execute([$marketCode, $result4d_toSave, $result3d, $result2d, $drawDate]);
                        } catch (Exception $e) {
                            $stmt = $db->getConnection()->prepare("
                                INSERT INTO " . SiteConfig::getTableName('live_draw_results') . " (market, result_4d, result_3d, result_2d, draw_date, draw_time) 
                                VALUES (?, ?, ?, ?, ?, CURTIME())
                            ");
                            $stmt->execute([$marketCode, $result4d_toSave, $result3d, $result2d, $drawDate]);
                        }
                    }
                    $successCount++;
                } catch (Exception $e) {
                    $errorCount++;
                    $errors[] = "Error untuk {$marketName}: " . $e->getMessage();
                }
            }
            
            if ($successCount > 0) {
                $message = "Berhasil update {$successCount} result!";
                if ($errorCount > 0) {
                    $message .= " ({$errorCount} error: " . implode(', ', array_slice($errors, 0, 3)) . ")";
                }
                $messageType = 'success';
            } else if ($errorCount > 0) {
                $message = "Error: " . implode(', ', $errors);
                $messageType = 'error';
            }
        }
        
        if ($action === 'edit_result') {
            $resultId = (int)$_POST['result_id'];
            $marketCode = $_POST['market_code'] ?? '';
            $marketName = $_POST['market_name'] ?? '';
            $result4d = $_POST['result_4d'] ?? '';
            $drawDate = $_POST['draw_date'] ?? date('Y-m-d');
            
            // Validate result format (same as update_result)
            $marketLower = strtolower($marketName);
            $isTotoMacau5D = (
                (strpos($marketLower, 'totomacau') !== false || 
                 strpos($marketLower, 'toto macau') !== false ||
                 strpos($marketLower, 'macau') !== false) && 
                (strpos($marketLower, '15') !== false || 
                 strpos($marketLower, '21') !== false ||
                 strpos($marketLower, '5d') !== false)
            );
            
            $isValidResult = false;
            if ($isTotoMacau5D) {
                $isValidResult = preg_match('/^\d{5}$/', $result4d);
            } else {
                $isValidResult = preg_match('/^\d{4}$/', $result4d);
            }
            
            if ($isValidResult) {
                // Generate 3D and 2D from result
                if ($isTotoMacau5D) {
                    $result4d_toSave = $result4d;
                    $result3d = substr($result4d, 2, 3);
                    $result2d = substr($result4d, 3, 2);
                } else {
                    $result4d_toSave = $result4d;
                    $result3d = substr($result4d, 1, 3);
                    $result2d = substr($result4d, 2, 2);
                }
                
                try {
                    $stmt = $db->getConnection()->prepare("
                        UPDATE " . SiteConfig::getTableName('live_draw_results') . " 
                        SET market_name = ?, result_4d = ?, result_3d = ?, result_2d = ?, draw_date = ?, draw_time = CURTIME(), updated_at = NOW()
                        WHERE id = ?
                    ");
                    $stmt->execute([$marketName, $result4d_toSave, $result3d, $result2d, $drawDate, $resultId]);
                } catch (Exception $e) {
                    $stmt = $db->getConnection()->prepare("
                        UPDATE " . SiteConfig::getTableName('live_draw_results') . " 
                        SET market_name = ?, result_4d = ?, result_3d = ?, result_2d = ?, draw_date = ?, draw_time = CURTIME()
                        WHERE id = ?
                    ");
                    $stmt->execute([$marketName, $result4d_toSave, $result3d, $result2d, $drawDate, $resultId]);
                }
                $message = "Result berhasil diedit!";
                $messageType = 'success';
            } else {
                if ($isTotoMacau5D) {
                    $message = "Format result harus 5 digit angka untuk TotoMacau (contoh: 12345)";
                } else {
                    $message = "Format result harus 4 digit angka (contoh: 1234)";
                }
                $messageType = 'error';
            }
        }

        if ($action === 'delete_result') {
            $resultId = (int)$_POST['result_id'];
            $stmt = $db->getConnection()->prepare("DELETE FROM " . SiteConfig::getTableName('live_draw_results') . " WHERE id = ?");
            $stmt->execute([$resultId]);
            $message = "Result berhasil dihapus!";
            $messageType = 'success';
        }
        
    } catch (Exception $e) {
        $message = "Error: " . $e->getMessage();
        $messageType = 'error';
    }
}

// Get markets for dropdown
$markets = $db->getMarketSchedules();

// Auto-insert missing results from yesterday, then check today's missing
$today = date('Y-m-d');
$yesterday = date('Y-m-d', strtotime('-1 day'));
$todayMissingMarkets = [];
$autoInsertedCount = 0;

try {
    // Get all active markets
    $stmt = $db->getConnection()->prepare("
        SELECT market_code, market_name, logo_path 
        FROM market_schedules 
        WHERE is_active = 1 
        ORDER BY market_name
    ");
    $stmt->execute();
    $allMarkets = $stmt->fetchAll();
    
    // AUTO-INSERT: Check and auto-insert missing results from YESTERDAY
    $yesterdayDayOfWeek = date('w', strtotime($yesterday));
    
    // Get markets that already have results yesterday
    $stmt = $db->getConnection()->prepare("
        SELECT DISTINCT market_code 
        FROM " . SiteConfig::getTableName('live_draw_results') . " 
        WHERE draw_date = ?
    ");
    $stmt->execute([$yesterday]);
    $yesterdayMarketsWithResults = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    // Auto-insert missing results from yesterday
    foreach ($allMarkets as $market) {
        $marketCode = $market['market_code'];
        $marketName = $market['market_name'];
        
        // Skip Singapore on weekends (Saturday = 6, Sunday = 0)
        if (strtoupper($marketCode) === 'SGP' && ($yesterdayDayOfWeek == 0 || $yesterdayDayOfWeek == 6)) {
            continue;
        }
        
        // Check if this market doesn't have result yesterday - AUTO INSERT
        if (!in_array($marketCode, $yesterdayMarketsWithResults)) {
            try {
                // Double-check to avoid duplicates
                $stmt = $db->getConnection()->prepare("
                    SELECT id FROM " . SiteConfig::getTableName('live_draw_results') . " 
                    WHERE market = ? AND draw_date = ?
                ");
                $stmt->execute([$marketCode, $yesterday]);
                $existingResult = $stmt->fetch();
                
                if (!$existingResult) {
                    // Auto-insert blank/empty result for yesterday (NULL values)
                    try {
                        $stmt = $db->getConnection()->prepare("
                            INSERT INTO " . SiteConfig::getTableName('live_draw_results') . " (market, result_4d, result_3d, result_2d, draw_date, draw_time, created_at, updated_at) 
                            VALUES (?, NULL, NULL, NULL, ?, '00:00:00', NOW(), NOW())
                        ");
                        $stmt->execute([$marketCode, $yesterday]);
                    } catch (Exception $e) {
                        $stmt = $db->getConnection()->prepare("
                            INSERT INTO " . SiteConfig::getTableName('live_draw_results') . " (market, result_4d, result_3d, result_2d, draw_date, draw_time) 
                            VALUES (?, NULL, NULL, NULL, ?, '00:00:00')
                        ");
                        $stmt->execute([$marketCode, $yesterday]);
                    }
                    $autoInsertedCount++;
                }
            } catch (Exception $e) {
                error_log("Error auto-inserting for {$marketCode} on {$yesterday}: " . $e->getMessage());
            }
        }
    }
    
    // NOW CHECK: Missing results for TODAY only  
    $todayDayOfWeek = date('w');
    
    // Get markets that already have results today
    $stmt = $db->getConnection()->prepare("
        SELECT DISTINCT market_code 
        FROM " . SiteConfig::getTableName('live_draw_results') . " 
        WHERE draw_date = ?
    ");
    $stmt->execute([$today]);
    $todayMarketsWithResults = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    // Check which markets are missing TODAY
    foreach ($allMarkets as $market) {
        $marketCode = $market['market_code'];
        
        // Skip Singapore on weekends (Saturday = 6, Sunday = 0)
        if (strtoupper($marketCode) === 'SGP' && ($todayDayOfWeek == 0 || $todayDayOfWeek == 6)) {
            continue;
        }
        
        // Check if this market doesn't have result today
        if (!in_array($marketCode, $todayMarketsWithResults)) {
            $todayMissingMarkets[] = $market;
        }
    }
} catch (Exception $e) {
    error_log("Error in auto-insert and missing check: " . $e->getMessage());
    $todayMissingMarkets = [];
    $autoInsertedCount = 0;
}

// Pagination parameters
$page = max(1, (int)($_GET['page'] ?? 1));
$itemsPerPage = 20;
$offset = ($page - 1) * $itemsPerPage;

// Get recent results with pagination
$recentResults = [];
$totalItems = 0;
$totalPages = 1;

try {
    // Get total count
    $countStmt = $db->getConnection()->prepare("SELECT COUNT(*) FROM " . SiteConfig::getTableName('live_draw_results') . "");
    $countStmt->execute();
    $totalItems = $countStmt->fetchColumn();
    $totalPages = ceil($totalItems / $itemsPerPage);
    
    // Get paginated results
    $stmt = $db->getConnection()->prepare("
        SELECT r.*, m.logo_path, m.market_name, m.market_code as market_code_schedule
        FROM " . SiteConfig::getTableName('live_draw_results') . " r 
        LEFT JOIN " . SiteConfig::getTableName('market_schedules') . " m ON r.market = m.market_code 
        ORDER BY r.updated_at DESC, r.created_at DESC, r.draw_date DESC, r.id DESC
        LIMIT ? OFFSET ?
    ");
    $stmt->execute([$itemsPerPage, $offset]);
    $recentResults = $stmt->fetchAll();
} catch (Exception $e) {
    // Fallback query if timestamp columns don't exist
    try {
        // Get total count
        $countStmt = $db->getConnection()->prepare("SELECT COUNT(*) FROM " . SiteConfig::getTableName('live_draw_results') . "");
        $countStmt->execute();
        $totalItems = $countStmt->fetchColumn();
        $totalPages = ceil($totalItems / $itemsPerPage);
        
        $stmt = $db->getConnection()->prepare("
            SELECT r.*, m.logo_path 
            FROM " . SiteConfig::getTableName('live_draw_results') . " r 
            LEFT JOIN market_schedules m ON r.market_code = m.market_code 
            ORDER BY r.draw_date DESC, r.id DESC
            LIMIT ? OFFSET ?
        ");
        $stmt->execute([$itemsPerPage, $offset]);
        $recentResults = $stmt->fetchAll();
    } catch (Exception $e2) {
        $recentResults = [];
        error_log("Error fetching recent results: " . $e2->getMessage());
    }
}
?>

<?php
// Include unified header
include 'admin-sidebar-template.php';
?>

<div class="admin-container">
    <?php if ($message): ?>
        <div class="alert alert-<?php echo $messageType === 'success' ? 'success' : 'danger'; ?> alert-dismissible fade show" role="alert">
            <i class="bi bi-<?php echo $messageType === 'success' ? 'check-circle' : 'exclamation-triangle'; ?> me-2"></i>
            <?php echo htmlspecialchars($message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Auto-Insert Status & Today's Missing Results -->
    <?php if ($autoInsertedCount > 0): ?>
    <div class="alert alert-info alert-dismissible fade show" role="alert">
        <i class="bi bi-stars me-2"></i>
        Sistem otomatis menambahkan <?php echo $autoInsertedCount; ?> entry kosong (blank) untuk tanggal kemarin (<?php echo date('d/m/Y', strtotime($yesterday)); ?>). 
        Silakan cari entry bertuliskan "KOSONG - Perlu Diisi" di tabel Recent Results untuk mengisi angka yang benar.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>

    <!-- Add/Update Result Form -->
    <div class="card mb-4">
        <div class="card-header">
            <h5 class="card-title mb-0">
                <i class="fas fa-plus-circle me-2"></i>
                Update Result Live Draw (Manual)
            </h5>
        </div>
        <div class="card-body">
            <form method="POST">
                <input type="hidden" name="action" value="update_result">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label for="market_code" class="form-label">Market / Pasaran</label>
                        <select name="market_code" id="market_code" class="form-select" required onchange="updateMarketName(); updateResultFormat();">
                            <option value="">Pilih Market</option>
                            <?php foreach ($markets as $market): 
                                $marketName = strtolower($market['market_name']);
                                $is5D = (strpos($marketName, 'totomacau') !== false && 
                                        (strpos($marketName, '15') !== false || strpos($marketName, '21') !== false)) ||
                                       strpos($marketName, '5d') !== false;
                            ?>
                                <option value="<?php echo $market['market_code']; ?>" 
                                        data-name="<?php echo htmlspecialchars($market['market_name']); ?>"
                                        data-is5d="<?php echo $is5D ? '1' : '0'; ?>">
                                    <?php echo htmlspecialchars($market['market_name']); ?>
                                    <?php if ($is5D): ?> [5D]<?php endif; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <input type="hidden" name="market_name" id="market_name">
                    </div>
                    <div class="col-md-4">
                        <label for="result_4d" id="result_label" class="form-label">Result 4D</label>
                        <input type="text" name="result_4d" id="result_4d" class="form-control"
                               placeholder="contoh: 1234" maxlength="4" 
                               pattern="\d{4}" required>
                        <small id="result_help" class="form-text text-muted">Format: 4 digit angka untuk pasaran reguler, 5 digit untuk TotoMacau 15/21</small>
                    </div>
                    <div class="col-md-4">
                        <label for="draw_date" class="form-label">Tanggal Draw</label>
                        <input type="date" name="draw_date" id="draw_date" class="form-control"
                               value="<?php echo date('Y-m-d'); ?>" required>
                    </div>
                </div>
                <div class="mt-3">
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-plus-circle me-2"></i>
                        Update Result
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Recent Results -->
    <div class="card">
        <div class="card-header">
            <h5 class="card-title mb-0">
                <i class="bi bi-arrow-clockwise me-2"></i>
                Recent Results (<?php echo count($recentResults); ?> dari <?php echo $totalItems; ?> total)
            </h5>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Market</th>
                            <th>Result</th>
                            <th>Waktu Draw</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($recentResults)): ?>
                            <tr>
                                <td colspan="4" class="text-center text-muted py-4">
                                    <i class="bi bi-inbox fs-2 d-block mb-2"></i>
                                    Belum ada hasil live draw
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($recentResults as $result): ?>
                                <tr>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <?php if (!empty($result['logo_path']) && file_exists('../' . $result['logo_path'])): ?>
                                                <img src="../<?php echo $result['logo_path']; ?>" 
                                                     alt="<?php echo htmlspecialchars($result['market_name'] ?? $result['market']); ?>" 
                                                     class="me-2" style="width: 40px; height: 25px; object-fit: contain; border-radius: 4px;">
                                            <?php endif; ?>
                                            <div>
                                                <div class="fw-semibold"><?php 
                                    // Display market name, fallback to proper name if empty
                                    $displayName = trim($result['market_name'] ?? '');
                                    if (empty($displayName)) {
                                        // Use proper names for common market codes
                                        switch(strtoupper($result['market'])) {
                                            case 'TWN': $displayName = 'Taiwan'; break;
                                            case 'SGP': $displayName = 'Singapore'; break;
                                            case 'HK': $displayName = 'Hongkong'; break;
                                            case 'SDY': $displayName = 'Sydney'; break;
                                            case 'JKT': $displayName = 'Jakarta'; break;
                                            case 'CHN': $displayName = 'China'; break;
                                            case 'CMD': $displayName = 'Cambodia'; break;
                                            default: $displayName = strtoupper($result['market']);
                                        }
                                    }
                                    echo htmlspecialchars($displayName); 
                                ?></div>
                                <small class="text-muted"><?php echo $result['market']; ?></small>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="result-digits">
                                            <?php 
                                            // Check if this is TotoMacau 5D for proper display
                                            $marketName = strtolower($result['market_name'] ?? '');
                                            $isTotoMacau5D = (
                                                (strpos($marketName, 'totomacau') !== false || 
                                                 strpos($marketName, 'toto macau') !== false ||
                                                 strpos($marketName, 'macau') !== false) && 
                                                (strpos($marketName, '15') !== false || 
                                                 strpos($marketName, '21') !== false ||
                                                 strpos($marketName, '5d') !== false)
                                            );
                                            
                                            $resultToDisplay = $result['result_4d'];
                                            $isEmpty = (empty($result['result_4d']) || $result['result_4d'] === null || $result['result_4d'] === '' || $result['result_4d'] === '0000' || $result['result_4d'] === '00000');
                                            
                                            if ($isEmpty): ?>
                                                <span class="badge bg-danger d-inline-flex align-items-center gap-2">
                                                    <i class="bi bi-exclamation-circle"></i>
                                                    KOSONG - Perlu Diisi
                                                </span>
                                            <?php else:
                                                // For TotoMacau 5D, if only 4 digits stored, pad with 0
                                                if ($isTotoMacau5D && strlen($resultToDisplay) == 4) {
                                                    $resultToDisplay = '0' . $resultToDisplay;
                                                }
                                                
                                                $digits = str_split($resultToDisplay);
                                                echo '<div class="d-flex gap-1">';
                                                foreach ($digits as $digit): 
                                                ?>
                                                    <span class="badge bg-warning text-dark rounded-circle d-flex align-items-center justify-content-center" style="width: 30px; height: 30px; font-weight: bold;"><?php echo $digit; ?></span>
                                                <?php endforeach;
                                                echo '</div>'; ?>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="fw-semibold"><?php echo date('d/m/Y', strtotime($result['draw_date'])); ?></div>
                                        <small class="text-muted"><?php echo date('H:i', strtotime($result['draw_time'])); ?></small>
                                    </td>
                                    <td class="text-nowrap">
                                        <div class="btn-group" role="group">
                                            <button class="btn btn-sm btn-primary px-2" 
                                                    onclick="editResult(<?php echo $result['id']; ?>, '<?php echo $result['market']; ?>', '<?php echo htmlspecialchars($result['market_name'] ?? $result['market'], ENT_QUOTES); ?>', <?php echo ($result['result_4d'] === null || $result['result_4d'] === '') ? 'null' : "'" . $result['result_4d'] . "'"; ?>, '<?php echo $result['draw_date']; ?>')"
                                                    title="Edit Result">
                                                <i class="bi bi-pencil-square"></i>
                                            </button>
                                            <form method="POST" class="d-inline" 
                                                  onsubmit="return confirm('Yakin ingin hapus result ini?')">
                                                <input type="hidden" name="action" value="delete_result">
                                                <input type="hidden" name="result_id" value="<?php echo $result['id']; ?>">
                                                <button type="submit" class="btn btn-sm btn-danger px-2" title="Hapus Result">
                                                    <i class="bi bi-trash3"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

        </div>
        
        <!-- Pagination -->
        <?php if ($totalPages > 1): ?>
        <div class="card-footer">
            <nav aria-label="Page navigation">
                <ul class="pagination pagination-sm justify-content-center mb-0">
                    <?php if ($page > 1): ?>
                        <li class="page-item">
                            <a href="?page=<?php echo ($page - 1); ?>" class="page-link">
                                <i class="fas fa-chevron-left"></i> Prev
                            </a>
                        </li>
                    <?php endif; ?>
                    
                    <?php
                    // Mobile-friendly pagination: max 5 numbers
                    $startPage = max(1, $page - 2);
                    $endPage = min($totalPages, $page + 2);
                    
                    if ($startPage > 1): ?>
                        <li class="page-item">
                            <a href="?page=1" class="page-link">1</a>
                        </li>
                        <?php if ($startPage > 2): ?>
                            <li class="page-item disabled">
                                <span class="page-link">...</span>
                            </li>
                        <?php endif; ?>
                    <?php endif; ?>
                    
                    <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
                        <li class="page-item <?php echo ($i === $page) ? 'active' : ''; ?>">
                            <a href="?page=<?php echo $i; ?>" class="page-link">
                                <?php echo $i; ?>
                            </a>
                        </li>
                    <?php endfor; ?>
                    
                    <?php if ($endPage < $totalPages): ?>
                        <?php if ($endPage < $totalPages - 1): ?>
                            <li class="page-item disabled">
                                <span class="page-link">...</span>
                            </li>
                        <?php endif; ?>
                        <li class="page-item">
                            <a href="?page=<?php echo $totalPages; ?>" class="page-link"><?php echo $totalPages; ?></a>
                        </li>
                    <?php endif; ?>
                    
                    <?php if ($page < $totalPages): ?>
                        <li class="page-item">
                            <a href="?page=<?php echo ($page + 1); ?>" class="page-link">
                                Next <i class="fas fa-chevron-right"></i>
                            </a>
                        </li>
                    <?php endif; ?>
                </ul>
            </nav>
            
            <div class="text-center mt-2">
                <small class="text-muted">
                    Halaman <?php echo $page; ?> dari <?php echo $totalPages; ?> 
                    (<?php echo $totalItems; ?> total results, menampilkan <?php echo count($recentResults); ?> results)
                </small>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Edit Result Modal -->
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-pencil-square me-2"></i>
                    Edit Result
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form method="POST" id="editForm">
                    <input type="hidden" name="action" value="edit_result">
                    <input type="hidden" name="result_id" id="edit_result_id">
                    <input type="hidden" name="market_code" id="edit_market_code">
                    <input type="hidden" name="market_name" id="edit_market_name">
                    
                    <div class="mb-3">
                        <label class="form-label">Market</label>
                        <div id="edit_market_display" class="form-control-plaintext fw-semibold"></div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit_result_4d" class="form-label" id="edit_result_label">Result</label>
                        <input type="text" name="result_4d" id="edit_result_4d" class="form-control"
                               placeholder="1234" maxlength="4" pattern="\d{4}" required>
                        <small id="edit_result_help" class="form-text text-muted">Format: 4 digit angka</small>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit_draw_date" class="form-label">Tanggal Draw</label>
                        <input type="date" name="draw_date" id="edit_draw_date" class="form-control" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="bi bi-x-lg me-2"></i>Batal
                </button>
                <button type="submit" form="editForm" class="btn btn-success">
                    <i class="bi bi-check-lg me-2"></i>Update Result
                </button>
            </div>
        </div>
    </div>
</div>

    <script>
        // Edit result functionality
        function editResult(id, marketCode, marketName, result4d, drawDate) {
            document.getElementById('edit_result_id').value = id;
            document.getElementById('edit_market_code').value = marketCode;
            document.getElementById('edit_market_name').value = marketName;
            
            // Handle empty/null results
            const displayResult = (result4d === null || result4d === 'null' || result4d === '' || result4d === undefined) ? '' : result4d;
            document.getElementById('edit_result_4d').value = displayResult;
            
            document.getElementById('edit_draw_date').value = drawDate;
            document.getElementById('edit_market_display').textContent = marketName + ' (' + marketCode + ')';
            
            // Check if it's TotoMacau 5D
            const marketLower = marketName.toLowerCase();
            const is5D = (marketLower.includes('totomacau') || marketLower.includes('toto macau') || marketLower.includes('macau')) && 
                        (marketLower.includes('15') || marketLower.includes('21') || marketLower.includes('5d'));
            
            const resultInput = document.getElementById('edit_result_4d');
            const resultLabel = document.getElementById('edit_result_label');
            const resultHelp = document.getElementById('edit_result_help');
            
            if (is5D) {
                resultInput.maxLength = 5;
                resultInput.setAttribute('maxlength', '5');
                resultInput.setAttribute('pattern', '\\d{5}');
                resultInput.placeholder = '12345';
                resultLabel.textContent = 'Result 5D';
                resultHelp.textContent = 'Format: 5 digit angka untuk TotoMacau 5D';
            } else {
                resultInput.maxLength = 4;
                resultInput.setAttribute('maxlength', '4');
                resultInput.setAttribute('pattern', '\\d{4}');
                resultInput.placeholder = '1234';
                resultLabel.textContent = 'Result 4D';
                resultHelp.textContent = 'Format: 4 digit angka untuk pasaran reguler';
            }
            
            // Show Bootstrap modal
            const editModal = new bootstrap.Modal(document.getElementById('editModal'));
            editModal.show();
            
            // Focus on input if empty
            if (displayResult === '') {
                setTimeout(() => resultInput.focus(), 300);
            }
        }
        
        // Auto-format result input in edit modal
        document.getElementById('edit_result_4d').addEventListener('input', function(e) {
            const marketName = document.getElementById('edit_market_name').value.toLowerCase();
            const is5D = (marketName.includes('totomacau') || marketName.includes('toto macau') || marketName.includes('macau')) && 
                        (marketName.includes('15') || marketName.includes('21') || marketName.includes('5d'));
            const maxLength = is5D ? 5 : 4;
            
            let value = e.target.value.replace(/\D/g, '');
            
            if (value.length > maxLength) {
                value = value.substring(0, maxLength);
            }
            e.target.value = value;
        });

        // Update market name when dropdown changes
        function updateMarketName() {
            const select = document.getElementById('market_code');
            const hiddenInput = document.getElementById('market_name');
            const selectedOption = select.options[select.selectedIndex];
            if (selectedOption && selectedOption.value) {
                hiddenInput.value = selectedOption.getAttribute('data-name');
            } else {
                hiddenInput.value = '';
            }
        }

        // Set market_name and result format on page load
        window.addEventListener('DOMContentLoaded', function() {
            updateMarketName();
            
            // Try multiple times to ensure it works
            setTimeout(updateResultFormat, 100);
            setTimeout(updateResultFormat, 500);
            setTimeout(updateResultFormat, 1000);
        });

        // Force check every time market changes
        setInterval(function() {
            const marketSelect = document.getElementById('market_code');
            if (marketSelect && marketSelect.selectedIndex > 0) {
                // Auto-update format if market is selected
                updateResultFormat();
            }
        }, 2000); // Check every 2 seconds

        // Update result input format based on market selection
        function updateResultFormat() {
            const marketSelect = document.getElementById('market_code');
            const resultInput = document.getElementById('result_4d');
            const resultLabel = document.getElementById('result_label');
            const resultHelp = document.getElementById('result_help');
            
            if (!marketSelect || !resultInput) {
                return;
            }
            
            const selectedIndex = marketSelect.selectedIndex;
            const selectedOption = marketSelect.options[selectedIndex];
            
            if (!selectedOption || selectedIndex === 0) {
                return;
            }
            
            const marketName = selectedOption.textContent.trim();
            const dataIs5D = selectedOption.getAttribute('data-is5d');
            const is5D = dataIs5D === '1';
            
            if (is5D) {
                resultInput.maxLength = 5;
                resultInput.setAttribute('maxlength', '5');
                resultInput.setAttribute('pattern', '\\d{5}');
                resultInput.placeholder = 'contoh: 12345';
                if (resultLabel) resultLabel.textContent = 'Result 5D';
                if (resultHelp) resultHelp.textContent = 'Format: 5 digit angka untuk TotoMacau 5D';
            } else {
                resultInput.maxLength = 4;
                resultInput.setAttribute('maxlength', '4');
                resultInput.setAttribute('pattern', '\\d{4}');
                resultInput.placeholder = 'contoh: 1234';
                if (resultLabel) resultLabel.textContent = 'Result 4D';
                if (resultHelp) resultHelp.textContent = 'Format: 4 digit angka untuk pasaran reguler';
            }
        }

        // Auto-format result input based on market type
        document.getElementById('result_4d').addEventListener('input', function(e) {
            const marketSelect = document.getElementById('market_code');
            const selectedOption = marketSelect.options[marketSelect.selectedIndex];
            
            // Use data attribute for consistent detection
            const is5D = selectedOption && selectedOption.getAttribute('data-is5d') === '1';
            const maxLength = is5D ? 5 : 4;
            
            let value = e.target.value.replace(/\D/g, '');
            
            if (value.length > maxLength) {
                value = value.substring(0, maxLength);
            }
            e.target.value = value;
        });

        // Update format when market selection changes
        document.getElementById('market_code').addEventListener('change', function() {
            updateMarketName();
            updateResultFormat();
            document.getElementById('result_4d').value = ''; // Clear previous input
            
            // Force update after a short delay to ensure DOM is updated
            setTimeout(function() {
                updateResultFormat();
            }, 100);
        });

        // Also listen to click event as backup
        document.getElementById('market_code').addEventListener('click', function() {
            setTimeout(function() {
                updateResultFormat();
            }, 50);
        });

        // Form animation
        document.addEventListener('DOMContentLoaded', function() {
            const formSections = document.querySelectorAll('.form-section, .results-table');
            formSections.forEach((section, index) => {
                section.style.opacity = '0';
                section.style.transform = 'translateY(20px)';
                
                setTimeout(() => {
                    section.style.transition = 'all 0.6s ease';
                    section.style.opacity = '1';
                    section.style.transform = 'translateY(0)';
                }, index * 150);
            });
        });
    </script>
</div>

<?php include __DIR__ . '/admin-sidebar-footer.php'; ?>