<?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;

$db = new Database();
$siteManager = SiteManager::getInstance($db);

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['action'])) {
            switch ($_POST['action']) {
                case 'add_result':
                    // Validate input
                    $siteId = $_POST['site_id'];
                    $marketName = $_POST['market_name'];
                    $result = $_POST['result'];
                    $resultDate = $_POST['result_date'];
                    
                    // Check if result already exists
                    $stmt = $db->getConnection()->prepare("
                        SELECT id FROM site_results 
                        WHERE site_id = ? AND market_name = ? AND result_date = ?
                    ");
                    $stmt->execute([$siteId, $marketName, $resultDate]);
                    
                    if ($stmt->fetch()) {
                        // Update existing result
                        $stmt = $db->getConnection()->prepare("
                            UPDATE site_results 
                            SET result = ?, updated_at = NOW() 
                            WHERE site_id = ? AND market_name = ? AND result_date = ?
                        ");
                        $stmt->execute([$result, $siteId, $marketName, $resultDate]);
                        $message = "Result berhasil diupdate!";
                    } else {
                        // Insert new result
                        $stmt = $db->getConnection()->prepare("
                            INSERT INTO site_results (site_id, market_name, result, result_date) 
                            VALUES (?, ?, ?, ?)
                        ");
                        $stmt->execute([$siteId, $marketName, $result, $resultDate]);
                        $message = "Result berhasil ditambahkan!";
                    }
                    
                    // Also insert into main live_draw_results table for backward compatibility
                    $stmt = $db->getConnection()->prepare("
                        INSERT INTO live_draw_results (market_name, result, result_date) 
                        VALUES (?, ?, ?)
                        ON DUPLICATE KEY UPDATE result = VALUES(result), updated_at = NOW()
                    ");
                    $stmt->execute([$marketName, $result, $resultDate]);
                    
                    $messageType = "success";
                    break;
                    
                case 'bulk_add':
                    $siteId = $_POST['bulk_site_id'];
                    $resultDate = $_POST['bulk_date'];
                    $results = $_POST['results'] ?? [];
                    
                    $successCount = 0;
                    foreach ($results as $marketName => $result) {
                        if (!empty(trim($result))) {
                            // Check if result exists
                            $stmt = $db->getConnection()->prepare("
                                SELECT id FROM site_results 
                                WHERE site_id = ? AND market_name = ? AND result_date = ?
                            ");
                            $stmt->execute([$siteId, $marketName, $resultDate]);
                            
                            if ($stmt->fetch()) {
                                // Update
                                $stmt = $db->getConnection()->prepare("
                                    UPDATE site_results 
                                    SET result = ?, updated_at = NOW() 
                                    WHERE site_id = ? AND market_name = ? AND result_date = ?
                                ");
                                $stmt->execute([trim($result), $siteId, $marketName, $resultDate]);
                            } else {
                                // Insert
                                $stmt = $db->getConnection()->prepare("
                                    INSERT INTO site_results (site_id, market_name, result, result_date) 
                                    VALUES (?, ?, ?, ?)
                                ");
                                $stmt->execute([$siteId, $marketName, trim($result), $resultDate]);
                            }
                            
                            // Also insert into main table
                            $stmt = $db->getConnection()->prepare("
                                INSERT INTO live_draw_results (market_name, result, result_date) 
                                VALUES (?, ?, ?)
                                ON DUPLICATE KEY UPDATE result = VALUES(result), updated_at = NOW()
                            ");
                            $stmt->execute([$marketName, trim($result), $resultDate]);
                            
                            $successCount++;
                        }
                    }
                    
                    $message = "Bulk input berhasil! $successCount results ditambahkan/diupdate.";
                    $messageType = "success";
                    break;
                    
                case 'delete_result':
                    $stmt = $db->getConnection()->prepare("DELETE FROM site_results WHERE id = ?");
                    $stmt->execute([$_POST['result_id']]);
                    $message = "Result berhasil dihapus!";
                    $messageType = "success";
                    break;
            }
        }
    } catch (Exception $e) {
        $message = "Error: " . $e->getMessage();
        $messageType = "error";
    }
}

// Get data for display
$allSites = $siteManager->getAllSites();

// Get recent results
$recentResults = [];
try {
    $stmt = $db->getConnection()->prepare("
        SELECT sr.*, s.site_name, s.site_code, s.primary_color
        FROM site_results sr
        JOIN sites s ON sr.site_id = s.id
        ORDER BY sr.result_date DESC, sr.created_at DESC
        LIMIT 50
    ");
    $stmt->execute();
    $recentResults = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // Handle error silently
}

$pageTitle = 'Multi Result Input - Multi-Site Admin';

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

<div class="container">
    <!-- Statistics -->
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 15px; margin-bottom: 20px;">
        <div class="stat-card">
            <div class="stat-number"><?php echo count($allSites); ?></div>
            <div class="stat-label">Active Sites</div>
        </div>
        <div class="stat-card">
            <div class="stat-number"><?php echo count($recentResults); ?></div>
            <div class="stat-label">Recent Results</div>
        </div>
        <div class="stat-card">
            <div class="stat-number" id="todayResults">0</div>
            <div class="stat-label">Today's Results</div>
        </div>
        <div class="stat-card">
            <div class="stat-number" id="totalMarkets">0</div>
            <div class="stat-label">Markets Today</div>
        </div>
    </div>
        
    <?php if ($message): ?>
    <div class="alert alert-<?php echo $messageType === 'success' ? 'success' : 'error'; ?>">
        <i class="fas fa-<?php echo $messageType === 'success' ? 'check-circle' : 'exclamation-triangle'; ?>"></i>
        <?php echo htmlspecialchars($message); ?>
    </div>
    <?php endif; ?>
    
    <!-- Quick Single Result Input -->
    <div class="admin-card">
        <div class="card-header">
            <div class="card-icon">
                <i class="fas fa-edit"></i>
            </div>
            <div>
                <div class="card-title">Quick Result Input</div>
            </div>
        </div>
            <form method="POST" id="quickForm">
                <input type="hidden" name="action" value="add_result">
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">Site *</label>
                        <select name="site_id" class="form-input" id="site_select" required onchange="loadSiteMarkets()">
                            <option value="">Choose Site...</option>
                            <?php foreach ($allSites as $site): ?>
                            <option value="<?php echo $site['id']; ?>" data-color="<?php echo $site['primary_color']; ?>">
                                <?php echo htmlspecialchars($site['site_name']); ?> (<?php echo $site['site_code']; ?>)
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Market *</label>
                        <select name="market_name" class="form-input" id="market_select" required>
                            <option value="">Select site first...</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Result *</label>
                        <input type="text" name="result" class="form-input" placeholder="e.g., 1234" required maxlength="10" pattern="[0-9]+" title="Only numbers allowed">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Date *</label>
                        <input type="date" name="result_date" class="form-input" value="<?php echo date('Y-m-d'); ?>" required>
                    </div>
                </div>
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-plus"></i> Add Result
                </button>
            </form>
        </div>
    
    <!-- Bulk Result Input -->
    <div class="admin-card">
        <div class="card-header">
            <div class="card-icon">
                <i class="fas fa-tasks"></i>
            </div>
            <div>
                <div class="card-title">Bulk Result Input</div>
            </div>
        </div>
            <form method="POST" id="bulkForm">
                <input type="hidden" name="action" value="bulk_add">
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">Site *</label>
                        <select name="bulk_site_id" class="form-input" id="bulk_site_select" required onchange="loadBulkMarkets()">
                            <option value="">Choose Site...</option>
                            <?php foreach ($allSites as $site): ?>
                            <option value="<?php echo $site['id']; ?>">
                                <?php echo htmlspecialchars($site['site_name']); ?> (<?php echo $site['site_code']; ?>)
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Date *</label>
                        <input type="date" name="bulk_date" class="form-input" value="<?php echo date('Y-m-d'); ?>" required>
                    </div>
                </div>
                
                <div class="bulk-form" id="bulkMarketsContainer" style="display: none;">
                    <h4><i class="fas fa-list"></i> Enter Results for Each Market</h4>
                    <div class="quick-actions">
                        <button type="button" class="quick-action-btn" onclick="clearAllResults()">
                            <i class="fas fa-eraser"></i> Clear All
                        </button>
                        <button type="button" class="quick-action-btn" onclick="fillSampleData()">
                            <i class="fas fa-magic"></i> Fill Sample
                        </button>
                    </div>
                    <div class="markets-grid" id="bulkMarketsGrid">
                        <!-- Markets will be loaded here -->
                    </div>
                    <div style="margin-top: 20px;">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Save All Results
                        </button>
                    </div>
                </div>
            </form>
        </div>
        
        <!-- Recent Results -->
        <div class="admin-card">
            <div class="card-header">
                <div class="card-icon">
                    <i class="fas fa-history"></i>
                </div>
                <div>
                    <div class="card-title">Recent Results (Last 50)</div>
                </div>
            </div>
            
            <?php if (empty($recentResults)): ?>
            <div style="text-align: center; padding: 40px; color: #666;">
                <i class="fas fa-inbox" style="font-size: 3em; margin-bottom: 15px; display: block;"></i>
                <p>No results found. Add your first result above.</p>
            </div>
            <?php else: ?>
            <div style="overflow-x: auto;">
                <table style="width: 100%; border-collapse: collapse; margin-top: 20px;">
                    <thead>
                        <tr style="background: rgba(255, 255, 255, 0.1);">
                            <th style="padding: 12px; text-align: left; border-bottom: 1px solid rgba(255, 255, 255, 0.2); color: #d4af37;">Site</th>
                            <th style="padding: 12px; text-align: left; border-bottom: 1px solid rgba(255, 255, 255, 0.2); color: #d4af37;">Market</th>
                            <th style="padding: 12px; text-align: left; border-bottom: 1px solid rgba(255, 255, 255, 0.2); color: #d4af37;">Result</th>
                            <th style="padding: 12px; text-align: left; border-bottom: 1px solid rgba(255, 255, 255, 0.2); color: #d4af37;">Date</th>
                            <th style="padding: 12px; text-align: left; border-bottom: 1px solid rgba(255, 255, 255, 0.2); color: #d4af37;">Added</th>
                            <th style="padding: 12px; text-align: left; border-bottom: 1px solid rgba(255, 255, 255, 0.2); color: #d4af37;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($recentResults as $result): ?>
                        <tr style="border-bottom: 1px solid rgba(255, 255, 255, 0.1);" onmouseover="this.style.background='rgba(212, 175, 55, 0.1)'" onmouseout="this.style.background='transparent'">
                            <td style="padding: 12px;">
                                <span style="padding: 4px 8px; border-radius: 4px; font-size: 11px; font-weight: 600; color: white; background: <?php echo $result['primary_color']; ?>">
                                    <?php echo htmlspecialchars($result['site_code']); ?>
                                </span>
                            </td>
                            <td style="padding: 12px;"><?php echo htmlspecialchars($result['market_name']); ?></td>
                            <td style="padding: 12px;">
                                <span style="font-family: 'Courier New', monospace; font-weight: bold; font-size: 16px; letter-spacing: 1px;"><?php echo htmlspecialchars($result['result']); ?></span>
                            </td>
                            <td style="padding: 12px;"><?php echo date('d/m/Y', strtotime($result['result_date'])); ?></td>
                            <td style="padding: 12px;">
                                <?php echo date('d/m/Y H:i', strtotime($result['created_at'])); ?>
                                <?php if ($result['updated_at'] && $result['updated_at'] !== $result['created_at']): ?>
                                <br><small style="color: #ffc107;">Updated: <?php echo date('d/m H:i', strtotime($result['updated_at'])); ?></small>
                                <?php endif; ?>
                            </td>
                            <td style="padding: 12px;">
                                <form method="POST" style="display: inline;" onsubmit="return confirm('Delete this result?');">
                                    <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-danger" style="padding: 4px 8px; font-size: 12px;">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>
        </div>
        </div>
    </div>

    <script>
        // Store site markets data
        let siteMarketsData = {};
        
        async function loadSiteMarkets() {
            const siteSelect = document.getElementById('site_select');
            const marketSelect = document.getElementById('market_select');
            const siteId = siteSelect.value;
            
            // Clear market select
            marketSelect.innerHTML = '<option value="">Loading...</option>';
            
            if (!siteId) {
                marketSelect.innerHTML = '<option value="">Select site first...</option>';
                return;
            }
            
            try {
                const response = await fetch('../api/markets.php?site_id=' + siteId);
                const markets = await response.json();
                
                marketSelect.innerHTML = '<option value="">Choose Market...</option>';
                markets.forEach(market => {
                    const option = document.createElement('option');
                    option.value = market.market_name;
                    option.textContent = market.market_name;
                    marketSelect.appendChild(option);
                });
                
                siteMarketsData[siteId] = markets;
            } catch (error) {
                console.error('Error loading markets:', error);
                marketSelect.innerHTML = '<option value="">Error loading markets</option>';
            }
        }
        
        async function loadBulkMarkets() {
            const siteSelect = document.getElementById('bulk_site_select');
            const container = document.getElementById('bulkMarketsContainer');
            const grid = document.getElementById('bulkMarketsGrid');
            const siteId = siteSelect.value;
            
            if (!siteId) {
                container.style.display = 'none';
                return;
            }
            
            grid.innerHTML = '<div style="text-align: center; padding: 20px; color: #666;"><i class="fas fa-spinner fa-spin"></i> Loading markets...</div>';
            container.style.display = 'block';
            
            try {
                const response = await fetch('../api/markets.php?site_id=' + siteId);
                const markets = await response.json();
                
                grid.innerHTML = '';
                markets.forEach(market => {
                    const marketDiv = document.createElement('div');
                    marketDiv.style.cssText = 'display: flex; flex-direction: column; gap: 5px;';
                    marketDiv.innerHTML = `
                        <label style="font-size: 12px; color: #d4af37; font-weight: 600;">${market.market_name}</label>
                        <input type="text" name="results[${market.market_name}]" 
                               class="form-input" placeholder="Result" maxlength="10" pattern="[0-9]+" 
                               title="Only numbers allowed" style="padding: 8px 12px; font-family: 'Courier New', monospace; text-align: center; letter-spacing: 1px;">
                    `;
                    grid.appendChild(marketDiv);
                });
                
                if (markets.length === 0) {
                    grid.innerHTML = '<p style="color: #666; text-align: center;">No markets assigned to this site. <a href="site-markets.php" style="color: #d4af37;">Assign markets first</a>.</p>';
                }
            } catch (error) {
                console.error('Error loading markets:', error);
                grid.innerHTML = '<p style="color: #dc3545; text-align: center;">Error loading markets. Please try again.</p>';
            }
        }
        
        function clearAllResults() {
            const inputs = document.querySelectorAll('#bulkMarketsGrid input[type="text"]');
            inputs.forEach(input => input.value = '');
        }
        
        function fillSampleData() {
            const inputs = document.querySelectorAll('#bulkMarketsGrid input[type="text"]');
            inputs.forEach(input => {
                const randomResult = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
                input.value = randomResult;
            });
        }
        
        // Update statistics
        function updateStats() {
            const today = new Date().toISOString().split('T')[0];
            let todayCount = 0;
            let marketsToday = new Set();
            
            <?php foreach ($recentResults as $result): ?>
            if ('<?php echo $result['result_date']; ?>' === today) {
                todayCount++;
                marketsToday.add('<?php echo $result['market_name']; ?>');
            }
            <?php endforeach; ?>
            
            document.getElementById('todayResults').textContent = todayCount;
            document.getElementById('totalMarkets').textContent = marketsToday.size;
        }
        
        // Initialize stats
        updateStats();
        
        // Form validation
        document.getElementById('quickForm').addEventListener('submit', function(e) {
            const result = this.result.value;
            if (!/^\d+$/.test(result)) {
                e.preventDefault();
                alert('Result must contain only numbers!');
                return false;
            }
        });
        
        document.getElementById('bulkForm').addEventListener('submit', function(e) {
            const inputs = document.querySelectorAll('#bulkMarketsGrid input[type="text"]');
            let hasValidData = false;
            let hasInvalidData = false;
            
            inputs.forEach(input => {
                const value = input.value.trim();
                if (value) {
                    hasValidData = true;
                    if (!/^\d+$/.test(value)) {
                        hasInvalidData = true;
                        input.style.borderColor = '#dc3545';
                    } else {
                        input.style.borderColor = '#d4af37';
                    }
                } else {
                    input.style.borderColor = 'rgba(255, 255, 255, 0.2)';
                }
            });
            
            if (hasInvalidData) {
                e.preventDefault();
                alert('Please enter only numbers for results!');
                return false;
            }
            
            if (!hasValidData) {
                e.preventDefault();
                alert('Please enter at least one result!');
                return false;
            }
        });
    </script>

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