<?php
use App\Modules\Tournaments\Models\Tournament;
use App\Modules\Tournaments\Models\TournamentParticipant;
use App\Modules\Tournaments\Models\TournamentMatch;
$__template->layout('Layout.main');
?>
<?php $__template->section('title'); ?><?= e($tournament['name_ar'] ?? 'تفاصيل البطولة') ?><?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<a href="/tournaments" class="btn btn-outline"><i data-lucide="arrow-right" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> العودة</a>
<?php
$status = $tournament['status'] ?? 'draft';
if ($status === 'draft' && can('tournament.manage')): ?>
    <form method="POST" action="/tournaments/<?= (int) $tournament['id'] ?>/open-registration" style="display:inline;"><?= csrf_field() ?>
        <button type="submit" class="btn btn-primary">فتح التسجيل</button>
    </form>
<?php elseif ($status === 'registration_open' && can('tournament.manage')): ?>
    <form method="POST" action="/tournaments/<?= (int) $tournament['id'] ?>/close-registration" style="display:inline;"><?= csrf_field() ?>
        <button type="submit" class="btn btn-outline">إغلاق التسجيل</button>
    </form>
<?php elseif ($status === 'registration_closed' && can('tournament.manage')): ?>
    <form method="POST" action="/tournaments/<?= (int) $tournament['id'] ?>/generate-bracket" style="display:inline;"><?= csrf_field() ?>
        <button type="submit" class="btn btn-primary" onclick="return confirm('سيتم توليد شجرة المباريات وبدء البطولة. متأكد؟');">توليد المباريات</button>
    </form>
<?php elseif ($status === 'in_progress' && can('tournament.manage')): ?>
    <form method="POST" action="/tournaments/<?= (int) $tournament['id'] ?>/complete" style="display:inline;"><?= csrf_field() ?>
        <button type="submit" class="btn btn-primary" onclick="return confirm('هل تريد إنهاء البطولة وتحديد الفائز؟');">إنهاء البطولة</button>
    </form>
<?php endif; ?>
<?php if (can('tournament.manage')): ?>
<a href="/tournaments/<?= (int) $tournament['id'] ?>/edit" class="btn btn-outline"><i data-lucide="edit-3" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> تعديل</a>
<?php endif; ?>
<?php $__template->endSection(); ?>

<?php $__template->section('content'); ?>

<?php
$statuses = Tournament::getStatuses();
$formats = Tournament::getFormats();
$types = Tournament::getTypes();
$statusLabel = $statuses[$status] ?? $status;
$statusColor = Tournament::getStatusColor($status);
$formatLabel = $formats[$tournament['format'] ?? ''] ?? ($tournament['format'] ?? '');
$typeLabel = $types[$tournament['tournament_type'] ?? ''] ?? ($tournament['tournament_type'] ?? '');
?>

<!-- Summary Card -->
<div class="card" style="padding:20px;margin-bottom:20px;">
    <div style="display:flex;justify-content:space-between;align-items:start;flex-wrap:wrap;gap:15px;">
        <div>
            <h2 style="margin:0 0 8px;font-size:20px;color:#1A1A2E;">
                <i data-lucide="trophy" style="width:20px;height:20px;vertical-align:middle;margin-left:6px;color:#7C3AED;"></i>
                <?= e($tournament['name_ar'] ?? '') ?>
            </h2>
            <div style="display:flex;gap:15px;flex-wrap:wrap;font-size:14px;color:#6B7280;">
                <span><i data-lucide="activity" style="width:14px;height:14px;vertical-align:middle;"></i> <?= e($tournament['discipline_name'] ?? '') ?></span>
                <span><?= e($typeLabel) ?> - <?= e($formatLabel) ?></span>
                <span><i data-lucide="calendar" style="width:14px;height:14px;vertical-align:middle;"></i> <?= e($tournament['start_date'] ?? '') ?><?= !empty($tournament['end_date']) ? ' إلى ' . e($tournament['end_date']) : '' ?></span>
            </div>
        </div>
        <span style="display:inline-block;padding:6px 14px;border-radius:10px;font-size:13px;font-weight:600;background:<?= $statusColor ?>15;color:<?= $statusColor ?>;"><?= e($statusLabel) ?></span>
    </div>
</div>

