<?php
define('ADMIN_ACCESS', true);
require_once 'config.php';
require_once '../includes/database.php';
require_once '../includes/integrated-admin-auth.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 || !isset($adminData['admin_type']) || $adminData['admin_type'] !== 'master') {
    if (!$adminData) {
        session_destroy();
        header('Location: login.php');
    } else {
        die("Access denied. Master Admin required.");
    }
    exit;
}

$db = new Database();

// Site configurations
$sites = [
    'mayortogel' => [
        'name' => 'MAYORTOGEL',
        'table_prefix' => 'live_draw_results_mayortogel',
        'color' => '#dc3545'
    ],
    'yuki585' => [
        'name' => 'YUKI585',
        'table_prefix' => 'live_draw_results_yuki585', 
        'color' => '#28a745'
    ],
    'wajahtoto' => [
        'name' => 'WAJAHTOTO',
        'table_prefix' => 'live_draw_results_wajahtoto',
        'color' => '#007bff'
    ]
];

// Get filter parameters
$selectedDate = $_GET['date'] ?? date('Y-m-d');
$selectedMarket = $_GET['market'] ?? '';
$selectedSite = $_GET['site'] ?? '';

// Get available markets (from all sites combined)
$markets = [];
try {
    // Combine markets from all sites to give Master Admin complete list
    $stmt = $db->getConnection()->query("
        SELECT DISTINCT market_code, market_name, 'all' as source
        FROM (
            SELECT market_code, market_name FROM market_schedules_mayortogel
            UNION 
            SELECT market_code, market_name FROM market_schedules_yuki585
            UNION 
            SELECT market_code, market_name FROM market_schedules_wajahtoto
            UNION
            SELECT market_code, market_name FROM market_schedules
        ) AS combined_markets
        ORDER BY market_name
    ");
    $markets = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // Fallback to mayortogel (most complete)
    try {
        $stmt = $db->getConnection()->query("SELECT DISTINCT market_code, market_name FROM market_schedules_mayortogel ORDER BY market_name");
        $markets = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e2) {
        $markets = [];
    }
}

// Get results data
$allResults = [];
foreach ($sites as $siteKey => $siteInfo) {
    if ($selectedSite && $selectedSite !== $siteKey) continue;
    
    try {
        $tableName = $siteInfo['table_prefix'];
        $whereClause = "WHERE 1=1";
        $params = [];
        
        if ($selectedDate) {
            $whereClause .= " AND draw_date = ?";
            $params[] = $selectedDate;
        }
        
        if ($selectedMarket) {
            $whereClause .= " AND market = ?";
            $params[] = $selectedMarket;
        }
        
        $stmt = $db->getConnection()->prepare("
            SELECT market, result_4d, result_3d, result_2d, draw_date, draw_time, periode, created_at
            FROM $tableName 
            $whereClause 
            ORDER BY draw_date DESC, created_at DESC 
            LIMIT 100
        ");
        $stmt->execute($params);
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $allResults[$siteKey] = $results;
    } catch (Exception $e) {
        $allResults[$siteKey] = [];
    }
}

// Page-specific variables for master header
$pageTitle = $pageTitle ?? 'Master Admin Panel';
$pageDescription = $pageDescription ?? 'Master admin functionality';

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

<!-- Additional Styles for View All Results -->
<style>
.site-card { border-left: 4px solid; margin-bottom: 20px; }
.site-mayortogel { border-left-color: #dc3545 !important; }
.site-yuki585 { border-left-color: #28a745 !important; }
.site-wajahtoto { border-left-color: #007bff !important; }

.result-badge {
    font-family: 'Courier New', monospace;
    font-size: 16px;
    font-weight: bold;
    letter-spacing: 1px;
}

.filter-section {
    background: white;
    border-radius: 10px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
</style>

<!-- Master View All Results Content -->

        <!-- Filters -->
        <div class="filter-section">
            <form method="GET" class="row g-3 align-items-end">
                <div class="col-md-3">
                    <label class="form-label"><strong>Tanggal:</strong></label>
                    <input type="date" name="date" class="form-control" value="<?php echo htmlspecialchars($selectedDate); ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label"><strong>Pasaran:</strong></label>
                    <select name="market" class="form-select">
                        <option value="">Semua Pasaran</option>
                        <?php foreach ($markets as $market): ?>
                        <option value="<?php echo htmlspecialchars($market['market_code']); ?>" 
                                <?php echo $selectedMarket === $market['market_code'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($market['market_name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label"><strong>Situs:</strong></label>
                    <select name="site" class="form-select">
                        <option value="">Semua Situs</option>
                        <?php foreach ($sites as $siteKey => $siteInfo): ?>
                        <option value="<?php echo $siteKey; ?>" <?php echo $selectedSite === $siteKey ? 'selected' : ''; ?>>
                            <?php echo $siteInfo['name']; ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-search"></i> Filter
                    </button>
                </div>
            </form>
        </div>

        <!-- Results Display -->
        <div class="row">
            <?php foreach ($sites as $siteKey => $siteInfo): ?>
                <?php if ($selectedSite && $selectedSite !== $siteKey) continue; ?>
                
                <div class="col-md-4">
                    <div class="card site-card site-<?php echo $siteKey; ?>">
                        <div class="card-header" style="background-color: <?php echo $siteInfo['color']; ?>; color: white;">
                            <h5 class="mb-0">
                                <i class="fas fa-trophy"></i> <?php echo $siteInfo['name']; ?>
                                <span class="badge bg-white text-dark ms-2">
                                    <?php echo count($allResults[$siteKey]); ?> results
                                </span>
                            </h5>
                        </div>
                        <div class="card-body p-0">
                            <?php if (!empty($allResults[$siteKey])): ?>
                                <div style="max-height: 500px; overflow-y: auto;">
                                    <?php foreach ($allResults[$siteKey] as $result): ?>
                                    <div class="border-bottom p-3">
                                        <div class="d-flex justify-content-between align-items-center mb-2">
                                            <strong class="text-primary"><?php echo htmlspecialchars($result['market']); ?></strong>
                                            <small class="text-muted"><?php echo $result['draw_date']; ?></small>
                                        </div>
                                        
                                        <div class="mb-2">
                                            <?php if (!empty($result['result_4d'])): ?>
                                                <span class="badge bg-primary result-badge"><?php echo htmlspecialchars($result['result_4d']); ?></span>
                                                <small class="text-muted ms-1">4D</small>
                                            <?php elseif (!empty($result['result_3d'])): ?>
                                                <span class="badge bg-success result-badge"><?php echo htmlspecialchars($result['result_3d']); ?></span>
                                                <small class="text-muted ms-1">3D</small>
                                            <?php elseif (!empty($result['result_2d'])): ?>
                                                <span class="badge bg-secondary result-badge"><?php echo htmlspecialchars($result['result_2d']); ?></span>
                                                <small class="text-muted ms-1">2D</small>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <div class="d-flex justify-content-between">
                                            <small class="text-muted">
                                                <i class="fas fa-clock"></i> <?php echo $result['draw_time'] ?? '-'; ?>
                                            </small>
                                            <small class="text-muted">
                                                Period: <?php echo $result['periode'] ?? '-'; ?>
                                            </small>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php else: ?>
                                <div class="p-4 text-center text-muted">
                                    <i class="fas fa-inbox fa-3x mb-3"></i>
                                    <p>Tidak ada hasil ditemukan</p>
                                    <?php if ($selectedDate || $selectedMarket): ?>
                                    <small>Coba ubah filter pencarian</small>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- Summary Stats -->
        <div class="row mt-4">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-chart-bar"></i> Statistics Summary</h5>
                    </div>
                    <div class="card-body">
                        <div class="row text-center">
                            <?php foreach ($sites as $siteKey => $siteInfo): ?>
                            <div class="col-md-4">
                                <div class="card border-0" style="background-color: <?php echo $siteInfo['color']; ?>15;">
                                    <div class="card-body">
                                        <h4 style="color: <?php echo $siteInfo['color']; ?>;">
                                            <?php echo count($allResults[$siteKey]); ?>
                                        </h4>
                                        <p class="mb-0"><strong><?php echo $siteInfo['name']; ?></strong></p>
                                        <small class="text-muted">Total Results</small>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="mt-4 text-center">
            <a href="master-multi-result-input.php" class="btn btn-primary btn-lg me-3">
                <i class="fas fa-plus"></i> Input New Results
            </a>
            <a href="dashboard.php" class="btn btn-secondary btn-lg">
                <i class="fas fa-home"></i> Back to Dashboard
            </a>
        </div>

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