<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once '../config.php';

if (!isset($_SESSION['admin_id'])) { header("Location: login.php"); exit; }

global $pdo;
$message = ''; $msgType = 'success';
$targetDir = "../assets/images/teams/";
if (!file_exists($targetDir)) { mkdir($targetDir, 0777, true); }

// =====================================
// 1. ADD / UPDATE / DELETE MATCHES
// =====================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_match'])) {
    $mId = 'M_' . time(); $t1 = $_POST['team1']; $t2 = $_POST['team2'];
    $start_time = !empty($_POST['start_time']) ? $_POST['start_time'] : null;
    $t1_logo = 'default.png'; $t2_logo = 'default.png';
    
    if (!empty($_FILES['team1_logo']['name'])) {
        $t1_logo = time() . '_t1_' . basename($_FILES["team1_logo"]["name"]);
        move_uploaded_file($_FILES["team1_logo"]["tmp_name"], $targetDir . $t1_logo);
    }
    if (!empty($_FILES['team2_logo']['name'])) {
        $t2_logo = time() . '_t2_' . basename($_FILES["team2_logo"]["name"]);
        move_uploaded_file($_FILES["team2_logo"]["tmp_name"], $targetDir . $t2_logo);
    }
    $pdo->prepare("INSERT INTO live_matches (match_id, team1_name, team2_name, team1_logo, team2_logo, start_time) VALUES (?, ?, ?, ?, ?, ?)")->execute([$mId, $t1, $t2, $t1_logo, $t2_logo, $start_time]);
    $message = "New Match Created Successfully!";
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_match'])) {
    $id = $_POST['id']; $score = $_POST['score']; $status = $_POST['status']; $start_time = !empty($_POST['start_time']) ? $_POST['start_time'] : null;
    $t1b = $_POST['t1_back']; $t1l = $_POST['t1_lay']; $t2b = $_POST['t2_back']; $t2l = $_POST['t2_lay'];
    $isLocked = isset($_POST['is_locked']) ? 1 : 0;
    $pdo->prepare("UPDATE live_matches SET score=?, status=?, t1_back=?, t1_lay=?, t2_back=?, t2_lay=?, is_locked=?, start_time=? WHERE id=?")->execute([$score, $status, $t1b, $t1l, $t2b, $t2l, $isLocked, $start_time, $id]);
    $message = "Live Data Updated!";
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_match'])) {
    $pdo->prepare("DELETE FROM live_matches WHERE id=?")->execute([$_POST['id']]);
    $message = "Match Deleted!";
}

// =====================================
// 2. SETTINGS
// =====================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_settings'])) {
    $pdo->prepare("UPDATE cricket_settings SET mode=?, api_url=?, api_key=?")->execute([$_POST['mode'], $_POST['api_url'], $_POST['api_key']]);
    $message = "Settings Updated!";
}

// =====================================
// 3. 🔥 MASS / BULK SETTLEMENT ENGINE 🔥
// =====================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_settle'])) {
    $b_match_id = $_POST['b_match_id'];
    $b_runner = $_POST['b_runner']; // e.g., "India"
    $b_action = $_POST['b_action']; // "team_win" or "team_lose"
    
    // Find all pending bets for this specific runner in this match
    $searchString = $b_runner . " [%";
    $stmt = $pdo->prepare("SELECT * FROM bets WHERE status='pending' AND period=? AND selection LIKE ?");
    $stmt->execute([$b_match_id, $searchString]);
    $pendingBets = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $settledCount = 0;

    foreach ($pendingBets as $bet) {
        $betId = $bet['id'];
        $userId = $bet['user_id'];
        $amountInDB = (float)$bet['amount'];
        $selection = $bet['selection'];
        
        preg_match('/@([0-9\.]+)/', $selection, $matches);
        $odds = isset($matches[1]) ? (float)$matches[1] : 1.0;
        $isBack = strpos($selection, '[BACK]') !== false;

        $winAmount = 0; $totalReturn = 0; $finalStatus = 'pending';

        if ($b_action === 'team_win') {
            // Team WON: Backers win, Layers lose
            if ($isBack) {
                $winAmount = $amountInDB * ($odds - 1);
                $totalReturn = $amountInDB + $winAmount;
                $finalStatus = 'win';
            } else {
                $finalStatus = 'lose'; // Layer loses liability
            }
        } else if ($b_action === 'team_lose') {
            // Team LOST: Backers lose, Layers win
            if ($isBack) {
                $finalStatus = 'lose'; // Backer loses stake
            } else {
                // Layer wins backer's stake
                $liability = $amountInDB;
                $winAmount = ($odds > 1) ? ($liability / ($odds - 1)) : 0;
                $totalReturn = $liability + $winAmount;
                $finalStatus = 'win';
            }
        }

        // Execute DB changes for each bet securely
        try {
            $pdo->beginTransaction();
            if ($finalStatus === 'win') {
                $pdo->prepare("UPDATE bets SET status='win', win_amount=? WHERE id=?")->execute([$winAmount, $betId]);
                $pdo->prepare("UPDATE wallets SET main_balance = main_balance + ? WHERE user_id=?")->execute([$totalReturn, $userId]);
            } else if ($finalStatus === 'lose') {
                $pdo->prepare("UPDATE bets SET status='lose' WHERE id=?")->execute([$betId]);
            }
            $pdo->commit();
            $settledCount++;
        } catch(Exception $e) { $pdo->rollBack(); }
    }
    
    $message = "Mass Settlement Complete! $settledCount bets settled for $b_runner.";
}