<!-- Stats Cards -->
<div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(150px, 1fr));gap:15px;margin-bottom:20px;">
    <div class="card" style="padding:15px;text-align:center;">
        <div style="font-size:28px;font-weight:700;color:#1e3a5f;"><?= count($participants) ?></div>
        <div style="font-size:12px;color:#6B7280;">مشارك</div>
    </div>
    <div class="card" style="padding:15px;text-align:center;">
        <div style="font-size:28px;font-weight:700;color:#7C3AED;"><?= count($matches) ?></div>
        <div style="font-size:12px;color:#6B7280;">مباراة</div>
    </div>
    <div class="card" style="padding:15px;text-align:center;">
        <?php $completed = array_filter($matches, fn($m) => ($m['status'] ?? '') === 'completed'); ?>
        <div style="font-size:28px;font-weight:700;color:#059669;"><?= count($completed) ?></div>
        <div style="font-size:12px;color:#6B7280;">مباراة منتهية</div>
    </div>
    <?php if (!empty($tournament['entry_fee']) && (float) $tournament['entry_fee'] > 0): ?>
    <div class="card" style="padding:15px;text-align:center;">
        <div style="font-size:28px;font-weight:700;color:#D97706;"><?= money($tournament['entry_fee']) ?></div>
        <div style="font-size:12px;color:#6B7280;">رسوم الاشتراك</div>
    </div>
    <?php endif; ?>
</div>

<!-- Tabs -->
<div style="margin-bottom:20px;">
    <div style="display:flex;gap:0;border-bottom:2px solid #E5E7EB;overflow-x:auto;" id="tabsNav">
        <button class="tab-btn active" onclick="showTab('overview')" style="padding:10px 20px;font-size:14px;font-weight:600;border:none;background:none;cursor:pointer;border-bottom:3px solid #1e3a5f;color:#1e3a5f;">نظرة عامة</button>
        <?php if ($tournament['format'] === 'knockout' && !empty($bracket)): ?>
        <button class="tab-btn" onclick="showTab('bracket')" style="padding:10px 20px;font-size:14px;font-weight:600;border:none;background:none;cursor:pointer;border-bottom:3px solid transparent;color:#6B7280;">شجرة المباريات</button>
        <?php endif; ?>
        <button class="tab-btn" onclick="showTab('standings')" style="padding:10px 20px;font-size:14px;font-weight:600;border:none;background:none;cursor:pointer;border-bottom:3px solid transparent;color:#6B7280;">الترتيب</button>
        <button class="tab-btn" onclick="showTab('matches')" style="padding:10px 20px;font-size:14px;font-weight:600;border:none;background:none;cursor:pointer;border-bottom:3px solid transparent;color:#6B7280;">المباريات</button>
        <button class="tab-btn" onclick="showTab('participants')" style="padding:10px 20px;font-size:14px;font-weight:600;border:none;background:none;cursor:pointer;border-bottom:3px solid transparent;color:#6B7280;">المشاركون</button>
    </div>
</div>

<!-- Tab: Overview -->
<div id="tab-overview" class="tab-content">
    <div class="card" style="padding:20px;">
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
            <div>
                <h4 style="margin:0 0 8px;color:#374151;">معلومات البطولة</h4>
                <table style="width:100%;font-size:14px;">
                    <tr><td style="padding:5px 0;color:#6B7280;width:120px;">الفئة العمرية:</td><td style="padding:5px 0;"><?= e($tournament['age_group'] ?? 'مفتوح') ?></td></tr>
                    <tr><td style="padding:5px 0;color:#6B7280;">الجنس:</td><td style="padding:5px 0;"><?= e($tournament['gender'] === 'male' ? 'ذكور' : ($tournament['gender'] === 'female' ? 'إناث' : 'مختلط')) ?></td></tr>
                    <tr><td style="padding:5px 0;color:#6B7280;">الحد الأقصى:</td><td style="padding:5px 0;"><?= $tournament['max_participants'] ?? 'غير محدد' ?></td></tr>
                    <tr><td style="padding:5px 0;color:#6B7280;">المنشأة:</td><td style="padding:5px 0;"><?= e($tournament['facility_name'] ?? '—') ?></td></tr>
                </table>
            </div>
            <?php if (!empty($tournament['prize_description_ar']) || !empty($tournament['rules_ar'])): ?>
            <div>
                <?php if (!empty($tournament['prize_description_ar'])): ?>
                <h4 style="margin:0 0 8px;color:#374151;">الجوائز</h4>
                <p style="font-size:14px;color:#374151;white-space:pre-wrap;"><?= e($tournament['prize_description_ar']) ?></p>
                <?php endif; ?>
                <?php if (!empty($tournament['rules_ar'])): ?>
                <h4 style="margin:15px 0 8px;color:#374151;">القواعد</h4>
                <p style="font-size:14px;color:#374151;white-space:pre-wrap;"><?= e($tournament['rules_ar']) ?></p>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>

        <?php if ($status === 'completed' && !empty($tournament['winner_team_name'])): ?>
        <div style="margin-top:20px;padding:15px;background:#ECFDF5;border:1px solid #A7F3D0;border-radius:8px;text-align:center;">
            <div style="font-size:13px;color:#065F46;margin-bottom:4px;">الفائز</div>
            <div style="font-size:20px;font-weight:700;color:#065F46;">
                <i data-lucide="trophy" style="width:18px;height:18px;vertical-align:middle;margin-left:4px;"></i>
                <?= e($tournament['winner_team_name']) ?>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Register Player (if registration open) -->
    <?php if ($status === 'registration_open' && can('tournament.register_players')): ?>
    <div class="card" style="padding:20px;margin-top:15px;">
        <h3 style="margin:0 0 12px;font-size:15px;color:#374151;">تسجيل لاعب</h3>
        <form method="POST" action="/tournaments/<?= (int) $tournament['id'] ?>/participants" style="display:flex;gap:10px;align-items:end;flex-wrap:wrap;">
            <?= csrf_field() ?>
            <div style="flex:1;min-width:200px;">
                <label class="form-label" style="font-size:12px;">اللاعب</label>
                <select name="player_id" class="form-input" required>
                    <option value="">اختر لاعب...</option>
                </select>
                <input type="hidden" id="tournamentIdForSearch" value="<?= (int) $tournament['id'] ?>">
            </div>
            <div style="min-width:150px;">
                <label class="form-label" style="font-size:12px;">اسم الفريق (اختياري)</label>
                <input type="text" name="team_name" class="form-input" placeholder="اسم الفريق...">
            </div>
            <button type="submit" class="btn btn-primary">تسجيل</button>
        </form>
    </div>
    <?php endif; ?>
