<?php
// api/endpoints/tournaments.php
include_once __DIR__ . '/../config/root_path.php';

require_once ROOT_PATH . 'api/core/response.php';
require_once ROOT_PATH . 'api/core/db.php';
require_once ROOT_PATH . 'api/core/tournament.php';
require_once ROOT_PATH . 'api/core/activity.php';


try {
    /**
     * =========================
     * PARSE ID FROM URL
     * =========================
     */
    $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    $segments = array_values(array_filter(explode('/', $uri)));
    $idFromUrl = is_numeric(end($segments)) ? (int) end($segments) : null;

    /**
     * =========================
     * SANITIZE GET
     * =========================
     */
    $get_action = isset($_GET['action']) ? trim($_GET['action']) : null;
    $status = isset($_GET['status']) ? trim($_GET['status']) : null;
    $type = isset($_GET['type']) ? trim($_GET['type']) : null;
    $lang = $_GET['lang'] ?? 'id';
    $category = isset($_GET['category']) ? trim($_GET['category']) : null;

    $page = isset($_GET['page']) ? max(1, (int) $_GET['page']) : 1;
    $limit = isset($_GET['limit']) ? min(50, max(1, (int) $_GET['limit'])) : 8;
    $offset = ($page - 1) * $limit;

    $dateFrom = (
        isset($_GET['dateFrom']) &&
        preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['dateFrom'])
    ) ? $_GET['dateFrom'] : null;

    $dateTo = (
        isset($_GET['dateTo']) &&
        preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['dateTo'])
    ) ? $_GET['dateTo'] : null;

    $search = isset($_GET['search']) ? trim($_GET['search']) : null;
    $action = basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

    $current_action = null;
    if ($get_action && $get_action !== null) {
        $current_action = $get_action;
    } else if ($action && $action !== null) {
        $current_action = $action;
    }

    if ($idFromUrl > 0 && $current_action === null) {
        $current_action = 'select';
    }

    if ($current_action == 'select') {

        /**
         * =========================
         * BASE QUERY (DATA)
         * =========================
         */
        $options = [
            'type' => $type,
            'lang' => $lang,
            'idFromUrl' => $idFromUrl,
            'page' => $page,
            'limit' => $limit,
            'search' => $search,
            'dateFrom' => $dateFrom,
            'dateTo' => $dateTo,
            'category' => $category,
            'status' => $status
        ];

        $result = getActiveTournaments($options);

        jsonResponse($result);

    } elseif ($current_action == 'register') {
        require_once ROOT_PATH . 'api/middleware/requireAuth.php';
        /**
         * =========================
         * REQUIRE LOGIN & GET PLAYER ID
         * =========================
         */
        $player = requireAuth();
        $playerId = (int) $player['IDPlayer'];

        /**
         * =========================
         * INPUT
         * =========================
         */
        $tournamentId = (int) ($_POST['tournament_id'] ?? 0);
        $tclId = (int) ($_POST['tcl_id'] ?? 0);
        $partnerId = (int) ($_POST['partner_id'] ?? 0);
        $partnerEmail = trim($_POST['partner_email'] ?? '');
        $playerName = trim($_POST['player_name'] ?? '');
        $memberId = trim($_POST['member_id'] ?? '');

        // Validasi wajib
        if ($tournamentId <= 0) {
            throw new Exception('Tournament ID tidak valid');
        }

        if ($tclId <= 0) {
            throw new Exception('Kategori tidak valid');
        }

        if ($partnerId <= 0) {
            throw new Exception('Partner tidak valid');
        }

        if (empty($_FILES['payment_proof']['name'])) {
            throw new Exception('Bukti pembayaran wajib diupload');
        }

        /**
         * =========================
         * FILE VALIDATION
         * =========================
         */
        $file = $_FILES['payment_proof'];
        $maxSize = 5 * 1024 * 1024;
        $allowedExt = ['jpg', 'jpeg', 'png', 'webp'];

        if ($file['size'] > $maxSize) {
            throw new Exception('Ukuran file maksimal 5MB');
        }

        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $allowedExt, true)) {
            throw new Exception('Format file tidak valid. Gunakan JPG, PNG, atau WEBP');
        }

        /**
         * =========================
         * CEK TOURNAMENT
         * =========================
         */
        $tournament = fetchOne("
            SELECT IDTournament, StatusTournament, NamaTournament
            FROM tournament
            WHERE IDTournament = :id
            LIMIT 1
        ", ['id' => $tournamentId]);

        if (!$tournament) {
            throw new Exception('Tournament tidak ditemukan');
        }

        if (in_array($tournament['StatusTournament'], ['finished', 'cancelled', 'closed_registration'])) {
            throw new Exception('Tournament sudah tidak menerima pendaftaran');
        }

        /**
         * =========================
         * CEK KATEGORI (dari TCL)
         * =========================
         */
        $tcl = fetchOne("
            SELECT 
                tcl.IDTCL,
                tcl.IDTournament,
                tcl.IDKategori,
                tcl.MaxSlot,
                k.NamaKategori,
                k.TipeKategori,
                k.GenderRestrict
            FROM tournament_category_level tcl
            LEFT JOIN kategori k ON k.IDKategori = tcl.IDKategori
            WHERE tcl.IDTCL = :id
            AND tcl.IDTournament = :tournamentId
            LIMIT 1
        ", [
            'id' => $tclId,
            'tournamentId' => $tournamentId
        ]);

        if (!$tcl) {
            throw new Exception('Kategori tournament tidak ditemukan');
        }

        // ============================================
        // VALIDASI TIPE KATEGORI (harus double)
        // ============================================
        $tipeKategori = $tcl['TipeKategori'] ?? 'single';
        if ($tipeKategori !== 'double') {
            throw new Exception('Kategori ini untuk single player, tidak bisa registrasi dengan partner');
        }

        // ============================================
        // CEK PARTNER
        // ============================================
        $partner = fetchOne("
            SELECT 
                p.IDPlayer, 
                p.full_name, 
                p.gender, 
                p.email, 
                p.verification_status,
                COALESCE(m.MembershipNumber, '-') AS membership_number
            FROM player p
            LEFT JOIN membership m ON m.IDPlayer = p.IDPlayer AND m.status = 'active'
            WHERE p.IDPlayer = :id
            AND p.verification_status = 'verified'
            LIMIT 1
        ", ['id' => $partnerId]);

        if (!$partner) {
            throw new Exception('Partner tidak ditemukan atau belum terverifikasi');
        }

        // Jangan biarkan user mendaftar dengan dirinya sendiri
        if ((int) $partner['IDPlayer'] === $playerId) {
            throw new Exception('Tidak bisa mendaftar dengan diri sendiri sebagai partner');
        }

        // Validasi email partner sesuai
        if (strtolower($partner['email']) !== strtolower($partnerEmail)) {
            throw new Exception('Email partner tidak sesuai');
        }

        // ============================================
        // VALIDASI GENDER
        // ============================================
        $genderRestrict = $tcl['GenderRestrict'] ?? 'no_restriction';
        $playerGender = $player['gender'] ?? '';
        $partnerGender = $partner['gender'] ?? '';

        // Validasi gender player yang login
        if ($genderRestrict === 'male_only' && $playerGender !== 'male') {
            throw new Exception('Kategori ini khusus untuk pemain pria');
        }

        if ($genderRestrict === 'female_only' && $playerGender !== 'female') {
            throw new Exception('Kategori ini khusus untuk pemain wanita');
        }

        // Validasi gender partner
        if ($genderRestrict === 'male_only' && $partnerGender !== 'male') {
            throw new Exception('Partner harus berjenis kelamin pria');
        }

        if ($genderRestrict === 'female_only' && $partnerGender !== 'female') {
            throw new Exception('Partner harus berjenis kelamin wanita');
        }

        // Untuk mix_of_both, cek apakah player dan partner memiliki gender yang berbeda
        if ($genderRestrict === 'mix_of_both') {
            if ($playerGender === $partnerGender) {
                throw new Exception('Untuk kategori Mixed, player dan partner harus berbeda jenis kelamin');
            }
        }

        // ============================================
        // CEK APAKAH PARTNER SUDAH TERDAFTAR DI TOURNAMENT INI
        // ============================================
        $existingRegistration = fetchOne("
            SELECT tr.IDRegistration
            FROM tournament_registration tr
            JOIN team_member tm ON tm.IDTeam = tr.IDTeam
            WHERE tr.IDTournament = :tournamentId
            AND tr.IDTCL = :tclId
            AND tm.IDPlayer = :partnerId
            AND tr.Status IN ('active', 'waiting')
            LIMIT 1
        ", [
            'tournamentId' => $tournamentId,
            'tclId' => $tclId,
            'partnerId' => $partnerId
        ]);

        if ($existingRegistration) {
            throw new Exception('Partner sudah terdaftar di tournament ini');
        }

        // ============================================
        // CEK APAKAH PLAYER SUDAH TERDAFTAR DI TCL INI
        // ============================================
        $playerRegistration = fetchOne("
            SELECT tr.IDRegistration
            FROM tournament_registration tr
            JOIN team_member tm ON tm.IDTeam = tr.IDTeam
            WHERE tr.IDTournament = :tournamentId
            AND tr.IDTCL = :tclId
            AND tm.IDPlayer = :playerId
            AND tr.Status IN ('active', 'waiting')
            LIMIT 1
        ", [
            'tournamentId' => $tournamentId,
            'tclId' => $tclId,
            'playerId' => $playerId
        ]);

        if ($playerRegistration) {
            throw new Exception('Anda sudah terdaftar di kategori ini');
        }

        // ============================================
        // CEK SLOT TERSEDIA
        // ============================================
        $currentRegistration = fetchOne("
            SELECT COUNT(*) as total
            FROM tournament_registration tr
            WHERE tr.IDTournament = :tournamentId
            AND tr.IDTCL = :tclId
            AND tr.Status IN ('active', 'waiting')
        ", [
            'tournamentId' => $tournamentId,
            'tclId' => $tclId
        ]);

        $currentCount = (int) ($currentRegistration['total'] ?? 0);
        $maxSlot = (int) ($tcl['MaxSlot'] ?? 0);

        if ($maxSlot > 0 && $currentCount >= $maxSlot) {
            throw new Exception('Slot untuk kategori ini sudah penuh');
        }

        /**
         * =========================
         * START TRANSACTION
         * =========================
         */
        $db = Database::getConnection();
        $db->beginTransaction();

        try {
            // ============================================
            // 1. INSERT TEAM
            // ============================================
            $teamName = $player['full_name'] . ' & ' . $partner['full_name'];

            $teamSql = "
                INSERT INTO team (
                    IDTournament,
                    IDTCL,
                    TeamName,
                    CreateAt
                ) VALUES (
                    :tournamentId,
                    :tclId,
                    :teamName,
                    NOW()
                )
            ";

            execute($teamSql, [
                'tournamentId' => $tournamentId,
                'tclId' => $tclId,
                'teamName' => $teamName
            ]);

            $teamId = $db->lastInsertId();

            // ============================================
            // 2. INSERT TEAM MEMBERS
            // ============================================
            // Member 1: Player yang login
            $memberSql = "
                INSERT INTO team_member (
                    IDTeam,
                    IDPlayer
                ) VALUES (
                    :teamId,
                    :playerId
                )
            ";

            execute($memberSql, [
                'teamId' => $teamId,
                'playerId' => $playerId
            ]);

            // Member 2: Partner
            execute($memberSql, [
                'teamId' => $teamId,
                'playerId' => $partnerId
            ]);

            // ============================================
            // 3. SAVE PAYMENT PROOF
            // ============================================
            $baseDir = ROOT_PATH . "api/assets/tournament_payment/{$tournamentId}/";
            if (!is_dir($baseDir)) {
                mkdir($baseDir, 0777, true);
            }

            $paymentFileName = "{$tournamentId}_{$teamId}_payment_" . time() . ".{$ext}";
            $targetPath = $baseDir . $paymentFileName;

            if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
                throw new Exception('Gagal menyimpan bukti pembayaran');
            }

            // ============================================
            // 4. INSERT TOURNAMENT REGISTRATION
            // ============================================
            $registrationSql = "
                INSERT INTO tournament_registration (
                    IDTournament,
                    IDTCL,
                    IDTeam,
                    PaymentStatus,
                    PaymentProof,
                    RegistrationDate,
                    Status,
                    CreateBy,
                    CreateAt
                ) VALUES (
                    :tournamentId,
                    :tclId,
                    :teamId,
                    'pending',
                    :paymentProof,
                    NOW(),
                    'waiting',
                    :createBy,
                    NOW()
                )
            ";

            execute($registrationSql, [
                'tournamentId' => $tournamentId,
                'tclId' => $tclId,
                'teamId' => $teamId,
                'paymentProof' => $paymentFileName,
                'createBy' => $playerId
            ]);

            $registrationId = $db->lastInsertId();

            /**
             * =========================
             * COMMIT TRANSACTION
             * =========================
             */
            $db->commit();

            // ============================================
            // DEVICE STRING
            // ============================================
            $deviceParts = [];
            if (!empty($_POST['device_type'])) {
                $deviceParts[] = $_POST['device_type'];
            }
            if (!empty($_POST['browser'])) {
                $deviceParts[] = $_POST['browser'];
            }
            if (!empty($_POST['os'])) {
                $deviceParts[] = $_POST['os'];
            }
            $device = implode(' | ', $deviceParts);

            // ============================================
            // ACTIVITY LOG
            // ============================================
            logActivity([
                'userId' => $playerId,
                'userUsed' => $player['email'],
                'category' => 'tournament',
                'kodeUnik' => $registrationId,
                'activityAction' => 'Register Tournament',
                'device' => $device,
                'skipDetail' => true
            ]);

            // ============================================
            // RESPONSE
            // ============================================
            jsonResponse([
                'success' => true,
                'message' => 'Pendaftaran berhasil! Menunggu verifikasi pembayaran.',
                'data' => [
                    'registration_id' => (string) $registrationId,
                    'team_id' => (string) $teamId,
                    'tournament_id' => (string) $tournamentId,
                    'tcl_id' => (string) $tclId,
                    'team_name' => $teamName,
                    'payment_status' => 'pending',
                    'status' => 'waiting',
                    'players' => [
                        [
                            'id' => (string) $playerId,
                            'name' => $player['full_name'],
                            'email' => $player['email'],
                            'role' => 'player'
                        ],
                        [
                            'id' => (string) $partnerId,
                            'name' => $partner['full_name'],
                            'email' => $partner['email'],
                            'role' => 'partner'
                        ]
                    ]
                ]
            ]);

        } catch (Exception $e) {
            // Rollback transaction
            if ($db && $db->inTransaction()) {
                $db->rollBack();
            }

            // Hapus file jika sudah terupload
            if (isset($targetPath) && file_exists($targetPath)) {
                unlink($targetPath);
            }

            throw $e;
        }

    } elseif ($current_action == 'register_cancel') {

        /**
         * =========================
         * REQUIRE LOGIN & GET PLAYER ID
         * =========================
         */
        $player = requireAuth();
        $playerId = (int) $player['IDPlayer'];

        /**
         * =========================
         * INPUT
         * =========================
         */
        $tournamentId = (int) ($_POST['tournament_id'] ?? 0);
        $statusRemarks = trim($_POST['status_remarks'] ?? '');

        // Validasi wajib
        if ($tournamentId <= 0) {
            throw new Exception('Tournament ID tidak valid');
        }

        if (empty($statusRemarks)) {
            throw new Exception('Alasan pembatalan wajib diisi');
        }

        // Sanitasi statusRemarks untuk keamanan
        $statusRemarks = htmlspecialchars($statusRemarks, ENT_QUOTES, 'UTF-8');

        /**
         * =========================
         * CEK TOURNAMENT
         * =========================
         */
        $tournament = fetchOne("
            SELECT IDTournament, StatusTournament, NamaTournament
            FROM tournament
            WHERE IDTournament = :id
            LIMIT 1
        ", ['id' => $tournamentId]);

        if (!$tournament) {
            throw new Exception('Tournament tidak ditemukan');
        }

        // Hanya tournament dengan status draft atau open_registration yang boleh cancel
        if (!in_array($tournament['StatusTournament'], ['draft', 'open_registration'])) {
            throw new Exception('Pembatalan registrasi hanya dapat dilakukan saat tournament berstatus open registration');
        }

        /**
         * =========================
         * CEK REGISTRATION PLAYER
         * =========================
         */
        $registration = fetchOne("
            SELECT 
                tr.IDRegistration,
                tr.IDTeam,
                tr.Status,
                tr.IDTournament,
                tr.IDTCL,
                tr.PaymentProof
            FROM tournament_registration tr
            JOIN team_member tm ON tm.IDTeam = tr.IDTeam
            WHERE tr.IDTournament = :tournamentId
            AND tm.IDPlayer = :playerId
            AND tr.Status IN ('active', 'waiting')
            LIMIT 1
        ", [
            'tournamentId' => $tournamentId,
            'playerId' => $playerId
        ]);

        if (!$registration) {
            throw new Exception('Anda tidak terdaftar di tournament ini');
        }

        /**
         * =========================
         * 🔥 VALIDASI: CEK APAKAH SUDAH MASUK GROUP
         * =========================
         */
        $checkGroup = fetchOne("
            SELECT 1
            FROM tournament_group_team
            WHERE IDRegistration = :registrationId
            LIMIT 1
        ", [
            'registrationId' => $registration['IDRegistration']
        ]);

        if ($checkGroup) {
            throw new Exception('Registrasi tidak dapat dibatalkan karena sudah dimasukkan ke dalam group tournament');
        }

        /**
         * =========================
         * START TRANSACTION
         * =========================
         */
        $db = Database::getConnection();
        $db->beginTransaction();

        try {
            // ============================================
            // 1. DELETE PAYMENT PROOF FILE
            // ============================================
            if (!empty($registration['PaymentProof'])) {
                $baseDir = ROOT_PATH . "api/assets/tournament_payment/{$tournamentId}/";
                $filePath = $baseDir . $registration['PaymentProof'];

                if (file_exists($filePath) && is_file($filePath)) {
                    unlink($filePath);
                }
            }

            // ============================================
            // 2. DELETE TEAM MEMBERS
            // ============================================
            $deleteMemberSql = "
                DELETE FROM team_member 
                WHERE IDTeam = :teamId
            ";

            execute($deleteMemberSql, [
                'teamId' => $registration['IDTeam']
            ]);

            // ============================================
            // 3. DELETE TEAM
            // ============================================
            $deleteTeamSql = "
                DELETE FROM team 
                WHERE IDTeam = :teamId
            ";

            execute($deleteTeamSql, [
                'teamId' => $registration['IDTeam']
            ]);

            // ============================================
            // 4. DELETE REGISTRATION
            // ============================================
            $deleteRegSql = "
                DELETE FROM tournament_registration 
                WHERE IDRegistration = :registrationId
            ";

            execute($deleteRegSql, [
                'registrationId' => $registration['IDRegistration']
            ]);

            /**
             * =========================
             * COMMIT TRANSACTION
             * =========================
             */
            $db->commit();

            // ============================================
            // DEVICE STRING
            // ============================================
            $deviceParts = [];
            if (!empty($_POST['device_type'])) {
                $deviceParts[] = $_POST['device_type'];
            }
            if (!empty($_POST['browser'])) {
                $deviceParts[] = $_POST['browser'];
            }
            if (!empty($_POST['os'])) {
                $deviceParts[] = $_POST['os'];
            }
            $device = implode(' | ', $deviceParts);

            // ============================================
            // ACTIVITY LOG
            // ============================================
            logActivity([
                'userId' => $playerId,
                'userUsed' => $player['email'],
                'category' => 'tournament',
                'kodeUnik' => $tournamentId,
                'activityAction' => 'Cancel Registration  ' . $statusRemarks,
                'device' => $device,
                'skipDetail' => true
            ]);

            // ============================================
            // RESPONSE
            // ============================================
            jsonResponse([
                'success' => true,
                'message' => 'Registrasi berhasil dibatalkan dan data dihapus',
                'data' => [
                    'registration_id' => (string) $registration['IDRegistration'],
                    'tournament_id' => (string) $tournamentId,
                    'status' => 'deleted',
                    'status_remarks' => $statusRemarks
                ]
            ]);

        } catch (Exception $e) {
            // Rollback transaction
            if ($db && $db->inTransaction()) {
                $db->rollBack();
            }
            throw $e;
        }

    } else {

        throw new Exception('Action tidak ditemukan');
    }



} catch (Throwable $e) {

    jsonResponse([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
