<?php
/**
 * ADMIN PAGE: TEAM MANAGEMENT
 * Professional Mobile UI for AOE Nusantara League
 */

// --- 1. LOGIKA PEMROSESAN DATA (POST) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $t_id = $_POST['target_team_id'] ?? $_POST['team_id'] ?? null;

    // Logic: Simpan Tim
    if (isset($_POST['save_team'])) {
        $id = $_POST['team_id'];
        $new_team = [
            "id" => $id ? $id : "T" . time(),
            "name" => htmlspecialchars($_POST['name']),
            "captain" => htmlspecialchars($_POST['captain'] ?? ''),
            "played" => (int)$_POST['played'],
            "win" => (int)$_POST['win'],
            "lose" => (int)$_POST['lose'],
            "points" => (int)$_POST['points'],
            "logo" => $_POST['existing_logo'] ?? ''
        ];
        if ($id) {
            foreach ($data['teams'] as &$t) { if ($t['id'] === $id) { $t = $new_team; break; } }
        } else { $data['teams'][] = $new_team; }
        file_put_contents($file_path, json_encode($data, JSON_PRETTY_PRINT));
        header("Location: index.php?p=team&msg=success"); exit;
    }

    // Logic: Upload Logo
    if (isset($_POST['upload_logo']) && isset($_FILES['team_logo'])) {
        $file = $_FILES['team_logo'];
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['png', 'jpg', 'jpeg', 'webp'])) {
            $filename = $t_id . "." . $ext;
            if (move_uploaded_file($file['tmp_name'], "../assets/img/teams/" . $filename)) {
                foreach ($data['teams'] as &$t) { if ($t['id'] === $t_id) { $t['logo'] = $filename; break; } }
                file_put_contents($file_path, json_encode($data, JSON_PRETTY_PRINT));
                header("Location: index.php?p=team&action=details&id=$t_id&msg=logo_updated"); exit;
            }
        }
    }

    // Logic: Tambah Player
    if (isset($_POST['add_player_to_team'])) {
        foreach ($data['players'] as &$p) { if ($p['id'] === $_POST['player_id']) { $p['team_id'] = $t_id; break; } }
        file_put_contents($file_path, json_encode($data, JSON_PRETTY_PRINT));
        header("Location: index.php?p=team&action=details&id=$t_id"); exit;
    }

    // Logic: Hapus Player
    if (isset($_POST['remove_player'])) {
        foreach ($data['players'] as &$p) { if ($p['id'] === $_POST['player_id']) { $p['team_id'] = ""; break; } }
        file_put_contents($file_path, json_encode($data, JSON_PRETTY_PRINT));
        header("Location: index.php?p=team&action=details&id=$t_id"); exit;
    }

    // Logic: Set Kapten
    if (isset($_POST['set_captain'])) {
        foreach ($data['teams'] as &$t) { if ($t['id'] === $t_id) { $t['captain'] = $_POST['captain_nickname']; break; } }
        file_put_contents($file_path, json_encode($data, JSON_PRETTY_PRINT));
        header("Location: index.php?p=team&action=details&id=$t_id"); exit;
    }
}

// --- 2. LOGIKA TAMPILAN ---
$action = $_GET['action'] ?? 'list';
$current_id = $_GET['id'] ?? null;
$edit_team = null;
if ($current_id) {
    foreach ($data['teams'] as $t) { if ($t['id'] == $current_id) { $edit_team = $t; break; } }
}
?>