</div>

<!-- Tab: Bracket -->
<?php if ($tournament['format'] === 'knockout' && !empty($bracket)): ?>
<div id="tab-bracket" class="tab-content" style="display:none;">
    <?php $__template->include('Tournaments.Views.bracket', ['bracket' => $bracket, 'tournament' => $tournament]); ?>
</div>
<?php endif; ?>

<!-- Tab: Standings -->
<div id="tab-standings" class="tab-content" style="display:none;">
    <?php $__template->include('Tournaments.Views.standings', ['standings' => $standings, 'tournament' => $tournament]); ?>
</div>

<!-- Tab: Matches -->
<div id="tab-matches" class="tab-content" style="display:none;">
    <div class="card" style="padding:0;overflow-x:auto;">
        <?php if (!empty($matches)): ?>
        <table style="width:100%;border-collapse:collapse;font-size:14px;">
            <thead>
                <tr style="background:#F9FAFB;border-bottom:2px solid #E5E7EB;">
                    <th style="padding:10px 12px;text-align:right;font-weight:600;color:#374151;">الجولة</th>
                    <th style="padding:10px 12px;text-align:right;font-weight:600;color:#374151;">المشارك أ</th>
                    <th style="padding:10px 12px;text-align:center;font-weight:600;color:#374151;">النتيجة</th>
                    <th style="padding:10px 12px;text-align:right;font-weight:600;color:#374151;">المشارك ب</th>
                    <th style="padding:10px 12px;text-align:right;font-weight:600;color:#374151;">الحالة</th>
                    <th style="padding:10px 12px;text-align:right;font-weight:600;color:#374151;">إجراء</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($matches as $m):
                    $mStatus = $m['status'] ?? 'scheduled';
                    $mStatusLabel = TournamentMatch::getStatuses()[$mStatus] ?? $mStatus;
                    $mStatusColor = TournamentMatch::getStatusColor($mStatus);
                ?>
                <tr style="border-bottom:1px solid #F3F4F6;">
                    <td style="padding:10px 12px;color:#6B7280;">الجولة <?= (int) $m['round_number'] ?></td>
                    <td style="padding:10px 12px;font-weight:<?= ($m['winner_participant_id'] ?? 0) == ($m['participant_a_id'] ?? -1) ? '700' : '400' ?>;">
                        <?= e($m['participant_a_name'] ?? 'TBD') ?>
                    </td>
                    <td style="padding:10px 12px;text-align:center;font-weight:600;">
                        <?php if ($mStatus === 'completed'): ?>
                            <?= e($m['score_a'] ?? '0') ?> - <?= e($m['score_b'] ?? '0') ?>
                        <?php else: ?>
                            <span style="color:#9CA3AF;">—</span>
                        <?php endif; ?>
                    </td>
                    <td style="padding:10px 12px;font-weight:<?= ($m['winner_participant_id'] ?? 0) == ($m['participant_b_id'] ?? -1) ? '700' : '400' ?>;">
                        <?= e($m['participant_b_name'] ?? 'TBD') ?>
                    </td>
                    <td style="padding:10px 12px;">
                        <span style="display:inline-block;padding:2px 8px;border-radius:8px;font-size:11px;font-weight:600;background:<?= $mStatusColor ?>15;color:<?= $mStatusColor ?>;"><?= e($mStatusLabel) ?></span>
                    </td>
                    <td style="padding:10px 12px;">
                        <?php if ($mStatus === 'scheduled' && $m['participant_a_id'] && $m['participant_b_id'] && can('tournament.record_results')): ?>
                        <a href="/matches/<?= (int) $m['id'] ?>/result" class="btn btn-sm btn-primary" style="font-size:11px;padding:3px 8px;">تسجيل نتيجة</a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php else: ?>
        <div style="padding:40px;text-align:center;color:#9CA3AF;">لا توجد مباريات بعد. قم بتوليد شجرة المباريات أولاً.</div>
        <?php endif; ?>
    </div>
