<?php
/**
 * ADMIN PAGE: MATCH MANAGEMENT (Professional Mobile Edition)
 * AOE Nusantara League
 */

// 1. MAPPING ID KE NAMA TIM
$team_map = [];
foreach ($data['teams'] as $t) {
    $team_map[$t['id']] = $t['name'];
}

// Helper Nama Bulan Indonesia
function getIndoMonthName($monthNum) {
    $months = [
        1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April', 5 => 'Mei', 6 => 'Juni',
        7 => 'Juli', 8 => 'Agustus', 9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
    ];
    return $months[(int)$monthNum];
}

// --- 2. LOGIKA PEMROSESAN DATA (POST) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    // A. GENERATOR JADWAL DENGAN JEDA ANTAR MUSIM
    if (isset($_POST['generate_schedule'])) {
        $start_week = (int)$_POST['start_week'];
        $season_break = (int)$_POST['season_break'];
        $start_date_input = $_POST['start_date']; 
        $do_reset = isset($_POST['reset_all']);
        
        $teams_raw = $data['teams'];
        if (count($teams_raw) < 2) {
            header("Location: index.php?p=match&msg=error_teams");
            exit;
        }

        if (!empty($data['matches'])) {
            $backup_file = '../data/backup_matches_' . date('Ymd_His') . '.json';
            file_put_contents($backup_file, json_encode($data['matches'], JSON_PRETTY_PRINT));
        }
        if ($do_reset) { $data['matches'] = []; }

        shuffle($teams_raw);
        $team_ids = array_column($teams_raw, 'id');
        if (count($team_ids) % 2 != 0) { $team_ids[] = "BYE"; }

        $num_teams = count($team_ids);
        $rounds = $num_teams - 1;
        $half = $num_teams / 2;

        $current_date = new DateTime($start_date_input);
        $week_num = $start_week;

        for ($season = 1; $season <= 2; $season++) {
            $circle = $team_ids; 

            if ($season == 2) {
                $days_break = $season_break * 7;
                $current_date->modify('+' . $days_break . ' days');
                $week_num += $season_break;
            }

            for ($r = 0; $r < $rounds; $r++) {
                for ($i = 0; $i < $half; $i++) {
                    $home = $circle[$i];
                    $away = $circle[$num_teams - 1 - $i];

                    if ($home !== "BYE" && $away !== "BYE") {
                        $t_a = ($season == 1) ? $home : $away;
                        $t_b = ($season == 1) ? $away : $home;

                        $end_date = clone $current_date;
                        $end_date->modify('+6 days');

                        $d_s = $current_date->format('j');
                        $m_s = getIndoMonthName($current_date->format('n'));
                        $d_e = $end_date->format('j');
                        $m_e = getIndoMonthName($end_date->format('n'));
                        $year = $current_date->format('Y');

                        $date_range = ($m_s == $m_e) ? "$d_s-$d_e $m_s $year" : "$d_s $m_s - $d_e $m_e $year";
                        $full_label = "Minggu $week_num, $date_range";

                        $data['matches'][] = [
                            "id" => "M" . uniqid(),
                            "season" => "Musim $season",
                            "team_a_id" => $t_a,
                            "team_b_id" => $t_b,
                            "date" => $full_label,
                            "time" => "20:00",
                            "status" => "Upcoming",
                            "winner_side" => "",
                            "processed" => false
                        ];

                        $current_date->modify('+7 days');
                        $week_num++;
                    }
                }
                $pivot = array_shift($circle);
                array_unshift($circle, array_pop($circle));
                array_unshift($circle, $pivot);
            }
        }

        file_put_contents($file_path, json_encode($data, JSON_PRETTY_PRINT));
        header("Location: index.php?p=match&msg=gen_success");
        exit;
    }

    // B. UPDATE SKOR
    if (isset($_POST['save_match_auto'])) {
        $m_id = $_POST['match_id'];
        $status = $_POST['status'];
        $winner = $_POST['winner'];
        $t_a_id = $_POST['team_a_id'];
        $t_b_id = $_POST['team_b_id'];

        $already_done = false;
        foreach ($data['matches'] as $m) {
            if ($m['id'] === $m_id && ($m['processed'] ?? false)) { $already_done = true; break; }
        }

        if ($status === 'Finished' && !$already_done && !empty($winner)) {
            foreach ($data['teams'] as &$t) {
                if ($t['id'] === $t_a_id) {
                    $t['played']++;
                    if ($winner === 'team_a') { $t['win']++; $t['points'] += 3; }
                    elseif ($winner === 'team_b') { $t['lose']++; }
                    else { $t['points'] += 1; }
                }
                if ($t['id'] === $t_b_id) {
                    $t['played']++;
                    if ($winner === 'team_b') { $t['win']++; $t['points'] += 3; }
                    elseif ($winner === 'team_a') { $t['lose']++; }
                    else { $t['points'] += 1; }
                }
            }
            $processed_flag = true;
        } else { $processed_flag = $already_done; }

        foreach ($data['matches'] as &$m) {
            if ($m['id'] === $m_id) {
                $m['date'] = $_POST['date'];
                $m['time'] = $_POST['time'];
                $m['status'] = $status;
                $m['winner_side'] = $winner;
                $m['processed'] = $processed_flag;
                break;
            }
        }
        file_put_contents($file_path, json_encode($data, JSON_PRETTY_PRINT));
        header("Location: index.php?p=match&msg=updated");
        exit;
    }
}