<style>
    /* Professional Tag A & Buttons */
    .btn-pro {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        padding: 12px 20px;
        border-radius: 12px;
        font-size: 0.8rem;
        font-weight: 700;
        text-decoration: none;
        transition: all 0.2s ease;
        border: 1px solid transparent;
        cursor: pointer;
    }
    .btn-pro-gold { background: var(--gold); color: black; }
    .btn-pro-outline { border-color: #333; color: #888; }
    .btn-pro-outline:active { border-color: var(--gold); color: white; background: #111; }
    
    .btn-icon-only {
        width: 45px; height: 45px; padding: 0; border-radius: 14px;
    }

    /* Team Card */
    .team-card {
        background: linear-gradient(145deg, #0f0f0f, #050505);
        border: 1px solid #1a1a1a;
        padding: 18px;
        border-radius: 20px;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
</style>

<?php if ($action == 'list'): ?>
    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:25px; padding: 0 5px;">
        <h2 class="section-title" style="margin:0; border:none;">Daftar Tim</h2>
        <a href="?p=team&action=add" class="btn-pro btn-pro-gold">
            <span class="material-icons-outlined">add</span> BARU
        </a>
    </div>

    <div class="team-list">
        <?php foreach ($data['teams'] as $t): ?>
        <div class="team-card">
            <div style="display:flex; align-items:center; gap:15px;">
                <?php $logo = !empty($t['logo']) ? "../assets/img/teams/".$t['logo'] : "https://ui-avatars.com/api/?name=".urlencode($t['name'])."&background=222&color=d4af37"; ?>
                <img src="<?php echo $logo; ?>" style="width:55px; height:55px; border-radius:18px; object-fit:cover; border: 1px solid #222;">
                <div>
                    <div style="color:white; font-weight:bold; font-size:1rem;"><?php echo $t['name']; ?></div>
                    <div style="color:#555; font-size:0.7rem; margin-top:4px; display:flex; align-items:center; gap:5px;">
                        <span class="material-icons-outlined" style="font-size:14px; color:var(--gold);">stars</span> 
                        <?php echo $t['captain'] ?: 'Belum ada kapten'; ?>
                    </div>
                </div>
            </div>
            
            <div style="display:flex; gap:10px;">
                <a href="?p=team&action=details&id=<?php echo $t['id']; ?>" class="btn-pro btn-pro-outline btn-icon-only" title="Details">
                    <span class="material-icons-outlined">groups</span>
                </a>
                <a href="?p=team&action=edit&id=<?php echo $t['id']; ?>" class="btn-pro btn-pro-outline btn-icon-only" title="Edit">
                    <span class="material-icons-outlined">settings</span>
                </a>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

<?php elseif ($action == 'details'): ?>
    <div style="margin-bottom:25px;">
        <a href="?p=team" class="btn-pro btn-pro-outline" style="padding: 8px 15px;">
            <span class="material-icons-outlined" style="font-size:18px;">arrow_back</span> KEMBALI
        </a>
    </div>

    <div style="background: #0a0a0a; border: 1px solid #1a1a1a; padding: 30px 20px; border-radius: 25px; text-align: center; margin-bottom: 25px;">
        <div style="position:relative; display:inline-block; margin-bottom:15px;">
            <?php 
                $logo_path = "../assets/img/teams/" . ($edit_team['logo'] ?? 'none');
                $img_url = (file_exists($logo_path) && !empty($edit_team['logo'])) ? $logo_path : "https://ui-avatars.com/api/?name=".urlencode($edit_team['name'])."&background=222&color=d4af37";
            ?>
            <img src="<?php echo $img_url; ?>" style="width:130px; height:130px; border-radius:30px; border:2px solid #222; object-fit:cover;">
            <label for="logo-upload" style="position:absolute; bottom:-10px; right:-10px; background:var(--gold); color:black; border-radius:12px; width:40px; height:40px; display:flex; align-items:center; justify-content:center; cursor:pointer; box-shadow: 0 4px 15px rgba(0,0,0,0.6);">
                <span class="material-icons-outlined">photo_camera</span>
            </label>
        </div>
        <h2 style="font-family:'Cinzel'; color:white; margin:10px 0;"><?php echo $edit_team['name']; ?></h2>
        
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="target_team_id" value="<?php echo $current_id; ?>">
            <input type="file" name="team_logo" id="logo-upload" accept="image/*" style="display:none;" onchange="this.form.submit()">
            <input type="hidden" name="upload_logo" value="1">
        </form>
    </div>

    <div style="padding:0 5px;">
        <h3 style="font-size:0.8rem; color:#444; letter-spacing:2px; margin-bottom:15px; text-transform:uppercase;">Lineup Pemain</h3>
        
        <?php foreach ($data['players'] as $p): if ($p['team_id'] == $current_id): 
            $is_cap = ($edit_team['captain'] == $p['nickname']);
        ?>
            <div style="background:#111; padding:15px; border-radius:18px; margin-bottom:10px; display:flex; justify-content:space-between; align-items:center; border: 1px solid <?php echo $is_cap ? 'var(--gold)' : '#1a1a1a'; ?>;">
                <div style="display:flex; align-items:center; gap:12px;">
                    <div style="color:<?php echo $is_cap ? 'var(--gold)' : '#555'; ?>;"><span class="material-icons-outlined"><?php echo $is_cap ? 'stars' : 'person'; ?></span></div>
                    <div>
                        <div style="color:white; font-weight:bold; font-size:0.9rem;"><?php echo $p['nickname']; ?></div>
                        <div style="font-size:0.65rem; color:#444;"><?php echo $p['role']; ?></div>
                    </div>
                </div>
                <div style="display:flex; gap:5px;">
                    <?php if(!$is_cap): ?>
                    <form method="POST" style="margin:0;"><input type="hidden" name="target_team_id" value="<?php echo $current_id; ?>"><input type="hidden" name="captain_nickname" value="<?php echo $p['nickname']; ?>"><button type="submit" name="set_captain" class="btn-pro btn-pro-outline btn-icon-only" style="width:35px; height:35px; border:none;"><span class="material-icons-outlined" style="font-size:18px;">military_tech</span></button></form>
                    <?php endif; ?>
                    <form method="POST" style="margin:0;"><input type="hidden" name="player_id" value="<?php echo $p['id']; ?>"><input type="hidden" name="target_team_id" value="<?php echo $current_id; ?>"><button type="submit" name="remove_player" class="btn-pro btn-pro-outline btn-icon-only" style="width:35px; height:35px; border:none; color:var(--accent);"><span class="material-icons-outlined" style="font-size:18px;">close</span></button></form>
                </div>
            </div>
        <?php endif; endforeach; ?>

        <form method="POST" style="margin-top:20px; background:#0a0a0a; padding:15px; border-radius:20px; border:1px solid #1a1a1a;">
            <input type="hidden" name="target_team_id" value="<?php echo $current_id; ?>">
            <div style="display:flex; gap:10px;">
                <select name="player_id" required style="flex:1; background:#000; color:white; border:1px solid #222; padding:12px; border-radius:12px; font-size:0.8rem;">
                    <option value="">Pilih Player Baru...</option>
                    <?php foreach($data['players'] as $p): if(empty($p['team_id'])): ?>
                        <option value="<?php echo $p['id']; ?>"><?php echo $p['nickname']; ?></option>
                    <?php endif; endforeach; ?>
                </select>
                <button type="submit" name="add_player_to_team" class="btn-pro btn-pro-gold" style="border-radius:12px; padding:0 20px;">REKRUT</button>
            </div>
        </form>
    </div>

<?php else: ?>
    <div style="margin-bottom:25px;">
        <a href="?p=team" class="btn-pro btn-pro-outline" style="padding: 8px 15px;">
            <span class="material-icons-outlined" style="font-size:18px;">arrow_back</span> KEMBALI
        </a>
    </div>
    
    <div style="background:#0a0a0a; border:1px solid #1a1a1a; padding:25px; border-radius:25px;">
        <h2 class="section-title" style="margin-top:0;"><?php echo $edit_team ? 'Update Statistik' : 'Klan Baru'; ?></h2>
        <form method="POST">
            <input type="hidden" name="team_id" value="<?php echo $edit_team['id'] ?? ''; ?>">
            <input type="hidden" name="existing_logo" value="<?php echo $edit_team['logo'] ?? ''; ?>">
            <input type="hidden" name="captain" value="<?php echo $edit_team['captain'] ?? ''; ?>">

            <div class="form-group">
                <label>NAMA KLAN</label>
                <input type="text" name="name" value="<?php echo $edit_team['name'] ?? ''; ?>" required placeholder="Contoh: Majapahit Empire">
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin: 20px 0;">
                <div class="form-group"><label>MATCH</label><input type="number" name="played" value="<?php echo $edit_team['played'] ?? 0; ?>"></div>
                <div class="form-group"><label>WIN</label><input type="number" name="win" value="<?php echo $edit_team['win'] ?? 0; ?>"></div>
                <div class="form-group"><label>LOSE</label><input type="number" name="lose" value="<?php echo $edit_team['lose'] ?? 0; ?>"></div>
                <div class="form-group"><label>POINTS</label><input type="number" name="points" value="<?php echo $edit_team['points'] ?? 0; ?>"></div>
            </div>

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