</div>

<!-- Tab: Participants -->
<div id="tab-participants" class="tab-content" style="display:none;">
    <div class="card" style="padding:0;overflow-x:auto;">
        <?php if (!empty($participants)): ?>
        <table style="width:100%;border-collapse:collapse;font-size:14px;">
            <thead>
                <tr style="background:#F9FAFB;border-bottom:2px solid #E5E7EB;">
                    <th style="padding:10px 12px;text-align:right;font-weight:600;color:#374151;">#</th>
                    <th style="padding:10px 12px;text-align:right;font-weight:600;color:#374151;">الاسم</th>
                    <th style="padding:10px 12px;text-align:right;font-weight:600;color:#374151;">الفريق</th>
                    <th style="padding:10px 12px;text-align:right;font-weight:600;color:#374151;">التصنيف</th>
                    <th style="padding:10px 12px;text-align:right;font-weight:600;color:#374151;">الحالة</th>
                    <th style="padding:10px 12px;text-align:right;font-weight:600;color:#374151;">إجراء</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($participants as $i => $p):
                    $pStatus = $p['status'] ?? 'registered';
                    $pStatuses = TournamentParticipant::getStatuses();
                    $pStatusLabel = $pStatuses[$pStatus] ?? $pStatus;
                    $pStatusColor = TournamentParticipant::getStatusColor($pStatus);
                ?>
                <tr style="border-bottom:1px solid #F3F4F6;">
                    <td style="padding:10px 12px;color:#6B7280;"><?= $i + 1 ?></td>
                    <td style="padding:10px 12px;font-weight:600;"><?= e($p['player_name'] ?? '—') ?></td>
                    <td style="padding:10px 12px;"><?= e($p['team_name'] ?? '—') ?></td>
                    <td style="padding:10px 12px;"><?= $p['seed_number'] ? '#' . (int) $p['seed_number'] : '—' ?></td>
                    <td style="padding:10px 12px;">
                        <span style="display:inline-block;padding:2px 8px;border-radius:8px;font-size:11px;font-weight:600;background:<?= $pStatusColor ?>15;color:<?= $pStatusColor ?>;"><?= e($pStatusLabel) ?></span>
                    </td>
                    <td style="padding:10px 12px;">
                        <?php if (!in_array($pStatus, ['withdrawn', 'disqualified', 'eliminated'], true) && can('tournament.manage')): ?>
                        <form method="POST" action="/tournaments/<?= (int) $tournament['id'] ?>/participants/<?= (int) $p['id'] ?>/withdraw" style="display:inline;">
                            <?= csrf_field() ?>
                            <button type="submit" class="btn btn-sm btn-outline" style="font-size:11px;padding:3px 8px;color:#DC2626;" onclick="return confirm('تأكيد الانسحاب؟');">انسحاب</button>
                        </form>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php else: ?>
        <div style="padding:40px;text-align:center;color:#9CA3AF;">لا يوجد مشاركون مسجلون بعد.</div>
        <?php endif; ?>
    </div>
</div>

<script>
function showTab(tabName) {
    document.querySelectorAll('.tab-content').forEach(function(el) { el.style.display = 'none'; });
    document.querySelectorAll('.tab-btn').forEach(function(btn) {
        btn.style.borderBottomColor = 'transparent';
        btn.style.color = '#6B7280';
    });
    var tab = document.getElementById('tab-' + tabName);
    if (tab) tab.style.display = '';
    event.target.style.borderBottomColor = '#1e3a5f';
    event.target.style.color = '#1e3a5f';
}

document.addEventListener('DOMContentLoaded', function() {
    if (typeof lucide !== 'undefined') lucide.createIcons();
});
</script>
<?php $__template->endSection(); ?>
