<?php
require_once __DIR__ . '/../init.php';
require_once PROJECT_ROOT . '/backend/controllers/common_function.php';
require_once PROJECT_ROOT . '/backend/controllers/db_select_helper.php';

// include other controller
require_once PROJECT_ROOT . '/backend/controllers/ActivityController.php';
require_once PROJECT_ROOT . '/backend/controllers/UserAksesController.php';

class TournamentRegistrationController
{
    private $conn;

    private $table = "
        tournament_registration TR
        LEFT JOIN tournament T ON TR.IDTournament = T.IDTournament
        LEFT JOIN team TM ON TR.IDTeam = TM.IDTeam
        LEFT JOIN tournament_category_level TCL ON TR.IDTCL = TCL.IDTCL
        LEFT JOIN kategori K ON TCL.IDKategori = K.IDKategori
        LEFT JOIN level L ON TCL.IDLevel = L.IDLevel
        LEFT JOIN (
            SELECT IDTeam, COUNT(*) AS TotalMember
            FROM team_member
            GROUP BY IDTeam
        ) M ON TM.IDTeam = M.IDTeam
        LEFT JOIN (
            SELECT 
                TM2.IDTeam,
                GROUP_CONCAT(P.full_name ORDER BY P.full_name SEPARATOR ' & ') AS Players
            FROM team_member TM2
            JOIN player P ON TM2.IDPlayer = P.IDPlayer
            GROUP BY TM2.IDTeam
        ) PL ON TM.IDTeam = PL.IDTeam
    ";

    private $pk = "IDRegistration";
    private $sv = "TournamentRegistration";

    protected $displayedColumn = [
        'TR.IDRegistration',

        'TR.IDTournament',
        'T.NamaTournament',
        'T.NamaTournamentEN',
        'T.StatusTournament',

        // TCL
        'IFNULL(TR.IDTCL,"") AS IDTCL',
        'IFNULL(TCL.IDKategori,"") AS IDKategori',
        'K.NamaKategori',
        'K.TipeKategori',
        'IFNULL(TCL.IDLevel,"") AS IDLevel',
        'L.NamaLevel',
        'L.NamaLevelEN',
        'TCL.MaxSlot',
        'TCL.RegistrationFee',

        'TR.IDTeam',
        'TM.TeamName',
        'TM.CreateAt AS TeamCreateAt',

        'M.TotalMember',
        'PL.Players',

        'TR.PaymentStatus',
        'TR.PaymentProof',
        'TR.RegistrationDate',
        'TR.Status',

        'TR.CreateBy',
        'TR.CreateAt',
        'TR.LastUpdateBy',
        'TR.LastUpdateAt'
    ];

    public function __construct($conn)
    {
        $this->conn = $conn;
        $this->activityController = new ActivityController($this->conn);
        $this->userAksesController = new UserAksesController($this->conn);
    }

    public function select($post)
    {
        $listExclude = [];

        $listSearch = [
            'NamaTournament',
            'NamaTournamentEN',
            'TeamName',
            'Players'
        ];



        return runSelect(
            $this->conn,
            $this->table,
            $this->pk,
            $this->displayedColumn,
            $post,
            $listExclude,
            $listSearch
        );
    }