// --- 3. LOGIKA TAMPILAN ---
$action = $_GET['action'] ?? 'list';
$edit_match = null;
if (isset($_GET['id'])) {
    foreach ($data['matches'] as $m) { if ($m['id'] == $_GET['id']) { $edit_match = $m; break; } }
}

$musim1 = []; $musim2 = []; $latest = [];
if (!empty($data['matches'])) {
    foreach ($data['matches'] as $m) {
        if ($m['status'] == 'Finished') { $latest[] = $m; }
        else {
            if (($m['season'] ?? '') == 'Musim 2') $musim2[] = $m;
            else $musim1[] = $m;
        }
    }
}
$latest = array_reverse(array_slice($latest, -5));
?>

<style>
    /* Professional Component Styles */
    .btn-pro {
        display: inline-flex; align-items: center; justify-content: center; gap: 8px;
        padding: 14px 24px; border-radius: 16px; font-size: 0.85rem; font-weight: 700;
        text-decoration: none; transition: all 0.3s ease; border: 1.5px solid transparent; cursor: pointer;
    }
    .btn-pro-gold { background: var(--gold); color: black; box-shadow: 0 4px 15px rgba(212, 175, 55, 0.2); }
    .btn-pro-outline { border-color: #1a1a1a; color: #666; background: #050505; }
    .btn-pro-outline:active { border-color: var(--gold); color: white; }

    .match-card {
        background: linear-gradient(145deg, #0d0d0d, #050505);
        border: 1px solid #1a1a1a; padding: 18px; border-radius: 22px;
        margin-bottom: 12px; display: flex; justify-content: space-between; align-items: center;
    }
    .status-badge {
        font-size: 0.6rem; font-weight: 800; letter-spacing: 1px; text-transform: uppercase;
        padding: 4px 10px; border-radius: 6px; margin-bottom: 5px; display: inline-block;
    }

    /* Modal Styling */
    .modal-overlay {
        display:none; position:fixed; top:0; left:0; width:100%; height:100%; 
        background:rgba(0,0,0,0.95); z-index:9999; align-items:center; justify-content:center; padding:20px;
    }
    .modal-content {
        background: #0a0a0a; border: 1px solid var(--gold);
        padding: 30px 20px; border-radius: 30px; width: 100%; max-width: 400px;
    }

    /* Professional Form Styling */
    .form-group { margin-bottom: 22px; }
    .form-group label { 
        display: block; font-size: 0.65rem; color: #555; font-weight: 800; 
        letter-spacing: 2px; text-transform: uppercase; margin-bottom: 10px; padding-left: 5px;
    }
    .form-group input, .form-group select {
        width: 100%; padding: 16px; background: #000; border: 1.5px solid #1a1a1a;
        color: white; border-radius: 14px; font-size: 0.95rem; box-sizing: border-box;
        transition: 0.3s;
    }
    .form-group input:focus, .form-group select:focus {
        outline: none; border-color: var(--gold);
    }
    .form-group select {
        appearance: none;
        background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23d4af37' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
        background-repeat: no-repeat; background-position: right 15px center; background-size: 18px;
    }
</style>

<?php if ($action == 'list'): ?>
    <div style="background: linear-gradient(180deg, #111 0%, #000 100%); border: 1px solid #222; padding: 25px; border-radius: 25px; text-align: center; margin-bottom: 30px;">
        <div style="background: rgba(212, 175, 55, 0.1); width: 60px; height: 60px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 15px; border: 1px solid rgba(212, 175, 55, 0.2);">
            <span class="material-icons-outlined" style="color:var(--gold); font-size:32px;">auto_awesome</span>
        </div>
        <h3 style="font-family:'Cinzel'; font-size:1.1rem; color:white; margin:0 0 5px;">Liga Nusantara</h3>
        <p style="font-size:0.7rem; color:#444; margin-bottom:20px; letter-spacing:1px;">KONTROL PENJADWALAN OTOMATIS</p>
        <button onclick="toggleModal(true)" class="btn-pro btn-pro-gold" style="width:100%;">
            <span class="material-icons-outlined">settings_suggest</span> KONFIGURASI LIGA
        </button>
    </div>

    <div id="genModal" class="modal-overlay">
        <div class="modal-content">
            <h2 style="font-family:'Cinzel'; color:white; font-size:1.3rem; margin:0 0 5px;">Sistem Liga</h2>
            <p style="color:#444; font-size:0.6rem; letter-spacing:2px; margin-bottom:25px; font-weight:800;">AUTO-GENERATOR — 2 MUSIM</p>
            
            <form method="POST">
                <div class="form-group">
                    <label>Start Week</label>
                    <input type="number" name="start_week" value="1" required>
                </div>
                <div class="form-group">
                    <label>Jeda Antar Musim</label>
                    <select name="season_break">
                        <option value="0">TIDAK ADA JEDA</option>
                        <option value="1">1 MINGGU</option>
                        <option value="2">2 MINGGU</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Kick-off Date</label>
                    <input type="date" name="start_date" value="<?php echo date('Y-m-d'); ?>" required>
                </div>
                <div style="background:#000; padding:15px; border-radius:12px; border:1.5px solid #1a1a1a; margin-bottom:25px;">
                    <label style="display:flex; align-items:center; gap:12px; cursor:pointer; color:#888;">
                        <input type="checkbox" name="reset_all" value="1" checked> 
                        <span style="font-size:0.75rem; font-weight:bold;">RESET & BACKUP JADWAL</span>
                    </label>
                </div>
                <div style="display:flex; gap:10px;">
                    <button type="button" onclick="toggleModal(false)" class="btn-pro btn-pro-outline" style="flex:1;">BATAL</button>
                    <button type="submit" name="generate_schedule" class="btn-pro btn-pro-gold" style="flex:2;">GENERATE</button>
                </div>
            </form>
        </div>
    </div>

    <?php if(!empty($latest)): ?>
        <h3 class="section-title" style="color:#333; font-size:0.75rem; margin-bottom:15px;">LATEST RESULTS</h3>
        <div style="margin-bottom:30px;">
            <?php foreach($latest as $m): ?>
                <div style="background:#080808; padding:12px 18px; border-radius:15px; margin-bottom:8px; display:flex; justify-content:space-between; align-items:center; border:1px solid #111;">
                    <span style="font-size:0.75rem; color:#666; font-weight:bold;">
                        <?php echo $team_map[$m['team_a_id']] ?? '??'; ?> <small style="color:#333;">VS</small> <?php echo $team_map[$m['team_b_id']] ?? '??'; ?>
                    </span>
                    <a href="?p=match&action=edit&id=<?php echo $m['id']; ?>" style="color:#333;"><span class="material-icons-outlined" style="font-size:18px;">edit_note</span></a>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <h3 class="section-title">MUSIM 1</h3>
    <?php foreach($musim1 as $m): ?>
        <div class="match-card">
            <div>
                <span class="status-badge" style="background:rgba(212, 175, 55, 0.1); color:var(--gold);">Upcoming</span>
                <div style="font-weight:900; color:white; font-size:1rem; letter-spacing:0.5px;">
                    <?php echo $team_map[$m['team_a_id']] ?? '??'; ?> <span style="color:#444; font-size:0.7rem;">VS</span> <?php echo $team_map[$m['team_b_id']] ?? '??'; ?>
                </div>
                <div style="color:#555; font-size:0.65rem; margin-top:5px; font-weight:bold;"><?php echo $m['date']; ?></div>
            </div>
            <a href="?p=match&action=edit&id=<?php echo $m['id']; ?>" class="btn-pro btn-pro-outline" style="width:45px; height:45px; padding:0; border-radius:14px;">
                <span class="material-icons-outlined" style="font-size:20px;">sports_score</span>
            </a>
        </div>
    <?php endforeach; ?>

    <h3 class="section-title" style="margin-top:35px;">MUSIM 2</h3>
    <?php foreach($musim2 as $m): ?>
        <div class="match-card" style="opacity:0.7;">
            <div>
                <span class="status-badge" style="background:#111; color:#444;">Upcoming</span>
                <div style="font-weight:900; color:white; font-size:1rem;">
                    <?php echo $team_map[$m['team_a_id']] ?? '??'; ?> <span style="color:#444; font-size:0.7rem;">VS</span> <?php echo $team_map[$m['team_b_id']] ?? '??'; ?>
                </div>
                <div style="color:#444; font-size:0.65rem; margin-top:5px;"><?php echo $m['date']; ?></div>
            </div>
            <a href="?p=match&action=edit&id=<?php echo $m['id']; ?>" class="btn-pro btn-pro-outline" style="width:45px; height:45px; padding:0; border-radius:14px;">
                <span class="material-icons-outlined" style="font-size:20px;">sports_score</span>
            </a>
        </div>
    <?php endforeach; ?>

<?php elseif ($action == 'edit'): ?>
    <div style="margin-bottom:25px;">
        <a href="?p=match" class="btn-pro btn-pro-outline" style="padding:10px 18px; border-radius:14px;">
            <span class="material-icons-outlined">arrow_back</span> KEMBALI
        </a>
    </div>

    <div style="background:#0a0a0a; border:1px solid #1a1a1a; padding:30px 20px; border-radius:30px;">
        <h2 style="font-family:'Cinzel'; color:white; font-size:1.2rem; margin:0 0 30px; text-align:center;">Input Hasil Match</h2>
        
        <div style="background:linear-gradient(145deg, #111, #000); padding:25px; border-radius:20px; border:1.5px solid #1a1a1a; text-align:center; margin-bottom:30px;">
            <div style="font-family:'Cinzel'; color:var(--gold); font-size:1rem; line-height:1.6;">
                <?php echo $team_map[$edit_match['team_a_id']] ?? '??'; ?>
                <div style="color:#333; font-size:0.7rem; margin:10px 0;">VS</div>
                <?php echo $team_map[$edit_match['team_b_id']] ?? '??'; ?>
            </div>
        </div>

        <form method="POST">
            <input type="hidden" name="match_id" value="<?php echo $edit_match['id']; ?>">
            <input type="hidden" name="team_a_id" value="<?php echo $edit_match['team_a_id']; ?>">
            <input type="hidden" name="team_b_id" value="<?php echo $edit_match['team_b_id']; ?>">

            <div class="form-group">
                <label>Keterangan Waktu</label>
                <input type="text" name="date" value="<?php echo $edit_match['date']; ?>">
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                <div class="form-group">
                    <label>Jam</label>
                    <input type="time" name="time" value="<?php echo $edit_match['time']; ?>">
                </div>
                <div class="form-group">
                    <label>Status</label>
                    <select name="status">
                        <option value="Upcoming" <?php echo ($edit_match['status'] == 'Upcoming') ? 'selected' : ''; ?>>UPCOMING</option>
                        <option value="Live" <?php echo ($edit_match['status'] == 'Live') ? 'selected' : ''; ?>>LIVE</option>
                        <option value="Finished" <?php echo ($edit_match['status'] == 'Finished') ? 'selected' : ''; ?>>FINISHED</option>
                    </select>
                </div>
            </div>

            <div class="form-group" style="background:#000; padding:20px; border-radius:18px; border:1.5px solid #1a1a1a;">
                <label style="color:var(--gold);">Pemenang Pertandingan</label>
                <select name="winner">
                    <option value="">-- BELUM ADA HASIL --</option>
                    <option value="draw" <?php echo ($edit_match['winner_side'] == 'draw') ? 'selected' : ''; ?>>DRAW (SERI)</option>
                    <option value="team_a" <?php echo ($edit_match['winner_side'] == 'team_a') ? 'selected' : ''; ?>>TIM HOME MENANG</option>
                    <option value="team_b" <?php echo ($edit_match['winner_side'] == 'team_b') ? 'selected' : ''; ?>>TIM AWAY MENANG</option>
                </select>
                <?php if($edit_match['processed'] ?? false): ?>
                    <div style="color:#27ae60; font-size:0.65rem; margin-top:10px; font-weight:bold; display:flex; align-items:center; gap:5px;">
                        <span class="material-icons-outlined" style="font-size:14px;">verified</span> POIN SUDAH MASUK KLASEMEN
                    </div>
                <?php endif; ?>
            </div>

            <button type="submit" name="save_match_auto" class="btn-pro btn-pro-gold" style="width:100%; padding:18px;">
                <span class="material-icons-outlined">save</span> SIMPAN HASIL
            </button>
        </form>
    </div>
<?php endif; ?>

<script>function toggleModal(s){document.getElementById('genModal').style.display=s?'flex':'none'}</script>