<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once 'class/config.php';
require_once 'class/database.php';
require_once 'steamauth/steamauth.php';
require_once 'class/utils.php';

$db = new DataBase();
$selectedSkins = [];
$selectedKnife = null;
$selectedGlove = null;
$weapons = [];
$skins = [];
$knifes = [];
$gloves = [];

if (isset($_SESSION['steamid'])) {
    $steamid = $_SESSION['steamid'];

    $weapons = UtilsClass::getWeaponsFromArray();
    $skins = UtilsClass::skinsFromJson();

    $querySelected = $db->select("
        SELECT `weapon_defindex`, MAX(`weapon_paint_id`) AS `weapon_paint_id`, MAX(`weapon_wear`) AS `weapon_wear`, MAX(`weapon_seed`) AS `weapon_seed`
        FROM `wp_player_skins`
        WHERE `steamid` = :steamid
        GROUP BY `weapon_defindex`, `steamid`
    ", ["steamid" => $steamid]);
    $selectedSkins = UtilsClass::getSelectedSkins($querySelected);

    $selectedKnife = $db->select("SELECT * FROM `wp_player_knife` WHERE `steamid` = :steamid AND `weapon_team` = 2 LIMIT 1", ["steamid" => $steamid]);
    $selectedGlove = $db->select("SELECT * FROM `wp_player_glove` WHERE `steamid` = :steamid LIMIT 1", ["steamid" => $steamid]);

    $knifes = UtilsClass::getKnifeTypes();
    $gloves = UtilsClass::getGloveTypes();

    if (isset($_POST['action'])) {
        $action = $_POST['action'];

        if ($action === 'set_knife' && isset($_POST['knife_index'])) {
            $idx = intval($_POST['knife_index']);
            if (isset($knifes[$idx])) {
                $knifeName = $knifes[$idx]['weapon_name'];
                $db->query("INSERT INTO `wp_player_knife` (`steamid`, `knife`, `weapon_team`) VALUES(:steamid, :knife, 2) ON DUPLICATE KEY UPDATE `knife` = :knife", ["steamid" => $steamid, "knife" => $knifeName]);
                $db->query("INSERT INTO `wp_player_knife` (`steamid`, `knife`, `weapon_team`) VALUES(:steamid, :knife, 3) ON DUPLICATE KEY UPDATE `knife` = :knife", ["steamid" => $steamid, "knife" => $knifeName]);
            }
        }

        if ($action === 'set_glove' && isset($_POST['glove_index'])) {
            $idx = intval($_POST['glove_index']);
            if (isset($gloves[$idx])) {
                $gloveName = $gloves[$idx]['weapon_name'];
                $db->query("INSERT INTO `wp_player_glove` (`steamid`, `weapon_defindex`) VALUES(:steamid, :defindex) ON DUPLICATE KEY UPDATE `weapon_defindex` = :defindex", ["steamid" => $steamid, "defindex" => $idx]);
            }
        }

        if ($action === 'set_skin' && isset($_POST['defindex'], $_POST['paint_id'], $_POST['wear'], $_POST['seed'])) {
            $defindex = intval($_POST['defindex']);
            $paintId = intval($_POST['paint_id']);
            $wear = floatval($_POST['wear']);
            $seed = intval($_POST['seed']);
            if ($wear < 0) $wear = 0; if ($wear > 1) $wear = 1;
            if ($seed < 0) $seed = 0; if ($seed > 1000) $seed = 1000;

            if (array_key_exists($defindex, $selectedSkins)) {
                $db->query("UPDATE wp_player_skins SET weapon_paint_id=:pid, weapon_wear=:wear, weapon_seed=:seed WHERE steamid=:steamid AND weapon_defindex=:defindex",
                    ["steamid"=>$steamid,"defindex"=>$defindex,"pid"=>$paintId,"wear"=>$wear,"seed"=>$seed]);
            } else {
                foreach ([2,3] as $team) {
                    $db->query("INSERT INTO wp_player_skins (`steamid`,`weapon_defindex`,`weapon_paint_id`,`weapon_wear`,`weapon_seed`,`weapon_team`) VALUES(:sid,:def,:pid,:wear,:seed,:team)",
                        ["sid"=>$steamid,"def"=>$defindex,"pid"=>$paintId,"wear"=>$wear,"seed"=>$seed,"team"=>$team]);
                }
            }
        }

        header("Location: {$_SERVER['PHP_SELF']}");
        exit;
    }
}

$categories = [
    'rifles'  => ['label' => 'Rifles',   'icon' => 'rifle',   'defindexes' => [7,8,10,16,39,40,60,61,64]],
    'pistols' => ['label' => 'Pistols',  'icon' => 'pistol',  'defindexes' => [1,2,3,4,30,32,36,61,63,64]],
    'smgs'    => ['label' => 'SMGs',     'icon' => 'smg',     'defindexes' => [17,19,23,24,26,33,34]],
    'heavy'   => ['label' => 'Heavy',    'icon' => 'heavy',   'defindexes' => [9,11,13,14,25,35,38,41]],
    'knives'  => ['label' => 'Knives',   'icon' => 'knife',   'defindexes' => []],
    'gloves'  => ['label' => 'Gloves',   'icon' => 'glove',   'defindexes' => []],
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BRO ARENA — Weapon Loadout</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@400;500;600;700&family=Share+Tech+Mono&family=Exo+2:wght@300;400;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
<body>

<div class="scanline"></div>
<div class="noise"></div>

<header class="site-header">
    <div class="header-inner">
        <a href="#" class="logo">
            <div class="logo-mark">
                <svg width="38" height="38" viewBox="0 0 38 38" fill="none">
                    <polygon points="19,2 36,10 36,28 19,36 2,28 2,10" stroke="white" stroke-width="1.5" fill="none"/>
                    <polygon points="19,8 30,13.5 30,24.5 19,30 8,24.5 8,13.5" fill="white" opacity="0.08"/>
                    <text x="19" y="23" text-anchor="middle" fill="white" font-family="Rajdhani" font-weight="700" font-size="11">BRO</text>
                </svg>
            </div>
            <div class="logo-text">
                <span class="logo-main">BRO ARENA</span>
                <span class="logo-sub">WEAPON LOADOUT</span>
            </div>
        </a>

        <nav class="header-nav">
            <?php if (isset($_SESSION['steamid'])): ?>
            <div class="player-info">
                <?php
                $info = UtilsClass::getSteamUserInfo($steamid);
                $avatar = $info['avatarmedium'] ?? '';
                $name = htmlspecialchars($info['personaname'] ?? 'Player');
                ?>
                <?php if ($avatar): ?><img src="<?= $avatar ?>" class="player-avatar" alt=""><?php endif; ?>
                <span class="player-name"><?= $name ?></span>
                <a href="?logout" class="btn-logout">LOGOUT</a>
            </div>
            <?php else: ?>
            <div class="login-prompt">
                <?php loginbutton("rectangle"); ?>
            </div>
            <?php endif; ?>
        </nav>
    </div>
</header>

<?php if (!isset($_SESSION['steamid'])): ?>
<div class="hero-login">
    <div class="hero-bg-grid"></div>
    <div class="hero-content">
        <div class="hero-badge">CS2 COMMUNITY SERVER</div>
        <h1 class="hero-title">CUSTOMIZE YOUR<br><em>WEAPON LOADOUT</em></h1>
        <p class="hero-desc">Sign in with Steam to set your skins, knives and gloves for BRO ARENA servers.</p>
        <div class="hero-login-btn"><?php loginbutton("rectangle"); ?></div>
        <div class="hero-stats">
            <div class="stat"><span class="stat-num">500+</span><span class="stat-label">Skins</span></div>
            <div class="stat"><span class="stat-num">20+</span><span class="stat-label">Knives</span></div>
            <div class="stat"><span class="stat-num">10+</span><span class="stat-label">Gloves</span></div>
        </div>
    </div>
</div>
<?php else: ?>

<div class="loadout-page">
    <aside class="sidebar">
        <div class="sidebar-title">CATEGORIES</div>
        <nav class="cat-nav">
            <?php foreach ($categories as $catKey => $cat): ?>
            <button class="cat-btn <?= $catKey === 'rifles' ? 'active' : '' ?>" data-cat="<?= $catKey ?>">
                <span class="cat-icon cat-icon-<?= $cat['icon'] ?>"></span>
                <?= $cat['label'] ?>
                <?php
                $count = 0;
                if ($catKey === 'knives') $count = $selectedKnife ? 1 : 0;
                elseif ($catKey === 'gloves') $count = $selectedGlove ? 1 : 0;
                else {
                    foreach ($cat['defindexes'] as $di) {
                        if (isset($selectedSkins[$di])) $count++;
                    }
                }
                if ($count > 0) echo "<span class='cat-badge'>$count</span>";
                ?>
            </button>
            <?php endforeach; ?>
        </nav>
        <div class="sidebar-info">
            <div class="info-row"><span>Steam ID</span><span class="mono"><?= substr($steamid, -8) ?>…</span></div>
            <div class="info-row"><span>Skins set</span><span class="mono"><?= count($selectedSkins) ?></span></div>
        </div>
    </aside>

    <main class="weapon-grid-area">

        <?php /* ─── RIFLES / PISTOLS / SMGS / HEAVY ─── */ ?>
        <?php foreach (['rifles','pistols','smgs','heavy'] as $catKey): ?>
        <section class="weapon-section" data-cat="<?= $catKey ?>" <?= $catKey !== 'rifles' ? 'style="display:none"' : '' ?>>
            <div class="weapon-grid">
            <?php foreach ($weapons as $defindex => $default):
                if (!in_array($defindex, $categories[$catKey]['defindexes'])) continue;
                $hasSkin = isset($selectedSkins[$defindex]);
                $currentSkin = $hasSkin ? $skins[$defindex][$selectedSkins[$defindex]['weapon_paint_id']] : $default;
                $currentWear = $hasSkin ? $selectedSkins[$defindex]['weapon_wear'] : 1.0;
                $currentSeed = $hasSkin ? $selectedSkins[$defindex]['weapon_seed'] : 0;
                $wearLabel = UtilsClass::getWearLabel($currentWear);
            ?>
            <div class="weapon-card <?= $hasSkin ? 'has-skin' : '' ?>">
                <div class="weapon-card-inner">
                    <div class="weapon-img-wrap">
                        <img src="<?= htmlspecialchars($currentSkin['image_url']) ?>" class="weapon-img" alt="">
                        <?php if ($hasSkin): ?>
                        <div class="wear-tag"><?= $wearLabel ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="weapon-info">
                        <div class="weapon-name"><?= htmlspecialchars($default['weapon_name']) ?></div>
                        <div class="weapon-skin-name"><?= $hasSkin ? htmlspecialchars($currentSkin['paint_name']) : '<span class="no-skin">Default</span>' ?></div>
                    </div>
                    <button class="btn-edit" onclick="openSkinModal(<?= $defindex ?>)">CUSTOMIZE</button>
                </div>
                <div class="card-glow"></div>
            </div>

            <div class="skin-modal-overlay" id="modal-<?= $defindex ?>" onclick="if(event.target===this)closeModal(<?= $defindex ?>)">
                <div class="skin-modal">
                    <div class="modal-header">
                        <span class="modal-weapon-name"><?= htmlspecialchars($default['weapon_name']) ?></span>
                        <button class="modal-close" onclick="closeModal(<?= $defindex ?>)">✕</button>
                    </div>
                    <div class="modal-body">
                        <div class="modal-preview">
                            <img id="preview-img-<?= $defindex ?>" src="<?= htmlspecialchars($currentSkin['image_url']) ?>" class="modal-weapon-img" alt="">
                            <div class="modal-skin-label" id="preview-name-<?= $defindex ?>"><?= htmlspecialchars($currentSkin['paint_name']) ?></div>
                        </div>
                        <form method="POST" class="modal-form" id="form-<?= $defindex ?>">
                            <input type="hidden" name="action" value="set_skin">
                            <input type="hidden" name="defindex" value="<?= $defindex ?>">
                            <input type="hidden" name="paint_id" id="paint_id-<?= $defindex ?>" value="<?= $hasSkin ? $selectedSkins[$defindex]['weapon_paint_id'] : 0 ?>">

                            <div class="form-field">
                                <label class="field-label">SKIN</label>
                                <div class="skin-search-wrap">
                                    <input type="text" class="skin-search" placeholder="Search skin..." oninput="filterSkins(<?= $defindex ?>, this.value)">
                                </div>
                                <div class="skin-list" id="skinlist-<?= $defindex ?>">
                                <?php foreach ($skins[$defindex] as $paintKey => $paint): ?>
                                    <div class="skin-option <?= ($hasSkin && $selectedSkins[$defindex]['weapon_paint_id'] == $paintKey) ? 'selected' : '' ?>"
                                         onclick="selectSkin(<?= $defindex ?>, <?= $paintKey ?>, '<?= addslashes(htmlspecialchars($paint['paint_name'])) ?>', '<?= addslashes($paint['image_url']) ?>')">
                                        <img src="<?= htmlspecialchars($paint['image_url']) ?>" class="skin-thumb" loading="lazy" alt="">
                                        <span><?= htmlspecialchars($paint['paint_name']) ?></span>
                                    </div>
                                <?php endforeach; ?>
                                </div>
                            </div>

                            <div class="form-row">
                                <div class="form-field">
                                    <label class="field-label">WEAR</label>
                                    <select class="field-select" onchange="setWear(<?= $defindex ?>, this.value)" id="wear-select-<?= $defindex ?>">
                                        <option value="0.00" <?= $currentWear <= 0.07 ? 'selected' : '' ?>>Factory New</option>
                                        <option value="0.07" <?= ($currentWear > 0.07 && $currentWear <= 0.15) ? 'selected' : '' ?>>Minimal Wear</option>
                                        <option value="0.15" <?= ($currentWear > 0.15 && $currentWear <= 0.38) ? 'selected' : '' ?>>Field-Tested</option>
                                        <option value="0.38" <?= ($currentWear > 0.38 && $currentWear <= 0.45) ? 'selected' : '' ?>>Well-Worn</option>
                                        <option value="0.45" <?= $currentWear > 0.45 ? 'selected' : '' ?>>Battle-Scarred</option>
                                    </select>
                                </div>
                                <div class="form-field">
                                    <label class="field-label">SEED</label>
                                    <input type="number" name="seed" class="field-input" value="<?= $currentSeed ?>" min="0" max="1000" id="seed-<?= $defindex ?>">
                                </div>
                            </div>
                            <input type="hidden" name="wear" id="wear-<?= $defindex ?>" value="<?= $currentWear ?>">

                            <div class="modal-actions">
                                <button type="button" class="btn-cancel" onclick="closeModal(<?= $defindex ?>)">CANCEL</button>
                                <button type="submit" class="btn-apply">APPLY SKIN</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
            </div>
        </section>
        <?php endforeach; ?>

        <?php /* ─── KNIVES ─── */ ?>
        <section class="weapon-section" data-cat="knives" style="display:none">
            <?php
            $actualKnifeName = 'weapon_knife';
            if ($selectedKnife && count($selectedKnife) > 0) $actualKnifeName = $selectedKnife[0]['knife'];
            ?>
            <div class="special-grid">
            <?php foreach ($knifes as $kIdx => $knife): ?>
            <form method="POST" style="display:contents">
                <input type="hidden" name="action" value="set_knife">
                <input type="hidden" name="knife_index" value="<?= $kIdx ?>">
                <button type="submit" class="special-card <?= ($actualKnifeName === $knife['weapon_name']) ? 'selected' : '' ?>">
                    <img src="<?= htmlspecialchars($knife['image_url']) ?>" class="special-img" alt="">
                    <div class="special-name"><?= htmlspecialchars($knife['paint_name']) ?></div>
                    <?php if ($actualKnifeName === $knife['weapon_name']): ?>
                    <div class="selected-badge">EQUIPPED</div>
                    <?php endif; ?>
                </button>
            </form>
            <?php endforeach; ?>
            </div>
        </section>

        <?php /* ─── GLOVES ─── */ ?>
        <section class="weapon-section" data-cat="gloves" style="display:none">
            <?php
            $actualGloveIdx = 0;
            if ($selectedGlove && count($selectedGlove) > 0) $actualGloveIdx = $selectedGlove[0]['weapon_defindex'];
            ?>
            <div class="special-grid">
            <?php foreach ($gloves as $gIdx => $glove): ?>
            <form method="POST" style="display:contents">
                <input type="hidden" name="action" value="set_glove">
                <input type="hidden" name="glove_index" value="<?= $gIdx ?>">
                <button type="submit" class="special-card <?= ($actualGloveIdx == $gIdx) ? 'selected' : '' ?>">
                    <img src="<?= htmlspecialchars($glove['image_url']) ?>" class="special-img" alt="">
                    <div class="special-name"><?= htmlspecialchars($glove['paint_name']) ?></div>
                    <?php if ($actualGloveIdx == $gIdx): ?>
                    <div class="selected-badge">EQUIPPED</div>
                    <?php endif; ?>
                </button>
            </form>
            <?php endforeach; ?>
            </div>
        </section>

    </main>
</div>

<?php endif; ?>

<footer class="site-footer">
    <span>BRO ARENA &copy; <?= date('Y') ?> — CS2 Community Platform</span>
</footer>

<script>
function openSkinModal(id) {
    document.getElementById('modal-' + id).classList.add('open');
    document.body.style.overflow = 'hidden';
}
function closeModal(id) {
    document.getElementById('modal-' + id).classList.remove('open');
    document.body.style.overflow = '';
}
function selectSkin(defindex, paintId, name, img) {
    document.getElementById('paint_id-' + defindex).value = paintId;
    document.getElementById('preview-img-' + defindex).src = img;
    document.getElementById('preview-name-' + defindex).textContent = name;
    document.querySelectorAll('#skinlist-' + defindex + ' .skin-option').forEach(el => el.classList.remove('selected'));
    event.currentTarget.classList.add('selected');
}
function setWear(defindex, val) {
    document.getElementById('wear-' + defindex).value = val;
}
function filterSkins(defindex, query) {
    const q = query.toLowerCase();
    document.querySelectorAll('#skinlist-' + defindex + ' .skin-option').forEach(el => {
        el.style.display = el.querySelector('span').textContent.toLowerCase().includes(q) ? '' : 'none';
    });
}
document.querySelectorAll('.cat-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        document.querySelectorAll('.cat-btn').forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        const cat = btn.dataset.cat;
        document.querySelectorAll('.weapon-section').forEach(s => {
            s.style.display = s.dataset.cat === cat ? '' : 'none';
        });
    });
});
</script>
</body>
</html>