    public function delete($post)
    {
        try {
            $MainID = $post[$this->pk];
            if (empty($MainID)) {
                throw new Exception("Parameter tidak lengkap");
            }

            return runWithTransaction($this->conn, function ($conn) use ($MainID, $post) {

                // --------------------------------------
                // VALIDASI AKSES USER
                // --------------------------------------
                $UserLogin = "";
                $AksesNeeded = $this->sv . ".Delete"; // TournamentRegistration.Delete
                $userAksesFilterParam = [
                    ["IDUser", $post['IDUserLogin'], 1]
                ];

                $userAksesselectParam = [
                    "filters" => $userAksesFilterParam,
                    "rows_per_page" => 1,
                    "page_number" => 1,
                    "no_count" => true
                ];

                $userAksesresult = $this->userAksesController->select($userAksesselectParam);
                $listAkses = array_column($userAksesresult['list_data'], 'AksesName');

                if ($userAksesresult['Status'] == 1 && !empty($listAkses)) {
                    if (!in_array($AksesNeeded, $listAkses)) {
                        throw new Exception("User tidak memiliki otoritas akses - [" . $AksesNeeded . "]");
                    }
                    $UserLogin = $userAksesresult['Username'];
                } else {
                    throw new Exception($userAksesresult['Keterangan'] ?? "Akses pengguna tidak valid");
                }

                // --------------------------------------
                // AMBIL DATA LAMA 
                // --------------------------------------
                $oldData = [];
                $idArray = is_array($MainID)
                    ? $MainID
                    : array_filter(array_unique(array_map('trim', explode(',', $MainID))));

                if (empty($idArray)) {
                    throw new Exception("Tidak ada ID valid untuk dihapus.");
                }

                if (count($idArray) > 1000) {
                    throw new Exception("Maksimal 1000 data yang dapat dihapus sekaligus.");
                }

                $oldDataFilter = [
                    ["IDRegistration", $MainID, 7]
                ];

                $oldDataSelectParam = [
                    "filters" => $oldDataFilter,
                    "rows_per_page" => 0,
                    "page_number" => 1,
                    "no_count" => true
                ];

                $oldDataResult = $this->select($oldDataSelectParam);

                if ($oldDataResult['Status'] == 1) {
                    $oldData = $oldDataResult['list_data'];
                } else {
                    $msg = $oldDataResult['Keterangan'];
                    throw new Exception($msg);
                }


                // --------------------------------------
                // VALIDASI: ADA BARANG?
                // --------------------------------------
                $errorList = [];
                $deleteID = [];

                foreach ($oldData as $row) {
                    $canDelete = true;

                    if ($row['StatusTournament'] != "open_registration" && $row['StatusTournament'] != "closed_registration") {
                        $errorList[] = [
                            "IDTournament" => $row['IDTournament'],
                            "NamaTournament" => $row['NamaTournament'],
                            "Keterangan" => "Participant hanya bisa di hapus saat statu tournament adalah open registration atau closed registration."
                        ];
                        $canDelete = false;
                    }

                    // ==========================================
                    // VALIDASI 2: CEK TOURNAMENT_GROUP_TEAM
                    // ==========================================
                    if ($canDelete) {
                        $sqlCheck = "SELECT COUNT(*) as total FROM tournament_group_team WHERE IDRegistration = ?";
                        $stmtCheck = $conn->prepare($sqlCheck);
                        $stmtCheck->bind_param("i", $row['IDRegistration']);
                        $stmtCheck->execute();
                        $resultCheck = $stmtCheck->get_result();
                        $rowCheck = $resultCheck->fetch_assoc();
                        $stmtCheck->close();

                        if ($rowCheck['total'] > 0) {
                            $errorList[] = [
                                "IDTournament" => $row['IDTournament'],
                                "NamaTournament" => $row['NamaTournament'],
                                "Keterangan" => "Registrasi tidak dapat dihapus karena sudah dimasukkan ke dalam group tournament (tournament_group_team)."
                            ];
                            $canDelete = false;
                        }
                    }

                    if ($canDelete) {
                        $deleteID[] = $row['IDRegistration'];
                    }
                }



                // --------------------------------------
                // PROSES DELETE
                // --------------------------------------
                $statusDelete = 2;

                if (!empty($deleteID)) {
                    $statusDelete = 1;

                    try {
                        $conn->begin_transaction();

                        // --------------------------------------
                        // Ambil IDTeam berdasarkan IDRegistration
                        // --------------------------------------
                        $placeholders = implode(',', array_fill(0, count($deleteID), '?'));
                        $types = str_repeat('i', count($deleteID));

                        $sqlGetTeam = "SELECT IDTeam FROM tournament_registration 
                       WHERE IDRegistration IN ($placeholders)";
                        $stmtGetTeam = $conn->prepare($sqlGetTeam);
                        if (!$stmtGetTeam) {
                            throw new Exception("Gagal prepare get team: " . $conn->error);
                        }

                        $stmtGetTeam->bind_param($types, ...$deleteID);
                        $stmtGetTeam->execute();
                        $resultTeam = $stmtGetTeam->get_result();

                        $teamIDs = [];
                        while ($row = $resultTeam->fetch_assoc()) {
                            if (!empty($row['IDTeam'])) {
                                $teamIDs[] = $row['IDTeam'];
                            }
                        }
                        $stmtGetTeam->close();



                        if (!empty($teamIDs)) {

                            $teamPlaceholders = implode(',', array_fill(0, count($teamIDs), '?'));
                            $teamTypes = str_repeat('i', count($teamIDs));

                            // --------------------------------------
                            // 1. DELETE team_member
                            // --------------------------------------
                            $sqlDelMember = "DELETE FROM team_member 
                             WHERE IDTeam IN ($teamPlaceholders)";
                            $stmtDelMember = $conn->prepare($sqlDelMember);
                            if (!$stmtDelMember) {
                                throw new Exception("Gagal prepare delete team_member: " . $conn->error);
                            }
                            $stmtDelMember->bind_param($teamTypes, ...$teamIDs);
                            $stmtDelMember->execute();
                            $stmtDelMember->close();

                            // --------------------------------------
                            // 2. DELETE team
                            // --------------------------------------
                            $sqlDelTeam = "DELETE FROM team 
                           WHERE IDTeam IN ($teamPlaceholders)";
                            $stmtDelTeam = $conn->prepare($sqlDelTeam);
                            if (!$stmtDelTeam) {
                                throw new Exception("Gagal prepare delete team: " . $conn->error);
                            }
                            $stmtDelTeam->bind_param($teamTypes, ...$teamIDs);
                            $stmtDelTeam->execute();
                            $stmtDelTeam->close();
                        }

                        // --------------------------------------
                        // 3. DELETE tournament_registration
                        // --------------------------------------
                        $sqlDelReg = "DELETE FROM tournament_registration 
                      WHERE IDRegistration IN ($placeholders)";
                        $stmtDelReg = $conn->prepare($sqlDelReg);
                        if (!$stmtDelReg) {
                            throw new Exception("Gagal prepare delete registration: " . $conn->error);
                        }
                        $stmtDelReg->bind_param($types, ...$deleteID);
                        if (!$stmtDelReg->execute()) {
                            var_dump($stmtDelReg->error);
                        }




                        $stmtDelReg->close();

                        $conn->commit();

                    } catch (Exception $e) {
                        $conn->rollback();
                        $statusDelete = 2;

                        $errorList[] = [
                            "IDRegistration" => implode(',', $deleteID),
                            "Keterangan" => "Terjadi kesalahan saat menghapus data: " . $e->getMessage()
                        ];
                    }
                }



                // --------------------------------------
                // LOG AKTIVITAS
                // --------------------------------------
                $di = json_decode($post['DeviceInfo'], true);
                $Platform = $di['platform'] ?? '';
                $DeviceName = $di['device_name'] ?? '';
                $FullDevice = $di['FullDevice'] ?? $Platform . " - " . $DeviceName;
                $IP = $post['IP'] ?? ($_SERVER['REMOTE_ADDR'] ?? '');
                $Category = "tournament_registration";

                if (!empty($deleteID)) {
                    foreach ($oldData as $row) {
                        if (in_array($row['IDTournament'], $deleteID)) {
                            $KodeUnik = $row['IDTournament'];
                            $blacklist = [];
                            $whitelist = ["TeamName", "Players", "NamaTournament", "NamaKategori", "NamaLevel"];
                            $queryAcitivy = g_generateActivityQuery("tournament_registration", "Delete", $row, null, $blacklist, $whitelist);
                            $this->activityController->generateActivity(
                                $post['IDUserLogin'],
                                $UserLogin,
                                $queryAcitivy,
                                $FullDevice,
                                $IP,
                                $Category,
                                $KodeUnik
                            );
                        }
                    }
                }

                // --------------------------------------
                // FINAL RETURN
                // --------------------------------------
                if ($statusDelete === 1 && empty($errorList)) {
                    return [
                        "Status" => 1,
                        "Keterangan" => "Semua data berhasil dihapus",
                        "listErrorMessage" => []
                    ];
                } else {
                    return [
                        "Status" => 0,
                        "Keterangan" => "",
                        "listErrorMessage" => $errorList
                    ];
                }
            });
        } catch (Exception $e) {
            return [
                "Status" => 0,
                "Keterangan" => $e->getMessage(),
                "listErrorMessage" => []
            ];
        }
    }
}
?>