<?php
define('ADMIN_ACCESS', true);
require_once 'config.php';
require_once '../includes/database.php';
require_once '../includes/site-manager.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',
        'database' => 'autoprediksi', 
        'table_prefix' => 'live_draw_results_mayortogel',
        'color' => '#dc3545'
    ],
    'yuki585' => [
        'name' => 'YUKI585',
        'database' => 'autoprediksi',
        'table_prefix' => 'live_draw_results_yuki585', 
        'color' => '#28a745'
    ],
    'wajahtoto' => [
        'name' => 'WAJAHTOTO',
        'database' => 'autoprediksi',
        'table_prefix' => 'live_draw_results_wajahtoto',
        'color' => '#007bff'
    ]
];

// Handle form submission
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'multi_result_input') {
    try {
        $market = $_POST['market'] ?? '';
        $resultDate = $_POST['result_date'] ?? date('Y-m-d');
        $resultTime = date('H:i:s'); // Auto generate current time
        $periode = date('Hi'); // Auto generate periode from current time (HHMM format)
        
        // Get results for each site
        $results = [
            'mayortogel' => trim($_POST['result_mayortogel'] ?? ''),
            'yuki585' => trim($_POST['result_yuki585'] ?? ''),
            'wajahtoto' => trim($_POST['result_wajahtoto'] ?? '')
        ];
        
        $updatedSites = [];
        $errors = [];
        
        // Process each site that has result data
        foreach ($results as $siteKey => $result) {
            
            if (!empty($result)) {
                try {
                    $tableName = $sites[$siteKey]['table_prefix'];
                    
                    // Check if result already exists
                    $checkStmt = $db->getConnection()->prepare("
                        SELECT id FROM $tableName 
                        WHERE market = ? AND draw_date = ? AND periode = ?
                    ");
                    $checkStmt->execute([$market, $resultDate, $periode]);
                    
                    if ($checkStmt->fetch()) {
                        // Update existing result
                        $updateStmt = $db->getConnection()->prepare("
                            UPDATE $tableName 
                            SET result_4d = ?, draw_time = ?, updated_at = NOW()
                            WHERE market = ? AND draw_date = ? AND periode = ?
                        ");
                        $updateStmt->execute([$result, $resultTime, $market, $resultDate, $periode]);
                        $updatedSites[] = $sites[$siteKey]['name'] . " (Updated)";
                    } else {
                        // Insert new result
                        $insertStmt = $db->getConnection()->prepare("
                            INSERT INTO $tableName 
                            (market, result_4d, draw_date, draw_time, periode, created_at) 
                            VALUES (?, ?, ?, ?, ?, NOW())
                        ");
                        $insertStmt->execute([$market, $result, $resultDate, $resultTime, $periode]);
                        $updatedSites[] = $sites[$siteKey]['name'] . " (Added)";
                    }
                } catch (Exception $e) {
                    $errors[] = $sites[$siteKey]['name'] . ": " . $e->getMessage();
                }
            }
        }
        
        if (!empty($updatedSites)) {
            $message = "✅ Results berhasil disimpan ke: " . implode(', ', $updatedSites);
            $messageType = 'success';
            
            if (!empty($errors)) {
                $message .= "<br>⚠️ Errors: " . implode(', ', $errors);
            }
        } else {
            $message = "❌ Tidak ada result yang diinput. Minimal isi 1 kolom site.";
            $messageType = 'error';
        }
        
    } catch (Exception $e) {
        $message = "❌ Error: " . $e->getMessage();
        $messageType = 'error';
    }
}

// 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 recent results for display
$recentResults = [];
try {
    foreach ($sites as $siteKey => $siteInfo) {
        $tableName = $siteInfo['table_prefix'];
        $stmt = $db->getConnection()->prepare("
            SELECT market, result_4d, draw_date, draw_time, periode, created_at 
            FROM $tableName 
            ORDER BY created_at DESC 
            LIMIT 5
        ");
        $stmt->execute();
        $recentResults[$siteKey] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Exception $e) {
    // Handle error silently
}

// 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 Multi Site Result -->
<style>
.site-column {
    border: 2px solid #dee2e6;
    border-radius: 10px;
    padding: 15px;
    margin: 5px;
    min-height: 120px;
}
.site-mayortogel { border-color: #dc3545; background: #fff5f5; }
.site-yuki585 { border-color: #28a745; background: #f5fff5; }
.site-wajahtoto { border-color: #007bff; background: #f5f9ff; }

.site-header {
    font-weight: bold;
    font-size: 16px;
    margin-bottom: 10px;
    text-align: center;
}

.result-input {
    font-size: 18px;
    font-weight: bold;
    text-align: center;
    letter-spacing: 2px;
}

.recent-results {
    max-height: 200px;
    overflow-y: auto;
    font-size: 12px;
}

.submit-section {
    background: #f8f9fa;
    border: 2px solid #e9ecef;
    border-radius: 10px;
    padding: 20px;
    margin-top: 20px;
}
</style>

<!-- Master Multi Site Result Input Content -->
<!-- Alert Messages -->
<?php if ($message): ?>
<div class="alert alert-<?php echo $messageType === 'success' ? 'success' : 'danger'; ?> alert-dismissible fade show">
    <strong><?php echo $messageType === 'success' ? 'Sukses!' : 'Error!'; ?></strong>
    <?php echo $message; ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>



<!-- Main Form -->
        <form method="POST" class="mb-4">
            <input type="hidden" name="action" value="multi_result_input">
            
            <!-- Market and Date Selection -->
            <div class="row mb-4">
                <div class="col-md-6">
                    <label class="form-label"><strong>Pasaran:</strong></label>
                    <select name="market" class="form-select" required>
                        <option value="">Pilih Pasaran</option>
                        <?php foreach ($markets as $market): ?>
                        <option value="<?php echo htmlspecialchars($market['market_code']); ?>">
                            <?php echo htmlspecialchars($market['market_name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label"><strong>Tanggal:</strong></label>
                    <input type="date" name="result_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                    <small class="text-muted">Jam dan periode akan otomatis digenerate saat input</small>
                </div>
            </div>

            <!-- Site Result Columns -->
            <div class="row">
                <div class="col-md-12">
                    <h4><i class="fas fa-columns"></i> Input Result per Situs</h4>
                    <p class="text-muted">Isi kolom sesuai situs yang ingin diupdate. Kosongkan jika tidak ingin mengupdate situs tersebut.</p>
                </div>
            </div>

            <div class="row">
                <!-- Mayortogel Column -->
                <div class="col-md-4">
                    <div class="site-column site-mayortogel">
                        <div class="site-header" style="color: #dc3545;">
                            <i class="fas fa-trophy"></i> MAYORTOGEL
                        </div>
                        <input type="text" 
                               name="result_mayortogel" 
                               class="form-control result-input" 
                               placeholder="Contoh: 1234"
                               pattern="[0-9]*"
                               maxlength="5">
                        <small class="text-muted">Kosongkan jika tidak ingin update</small>
                    </div>
                </div>

                <!-- Yuki585 Column -->
                <div class="col-md-4">
                    <div class="site-column site-yuki585">
                        <div class="site-header" style="color: #28a745;">
                            <i class="fas fa-star"></i> YUKI585
                        </div>
                        <input type="text" 
                               name="result_yuki585" 
                               class="form-control result-input" 
                               placeholder="Contoh: 5678"
                               pattern="[0-9]*"
                               maxlength="5">
                        <small class="text-muted">Kosongkan jika tidak ingin update</small>
                    </div>
                </div>

                <!-- Wajahtoto Column -->
                <div class="col-md-4">
                    <div class="site-column site-wajahtoto">
                        <div class="site-header" style="color: #007bff;">
                            <i class="fas fa-gem"></i> WAJAHTOTO
                        </div>
                        <input type="text" 
                               name="result_wajahtoto" 
                               class="form-control result-input" 
                               placeholder="Contoh: 9012"
                               pattern="[0-9]*"
                               maxlength="5">
                        <small class="text-muted">Kosongkan jika tidak ingin update</small>
                    </div>
                </div>
            </div>

            <!-- Submit Section -->
            <div class="submit-section">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <h5><i class="fas fa-upload"></i> Konfirmasi Input</h5>
                        <p class="mb-0 text-muted">Pastikan data sudah benar sebelum submit. Sistem akan otomatis mengupdate hanya situs yang kolom resultnya diisi.</p>
                    </div>
                    <div class="col-md-4 text-end">
                        <button type="submit" class="btn btn-primary btn-lg">
                            <i class="fas fa-save"></i> Input Results
                        </button>
                    </div>
                </div>
            </div>
        </form>

        <!-- Recent Results Display -->
        <div class="row mt-5">
            <div class="col-md-12">
                <h4><i class="fas fa-history"></i> Recent Results</h4>
            </div>
        </div>

        <div class="row">
            <?php foreach ($sites as $siteKey => $siteInfo): ?>
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header" style="background-color: <?php echo $siteInfo['color']; ?>; color: white;">
                        <strong><?php echo $siteInfo['name']; ?></strong>
                    </div>
                    <div class="card-body p-2">
                        <div class="recent-results">
                            <?php if (!empty($recentResults[$siteKey])): ?>
                                <?php foreach ($recentResults[$siteKey] as $result): ?>
                                <div class="border-bottom py-1">
                                    <strong><?php echo htmlspecialchars($result['market']); ?></strong><br>
                                    <span class="badge bg-primary"><?php echo htmlspecialchars($result['result_4d'] ?? 'N/A'); ?></span>
                                    <small class="text-muted d-block"><?php echo $result['draw_date']; ?> <?php echo $result['draw_time'] ?? ''; ?></small>
                                    <small class="text-muted">Periode: <?php echo $result['periode'] ?? 'N/A'; ?></small>
                                </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <small class="text-muted">Belum ada hasil recent</small>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <!-- Info Panel -->
        <div class="alert alert-info mt-4">
            <h5><i class="fas fa-info-circle"></i> Cara Penggunaan:</h5>
            <ul class="mb-0">
                <li><strong>Pilih Pasaran</strong> dan <strong>Tanggal</strong> terlebih dahulu</li>
                <li><strong>Jam dan Periode</strong> akan otomatis digenerate saat input (jam saat ini)</li>
                <li><strong>Isi kolom result</strong> untuk situs yang ingin diupdate</li>
                <li><strong>Kosongkan kolom</strong> untuk situs yang tidak ingin diupdate</li>
                <li>Sistem akan otomatis mengupdate database sesuai kolom yang diisi</li>
                <li>Contoh: Isi kolom Mayortogel dan Yuki585, kosongkan Wajahtoto → hanya 2 situs pertama yang ter-update</li>
            </ul>
        </div>

<script>
// Auto-format number inputs
document.querySelectorAll('.result-input').forEach(input => {
    input.addEventListener('input', function() {
        this.value = this.value.replace(/[^0-9]/g, '');
    });
});
</script>

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