// Fetch Data
$matches = $pdo->query("SELECT * FROM live_matches ORDER BY id DESC")->fetchAll();
$settings = $pdo->query("SELECT * FROM cricket_settings LIMIT 1")->fetch(PDO::FETCH_ASSOC);

// =====================================
// PREPARE DATA FOR BULK SETTLEMENT UI
// =====================================
$pendingQuery = $pdo->query("SELECT * FROM bets WHERE status='pending' AND selection LIKE '%@%'");
$pendingBetsList = $pendingQuery->fetchAll(PDO::FETCH_ASSOC);

$bulkGroups = [];
foreach($pendingBetsList as $b) {
    $parts = explode(' [', $b['selection']);
    $runner = trim($parts[0]);
    $matchId = $b['period'];
    $key = $matchId . '|' . $runner;
    
    if(!isset($bulkGroups[$key])) {
        $bulkGroups[$key] = ['match_id' => $matchId, 'runner' => $runner, 'total_bets' => 0, 'total_volume' => 0];
    }
    $bulkGroups[$key]['total_bets']++;
    $bulkGroups[$key]['total_volume'] += $b['amount'];
}

$pageTitle = "Pro Sports Controller";
require_once 'includes/header.php';
?>

<style>
    .nav-pills .nav-link { color: #6c757d; font-weight: 700; border-radius: 10px; margin-right: 10px; padding: 10px 20px;}
    .nav-pills .nav-link.active { background: #1E88E5; color: white; box-shadow: 0 4px 10px rgba(30, 136, 229, 0.3);}
    .match-card { background: #fff; border-radius: 12px; padding: 20px; margin-bottom: 20px; border: 1px solid #eee; box-shadow: 0 5px 15px rgba(0,0,0,0.05);}
    .team-img-preview { width: 40px; height: 40px; border-radius: 50%; object-fit: cover; border: 2px solid #ddd; margin-right: 10px; }
    .score-input { background: #f1f1f4; font-size: 18px; font-weight: 900; text-align: center; }
    .odd-group { background: #f9f9f9; padding: 15px; border-radius: 10px; border: 1px solid #eee; }
    .inp-back { background: #E1F0FF; border: 1px solid #72BBE3; font-weight: 900; text-align: center; color: #1E88E5;}
    .inp-lay { background: #FFEAEE; border: 1px solid #FAA9BA; font-weight: 900; text-align: center; color: #E53935;}
    .locked-bg { background: #fff5f8; border-color: #f1416c;}
    
    .mass-card { background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%); color: white; border-radius: 12px; padding: 20px;}
    .bulk-row { background: rgba(255,255,255,0.1); border-radius: 8px; padding: 15px; margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center;}
</style>

<?php if($message): ?>
    <script>Swal.fire({ toast: true, position: 'top-end', icon: '<?= $msgType ?>', title: '<?= $message ?>', showConfirmButton: false, timer: 4000 });</script>
<?php endif; ?>

<ul class="nav nav-pills mb-4">
    <li class="nav-item"><button class="nav-link active" data-bs-toggle="pill" data-bs-target="#mass">🏆 MASS SETTLEMENT (NEW)</button></li>
    <li class="nav-item"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#manual">🏏 Live Match Control</button></li>
    <li class="nav-item"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#history">📊 Single Bet History</button></li>
    <li class="nav-item"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#settings">⚙️ API Settings</button></li>
</ul>

<div class="tab-content">
    
    <div class="tab-pane fade show active" id="mass">
        <div class="mass-card shadow-lg">
            <h4 class="fw-bold mb-4"><i class="fas fa-bolt text-warning"></i> Bulk Auto-Settlement Engine</h4>
            <p style="font-size:13px; color:#ddd;">Clicking "WIN" will pay all Backers and take money from Layers for that team. Clicking "LOSE" will take money from Backers and pay Layers.</p>
            
            <?php if(empty($bulkGroups)): ?>
                <div class="alert alert-light text-center fw-bold text-dark m-0">No pending bets available for settlement.</div>
            <?php else: ?>
                <?php foreach($bulkGroups as $bg): ?>
                <div class="bulk-row">
                    <div>
                        <h5 class="fw-bold m-0 text-warning"><?= htmlspecialchars($bg['runner']) ?></h5>
                        <div style="font-size:12px; color:#ccc;">Match ID: <?= htmlspecialchars($bg['match_id']) ?> | Pending Bets: <?= $bg['total_bets'] ?> | Total Volume: ₹<?= $bg['total_volume'] ?></div>
                    </div>
                    <div class="d-flex gap-2">
                        <form method="POST" onsubmit="return confirm('Are you sure <?= htmlspecialchars($bg['runner']) ?> WON? This will settle <?= $bg['total_bets'] ?> bets immediately!');">
                            <input type="hidden" name="bulk_settle" value="1">
                            <input type="hidden" name="b_match_id" value="<?= htmlspecialchars($bg['match_id']) ?>">
                            <input type="hidden" name="b_runner" value="<?= htmlspecialchars($bg['runner']) ?>">
                            <input type="hidden" name="b_action" value="team_win">
                            <button type="submit" class="btn btn-success fw-bold px-4 py-2 shadow-sm"><i class="fas fa-trophy"></i> Declare WIN</button>
                        </form>
                        <form method="POST" onsubmit="return confirm('Are you sure <?= htmlspecialchars($bg['runner']) ?> LOST? This will settle <?= $bg['total_bets'] ?> bets immediately!');">
                            <input type="hidden" name="bulk_settle" value="1">
                            <input type="hidden" name="b_match_id" value="<?= htmlspecialchars($bg['match_id']) ?>">
                            <input type="hidden" name="b_runner" value="<?= htmlspecialchars($bg['runner']) ?>">
                            <input type="hidden" name="b_action" value="team_lose">
                            <button type="submit" class="btn btn-danger fw-bold px-4 py-2 shadow-sm"><i class="fas fa-times-circle"></i> Declare LOSE</button>
                        </form>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>

    <div class="tab-pane fade" id="manual">
        <div class="row">
            <div class="col-md-4">
                <div class="card shadow-sm border-0 mb-4">
                    <div class="card-header bg-dark text-white fw-bold"><i class="fas fa-plus-circle text-success"></i> Create Match</div>
                    <div class="card-body">
                        <form method="POST" enctype="multipart/form-data">
                            <input type="hidden" name="add_match" value="1">
                            <div class="mb-3">
                                <label class="fw-bold text-primary">Team 1 Name</label>
                                <input type="text" name="team1" class="form-control" required>
                                <input type="file" name="team1_logo" class="form-control mt-1 form-control-sm" accept="image/*">
                            </div>
                            <div class="mb-3">
                                <label class="fw-bold text-danger">Team 2 Name</label>
                                <input type="text" name="team2" class="form-control" required>
                                <input type="file" name="team2_logo" class="form-control mt-1 form-control-sm" accept="image/*">
                            </div>
                            <div class="mb-4 border border-warning p-2 rounded bg-light-warning">
                                <label class="fw-bold text-dark"><i class="fas fa-clock text-warning"></i> Start Time (Timer)</label>
                                <input type="datetime-local" name="start_time" class="form-control fw-bold">
                            </div>
                            <button type="submit" class="btn btn-primary w-100 fw-bold">Create Match</button>
                        </form>
                    </div>
                </div>
            </div>

            <div class="col-md-8">
                <?php foreach($matches as $m): ?>
                <div class="match-card <?= $m['is_locked'] ? 'locked-bg' : '' ?>">
                    <form method="POST" class="text-end mb-2" onsubmit="return confirm('Completely delete match?');">
                        <input type="hidden" name="delete_match" value="1"><input type="hidden" name="id" value="<?= $m['id'] ?>">
                        <button type="submit" class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button>
                    </form>

                    <form method="POST">
                        <input type="hidden" name="update_match" value="1"><input type="hidden" name="id" value="<?= $m['id'] ?>">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5 class="fw-bold m-0"><img src="<?= $targetDir . $m['team1_logo'] ?>" class="team-img-preview"> <?= $m['team1_name'] ?> <span class="text-muted mx-2">vs</span> <img src="<?= $targetDir . $m['team2_logo'] ?>" class="team-img-preview"> <?= $m['team2_name'] ?></h5>
                            <span class="badge <?= $m['is_locked'] ? 'bg-danger' : 'bg-success' ?> p-2"><?= $m['is_locked'] ? 'LOCKED' : 'OPEN' ?></span>
                        </div>
                        <div class="row g-2 mb-3">
                            <div class="col-md-5"><input type="text" name="score" class="form-control score-input" value="<?= htmlspecialchars($m['score']) ?>"></div>
                            <div class="col-md-3"><input type="text" name="status" class="form-control fw-bold text-center" value="<?= htmlspecialchars($m['status']) ?>"></div>
                            <div class="col-md-4"><input type="datetime-local" name="start_time" class="form-control fw-bold" value="<?= $m['start_time'] ? date('Y-m-d\TH:i', strtotime($m['start_time'])) : '' ?>"></div>
                        </div>
                        <div class="row g-2 mb-3">
                            <div class="col-md-6"><div class="odd-group"><div class="d-flex gap-2"><div class="w-50"><small class="fw-bold text-primary">BACK</small><input type="number" step="0.01" name="t1_back" class="form-control inp-back" value="<?= $m['t1_back'] ?>"></div><div class="w-50"><small class="fw-bold text-danger">LAY</small><input type="number" step="0.01" name="t1_lay" class="form-control inp-lay" value="<?= $m['t1_lay'] ?>"></div></div></div></div>
                            <div class="col-md-6"><div class="odd-group"><div class="d-flex gap-2"><div class="w-50"><small class="fw-bold text-primary">BACK</small><input type="number" step="0.01" name="t2_back" class="form-control inp-back" value="<?= $m['t2_back'] ?>"></div><div class="w-50"><small class="fw-bold text-danger">LAY</small><input type="number" step="0.01" name="t2_lay" class="form-control inp-lay" value="<?= $m['t2_lay'] ?>"></div></div></div></div>
                        </div>
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="form-check form-switch"><input class="form-check-input border-danger" type="checkbox" name="is_locked" value="1" <?= $m['is_locked'] ? 'checked' : '' ?> style="transform:scale(1.4);"><label class="fw-bold text-danger ms-2">Suspend</label></div>
                            <button type="submit" class="btn btn-success fw-bold px-5">Save</button>
                        </div>
                    </form>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <div class="tab-pane fade" id="history">
        <div class="custom-card">
            <div class="custom-card-header"><h6 class="m-0 fw-bold"><i class="fas fa-list"></i> Detailed User Bets</h6></div>
            <div class="table-responsive p-3">
                <table class="table table-hover align-middle">
                    <thead class="table-dark"><tr><th>User</th><th>Selection</th><th>Risk Amount</th><th>Status</th></tr></thead>
                    <tbody>
                        <?php foreach($pendingBetsList as $b): 
                            $uName = $pdo->query("SELECT username FROM users WHERE id=".$b['user_id'])->fetchColumn();
                        ?>
                        <tr>
                            <td class="fw-bold text-primary"><?= htmlspecialchars($uName) ?></td>
                            <td><span class="badge bg-secondary fs-6"><?= $b['selection'] ?></span></td>
                            <td class="fw-bold fs-6">₹<?= $b['amount'] ?></td>
                            <td><span class="badge bg-warning text-dark">PENDING</span></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <small class="text-muted">Only pending bets shown here. Settle them from the MASS SETTLEMENT tab.</small>
            </div>
        </div>
    </div>

    <div class="tab-pane fade" id="settings">
        <div class="custom-card w-50">
            <div class="custom-card-header"><h6 class="m-0 fw-bold"><i class="fas fa-cog"></i> Engine Settings</h6></div>
            <div class="card-body p-4">
                <form method="POST">
                    <input type="hidden" name="update_settings" value="1">
                    <div class="mb-3">
                        <label class="fw-bold">Match Data Mode</label>
                        <select name="mode" class="form-select fw-bold border-dark">
                            <option value="manual" <?= ($settings['mode']??'manual') == 'manual' ? 'selected' : '' ?>>MANUAL</option>
                            <option value="api" <?= ($settings['mode']??'manual') == 'api' ? 'selected' : '' ?>>HYBRID API (Auto Fetch)</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="fw-bold text-primary">Live API URL</label>
                        <input type="text" name="api_url" class="form-control" value="<?= htmlspecialchars($settings['api_url'] ?? '') ?>">
                    </div>
                    <button type="submit" class="btn btn-dark w-100 fw-bold">Save Settings</button>
                </form>
            </div>
        </div>
    </div>
</div>

<?php require_once 'includes/footer.php'; ?>