<?php

namespace App\Http\Controllers;

use App\Models\Climbing;
use App\Models\Ticket;
use App\Models\Guide; 
use App\Models\Group; 
use App\Models\TicketCounter;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB; 
use Carbon\Carbon; 
use App\Events\PendakiTerdaftar; // Tambahan untuk Real-time
use App\Events\GuideUpdated;    // Tambahan untuk Real-time Guide
use App\Events\GroupUpdated;    // Tambahan untuk Real-time Group

class AdminController extends Controller
{
    // =====================
    // FUNGSI PRIVATE UNTUK NOTIFIKASI (Agar Sinkron di Semua Halaman)
    // =====================
    private function getNotificationData()
    {
        $overdue = \App\Models\Climbing::whereNull('check_out_date')
            ->where('created_at', '<=', now()->subHours(25)) // Batas Konsisten 25 Jam
            ->get();
            
        return [
            'overdueClimbers' => $overdue,
            'notifCount' => $overdue->count()
        ];
    }

    // =====================
    // LOGIN FORM
    // =====================
    public function showLoginForm()
    {
        return view('admin.login');
    }

    // =====================
    // MANAJEMEN PENJAGA TIKET (CRUD & LOGS)
    // =====================
    public function ticketCounter()
    {
        // Mengambil semua data dari tabel ticket_counters
        $counters = \App\Models\TicketCounter::all();
        
        // Data notifikasi
        $notifData = $this->getNotificationData();

        // PENYESUAIAN WITA:
        $dailyData = \App\Models\Climbing::selectRaw("DATE(CONVERT_TZ(created_at, '+00:00', '+08:00')) as date, COUNT(*) as count")
            ->where('created_at', '>=', now()->subDays(13))
            ->groupBy('date')->get();

        $monthlyData = \App\Models\Climbing::selectRaw('MONTHNAME(created_at) as month, COUNT(*) as total_pendaki')
            ->whereYear('created_at', date('Y'))
            ->groupBy('month')->get();

        return view('admin.ticket_counters', array_merge([
            'counters' => $counters, 
            'dailyData' => $dailyData, 
            'monthlyData' => $monthlyData
        ], $notifData));
    }

    public function storeTicketCounter(Request $request)
    {
        $request->validate([
            'nama' => 'required|string|max:255',
            'email' => 'required|email',
            'password' => 'required|min:6',
            'alamat' => 'required',
            'tanggal_lahir' => 'required|date',
        ]);

        // PENYESUAIAN: Nama kolom disamakan dengan struktur image_ff6644.jpg
        \App\Models\TicketCounter::create([
            'name'           => $request->nama,           // Kolom 'name' di DB
            'email'          => $request->email,          // Kolom 'email' di DB
            'password'       => bcrypt($request->password), 
            'address'        => $request->alamat,         // Kolom 'address' di DB
            'date_of_birth'  => $request->tanggal_lahir, // Kolom 'date_of_birth' di DB
            
            // Log login
            'last_login_at'  => null,
            'last_logout_at' => null,
        ]);

        return back()->with('success', 'Penjaga tiket berhasil ditambahkan!');
    }

    public function destroyTicketCounter($id)
    {
        // Mencari data berdasarkan Primary Key (id) dan menghapusnya
        \App\Models\TicketCounter::findOrFail($id)->delete();
        
        return back()->with('success', 'Data penjaga tiket berhasil dihapus!');
    }

    // =====================
    // FITUR EXPORT LAPORAN
    // =====================
    public function exportExcel()
    {
        $climbings = \App\Models\Climbing::with('ticket')->get();
        
        // Header agar browser mendownload file sebagai Excel
        header("Content-Type: application/vnd.ms-excel");
        header("Content-Disposition: attachment; filename=Laporan_Pendapatan_Tiket_".date('d-m-Y').".xls");
        
        echo "No\tNama Pendaki\tKategori\tHarga Tiket\tWaktu Naik\n";
        
        foreach($climbings as $key => $data) {
            $harga = $data->ticket->price ?? 0;
            $waktu = $data->created_at->timezone('Asia/Makassar')->format('d/m/Y H:i');
            echo ($key+1)."\t".$data->name."\t".($data->ticket->name ?? '-')."\t".$harga."\t".$waktu."\n";
        }
        exit;
    }

    public function exportPdf()
    {
        // Ambil data untuk tabel
        $climbings = \App\Models\Climbing::with(['ticket', 'group'])->get();
        $totalIncome = $climbings->sum(fn($c) => $c->ticket->price ?? 0);

        // PENYESUAIAN WITA: Grafik Harian (14 hari terakhir)
        $dailyData = \App\Models\Climbing::selectRaw("DATE(CONVERT_TZ(created_at, '+00:00', '+08:00')) as date, COUNT(*) as count")
            ->where('created_at', '>=', now()->subDays(13))
            ->groupBy('date')->orderBy('date', 'asc')->get();

        // Ambil data untuk Grafik Bulanan (Tahun ini)
        $monthlyData = \App\Models\Climbing::selectRaw('MONTHNAME(created_at) as month, COUNT(*) as total_pendaki')
            ->whereYear('created_at', date('Y'))
            ->groupBy('month')
            ->orderBy(DB::raw('MONTH(DB::raw("MIN(created_at)"))'), 'asc')->get();

        // Memanggil view khusus cetak
        return view('admin.reports.print_pendaki', compact('climbings', 'totalIncome', 'dailyData', 'monthlyData'));
    }

    // ==========================================
    // EXPORT EXCEL KHUSUS REKAP (FLEKSIBEL TANGGAL)
    // ==========================================
    public function exportRekapExcel(Request $request)
    {
        $start = $request->get('start_date');
        $end = $request->get('end_date');

        $query = \App\Models\Climbing::with('ticket');

        if ($start && $end) {
            $query->whereBetween('created_at', [$start . ' 00:00:00', $end . ' 23:59:59']);
        }

        $data = $query->orderBy('created_at', 'desc')->get();

        header("Content-Type: application/vnd.ms-excel");
        header("Content-Disposition: attachment; filename=Laporan_Rinci_Pendaki_".$start."_to_".$end.".xls");

        echo "No\tTanggal\tNama Pendaki\tKategori\tHarga Tiket\n";
        foreach($data as $i => $row) {
            $tgl = $row->created_at->format('d/m/Y');
            $nama = $row->name;
            $kat = $row->ticket->name ?? '-';
            $harga = $row->ticket->price ?? 0;
            echo ($i+1)."\t".$tgl."\t".$nama."\t".$kat."\t".$harga."\n";
        }
        echo "\t\t\tTOTAL PENDAPATAN\t".$data->sum(fn($c) => $c->ticket->price ?? 0);
        exit;
    }

    // ==========================================
    // EXPORT PDF KHUSUS REKAP (FLEKSIBEL TANGGAL)
    // ==========================================
    public function exportRekapPdf(Request $request)
    {
        $start = $request->get('start_date');
        $end = $request->get('end_date');

        $query = \App\Models\Climbing::with('ticket');

        if ($start && $end) {
            $query->whereBetween('created_at', [$start . ' 00:00:00', $end . ' 23:59:59']);
        }

        $climbings = $query->orderBy('created_at', 'asc')->get();
        $totalIncomeAll = $climbings->sum(fn($c) => $c->ticket->price ?? 0);

        return view('admin.reports.rekap_kustom_pdf', compact('climbings', 'totalIncomeAll', 'start', 'end'));
    }

    // ============================================================
    // DATA PENDAFTARAN (Halaman Pendaki - Biru)
    // Mendukung Filter Range Tanggal & Tahun + Pagination
    // ============================================================
    public function climbing(Request $request)
    {
        $fromDate = $request->input('from_date');
        $toDate   = $request->input('to_date');

        $query = \App\Models\Climbing::with(['ticket', 'group.guide', 'guide', 'ticketCounter']);

        // DISESUAIKAN: Statistik sekarang mengikuti filter pencarian
        if ($fromDate && $toDate) {
            $query->whereBetween('created_at', [
                \Carbon\Carbon::parse($fromDate)->startOfDay(),
                \Carbon\Carbon::parse($toDate)->endOfDay()
            ]);
        } else {
            $query->whereDate('created_at', \Carbon\Carbon::today());
        }

        // Simpan data hasil filter untuk statistik Mini Stat Cards (sebelum dipaginasi)
        $allFilteredClimbings = $query->get();

        // Baru lakukan paginasi untuk tabel
        $climbings = $query->orderBy('created_at', 'desc')->paginate(10)->withQueryString();

        $guides = \App\Models\Guide::all();
        $groups = \App\Models\Group::all(); 
        
        $totalTiket = $allFilteredClimbings->count();
        $income = $allFilteredClimbings->sum(fn($c) => $c->ticket->price ?? 0);

        $dailyData = \App\Models\Climbing::selectRaw("DATE(CONVERT_TZ(climbings.created_at, '+00:00', '+08:00')) as date, COUNT(*) as count")
            ->where('climbings.created_at', '>=', now()->subDays(13))
            ->groupBy('date')->orderBy('date', 'asc')->get();

        $monthlyData = \App\Models\Climbing::selectRaw('MONTH(climbings.created_at) as month_num, MONTHNAME(climbings.created_at) as month, COUNT(*) as total_pendaki')
            ->whereYear('climbings.created_at', date('Y'))
            ->groupBy('month_num', 'month')->orderBy('month_num', 'asc')->get();

        $notifData = $this->getNotificationData();

        return view('admin.climbings', array_merge([
            // PENTING: Kirim $allFilteredClimbings agar Mini Stat Card akurat
            'climbings' => $allFilteredClimbings, 
            'paginatedClimbings' => $climbings, // Tambahan untuk looping tabel jika perlu
            'groups' => $groups, 
            'guides' => $guides, 
            'income' => $income, 
            'totalTiket' => $totalTiket,
            'dailyData' => $dailyData, 
            'monthlyData' => $monthlyData, 
            'fromDate' => $fromDate, 
            'toDate' => $toDate
        ], $notifData));
    }

    // =====================
    // HAPUS DATA PENDAKI
    // =====================
    public function destroyClimbing($id)
    {
        \App\Models\Climbing::findOrFail($id)->delete();
        // Picu real-time agar admin tahu data dihapus
        broadcast(new PendakiTerdaftar())->toOthers(); 
        return redirect()->route('admin.climbing')->with('success', 'Data pendaki berhasil dihapus.');
    }

    // =====================
    // GROUPS MANAGEMENT
    // =====================
    public function group()
    {
        $groups = \App\Models\Group::all();
        $guides = \App\Models\Guide::all(); 
        $climbings = \App\Models\Climbing::all();
        $totalTiket = $climbings->count();
        $income = $climbings->sum(fn($c) => optional($c->ticket)->price ?? 0);

        $dailyData = \App\Models\Climbing::selectRaw("DATE(CONVERT_TZ(climbings.created_at, '+00:00', '+08:00')) as date, COUNT(*) as count")
            ->where('climbings.created_at', '>=', now()->subDays(13))
            ->groupBy('date')->orderBy('date', 'asc')->get();

        $monthlyData = \App\Models\Climbing::selectRaw('MONTH(climbings.created_at) as month_num, MONTHNAME(climbings.created_at) as month, COUNT(*) as total_pendaki')
            ->whereYear('climbings.created_at', date('Y'))
            ->groupBy('month_num', 'month')->orderBy('month_num', 'asc')->get();

        $notifData = $this->getNotificationData();

        return view('admin.groups', array_merge([
            'groups' => $groups, 'guides' => $guides, 'climbings' => $climbings, 'totalTiket' => $totalTiket, 'income' => $income, 'dailyData' => $dailyData, 'monthlyData' => $monthlyData
        ], $notifData));
    }

    public function storeGroup(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'guide_id' => 'required|exists:guides,id',
            'description' => 'nullable|string'
        ]);

        \App\Models\Group::create([
            'name' => $request->name,
            'guide_id' => $request->guide_id,
            'description' => $request->description,
            'climbing_date' => now(), 
        ]);

        // Picu Event Real-time Update Grup
        event(new \App\Events\GroupUpdated());

        return back()->with('success', 'Group pendakian berhasil ditambahkan!');
    }

    public function destroyGroup($id)
    {
        // Mencari data berdasarkan Primary Key (id) dan menghapusnya
        \App\Models\Group::findOrFail($id)->delete();
        
        // Picu Event Real-time Update Grup
        event(new \App\Events\GroupUpdated());

        return back()->with('success', 'Group pendakian berhasil dihapus!');
    }

    // =====================
    // DASHBOARD (Tabel Dashboard & Grafik)
    // =====================
    public function dashboard()
    {
        // Filter Data khusus Bulan Ini
        $startOfMonth = now()->startOfMonth();
        $endOfMonth = now()->endOfMonth();

        // 1. Ambil data pendaki (climbings) dengan paginasi
        $climbings = \App\Models\Climbing::with(['ticket', 'group.guide', 'guide', 'ticketCounter'])
            ->orderByRaw('check_out_date IS NULL DESC')
            ->orderBy('created_at', 'desc')
            ->paginate(10); 
        
        $guides = \App\Models\Guide::all();

        // 2. Hitung statistik khusus bulan ini saja
        $totalDomestik = \App\Models\Climbing::whereHas('ticket', function($q){ 
                $q->where('name', 'Domestik'); 
            })
            ->whereBetween('created_at', [$startOfMonth, $endOfMonth])
            ->count();

        $totalMancanegara = \App\Models\Climbing::whereHas('ticket', function($q){ 
                $q->where('name', 'Mancanegara'); 
            })
            ->whereBetween('created_at', [$startOfMonth, $endOfMonth])
            ->count();

        $income = \App\Models\Climbing::join('tickets', 'climbings.ticket_id', '=', 'tickets.id')
            ->whereBetween('climbings.created_at', [$startOfMonth, $endOfMonth])
            ->sum('tickets.price');

        $totalTiket = \App\Models\Climbing::whereBetween('created_at', [$startOfMonth, $endOfMonth])->count();

        // 3. Data Grafik
        $dailyData = \App\Models\Climbing::selectRaw("DATE(CONVERT_TZ(climbings.created_at, '+00:00', '+08:00')) as date, COUNT(*) as count")
            ->where('climbings.created_at', '>=', now()->subDays(13))
            ->groupBy('date')->orderBy('date', 'asc')->get();

        $monthlyData = \App\Models\Climbing::selectRaw('MONTH(climbings.created_at) as month_num, MONTHNAME(climbings.created_at) as month, COUNT(*) as total_pendaki')
            ->whereYear('climbings.created_at', date('Y'))
            ->groupBy('month_num', 'month')->orderBy('month_num', 'asc')->get();

        $notifData = $this->getNotificationData();

        return view('admin.dashboardAdmin', array_merge([
            'climbings' => $climbings, 
            'guides' => $guides, 
            'income' => $income, 
            'totalTiket' => $totalTiket, 
            'totalDomestik' => $totalDomestik, 
            'totalMancanegara' => $totalMancanegara,
            'dailyData' => $dailyData, 
            'monthlyData' => $monthlyData
        ], $notifData));
    }

    // =====================
    // HALAMAN STATISTIK (Hanya Grafik) - DENGAN FILTER TANGGAL FLEKSIBEL
    // =====================
    public function statistik(Request $request)
    {
        $fromDate = $request->input('from_date');
        $toDate   = $request->input('to_date');

        // Default jika filter kosong (tampilkan 14 hari terakhir)
        if (!$fromDate || !$toDate) {
            $fromDate = now()->subDays(13)->toDateString();
            $toDate   = now()->toDateString();
        }

        $dailyData = \App\Models\Climbing::selectRaw("DATE(CONVERT_TZ(created_at, '+00:00', '+08:00')) as date, COUNT(*) as count")
            ->whereBetween('created_at', [
                \Carbon\Carbon::parse($fromDate)->startOfDay(),
                \Carbon\Carbon::parse($toDate)->endOfDay()
            ])
            ->groupBy('date')->orderBy('date', 'asc')->get();

        $monthlyData = \App\Models\Climbing::selectRaw('MONTH(created_at) as month_num, MONTHNAME(created_at) as month, COUNT(*) as total_pendaki')
            ->whereYear('created_at', date('Y'))
            ->groupBy('month_num', 'month')->orderBy('month_num', 'asc')->get();

        $totalPendaki = \App\Models\Climbing::count();
        $totalBulanIni = \App\Models\Climbing::whereMonth('created_at', date('m'))->count();

        $notifData = $this->getNotificationData();

        return view('admin.statistik', array_merge([
            'dailyData' => $dailyData, 
            'monthlyData' => $monthlyData, 
            'totalPendaki' => $totalPendaki, 
            'totalBulanIni' => $totalBulanIni
        ], $notifData));
    }

    // =====================
    // HALAMAN KEUANGAN (Detail Pendapatan) - DISESUAIKAN UNTUK FILTER TANGGAL
    // =====================
    public function keuangan(Request $request)
    {
        $fromDate = $request->get('from_date');
        $toDate   = $request->get('to_date');

        $query = \App\Models\Climbing::with(['ticket']);

        // LOGIKA FILTER: Jika ada input tanggal, gunakan filter. Jika tidak, default bulan ini.
        if ($fromDate && $toDate) {
            $query->whereBetween('created_at', [
                \Carbon\Carbon::parse($fromDate)->startOfDay(),
                \Carbon\Carbon::parse($toDate)->endOfDay()
            ]);
        } else {
            $query->whereMonth('created_at', date('m'))
                  ->whereYear('created_at', date('Y'));
        }

        $climbings = $query->orderBy('created_at', 'desc')->get();
        
        $totalIncome = $climbings->sum(fn($c) => optional($c->ticket)->price ?? 0);
        $incomeDomestik = $climbings->filter(fn($c) => optional($c->ticket)->name == 'Domestik')->sum(fn($c) => $c->ticket->price ?? 0);
        $incomeMancanegara = $climbings->filter(fn($c) => optional($c->ticket)->name == 'Mancanegara')->sum(fn($c) => $c->ticket->price ?? 0);

        $dailyData = \App\Models\Climbing::selectRaw("DATE(CONVERT_TZ(created_at, '+00:00', '+08:00')) as date, COUNT(*) as count")
            ->where('created_at', '>=', now()->subDays(13))->groupBy('date')->get();

        $monthlyData = \App\Models\Climbing::selectRaw('MONTHNAME(created_at) as month, COUNT(*) as total_pendaki')->whereYear('created_at', date('Y'))->groupBy('month')->get();

        $notifData = $this->getNotificationData();

        return view('admin.keuangan', array_merge([
            'totalIncome' => $totalIncome, 
            'incomeDomestik' => $incomeDomestik, 
            'incomeMancanegara' => $incomeMancanegara, 
            'climbings' => $climbings, 
            'dailyData' => $dailyData, 
            'monthlyData' => $monthlyData
        ], $notifData));
    }

    // =====================
    // REKAP BULANAN
    // =====================
    public function rekapBulanan()
    {
        $rekap = \App\Models\Climbing::selectRaw("
                MONTH(created_at)  as bulan,
                YEAR(created_at)   as tahun,
                COUNT(*)           as total_pendaki,
                SUM(CASE WHEN EXISTS (
                    SELECT 1 FROM tickets
                    WHERE tickets.id = climbings.ticket_id
                    AND tickets.name = 'Domestik'
                ) THEN 1 ELSE 0 END) as total_domestik,
                SUM(CASE WHEN EXISTS (
                    SELECT 1 FROM tickets
                    WHERE tickets.id = climbings.ticket_id
                    AND tickets.name = 'Mancanegara'
                ) THEN 1 ELSE 0 END) as total_mancanegara,
                SUM((
                    SELECT COALESCE(tickets.price, 0)
                    FROM tickets
                    WHERE tickets.id = climbings.ticket_id
                )) as total_pendapatan
            ")
            ->groupBy('tahun', 'bulan')
            ->orderBy('tahun', 'desc')
            ->orderBy('bulan', 'desc')
            ->get();

        $dailyData = \App\Models\Climbing::selectRaw("DATE(CONVERT_TZ(climbings.created_at, '+00:00', '+08:00')) as date, COUNT(*) as count")
            ->where('climbings.created_at', '>=', now()->subDays(13))
            ->groupBy('date')->orderBy('date', 'asc')->get();

        $monthlyData = \App\Models\Climbing::selectRaw('MONTH(climbings.created_at) as month_num, MONTHNAME(climbings.created_at) as month, COUNT(*) as total_pendaki')
            ->whereYear('climbings.created_at', date('Y'))
            ->groupBy('month_num', 'month')->orderBy('month_num', 'asc')->get();

        $notifData = $this->getNotificationData();

        return view('admin.Rekap_bulanan', array_merge([
            'rekap' => $rekap, 'dailyData' => $dailyData, 'monthlyData' => $monthlyData
        ], $notifData));
    }

    // =====================
    // HALAMAN KHUSUS TIKET (Monitoring Tiket)
    // =====================
    public function tiket(Request $request) 
    {
        // 1. Ambil input filter tanggal
        $startDate = $request->get('start_date', date('Y-m-d'));
        $endDate = $request->get('end_date', date('Y-m-d'));

        // 2. Query dasar dengan filter tanggal
        $query = \App\Models\Climbing::with(['ticket'])
                ->whereBetween('created_at', [
                    \Carbon\Carbon::parse($startDate)->startOfDay(),
                    \Carbon\Carbon::parse($endDate)->endOfDay()
                ]);

        // 3. Ambil data koleksi (untuk Stat Cards)
        $allClimbings = $query->get();

        // 4. Ambil data paginasi (10 deret sesuai permintaan)
        $paginatedClimbings = \App\Models\Climbing::with(['ticket'])
                ->whereBetween('created_at', [
                    \Carbon\Carbon::parse($startDate)->startOfDay(),
                    \Carbon\Carbon::parse($endDate)->endOfDay()
                ])
                ->orderBy('created_at', 'desc')
                ->paginate(10)
                ->withQueryString();

        // 5. Hitung variabel untuk stat cards
        $totalTiket = $allClimbings->count(); 
        $totalDomestik = $allClimbings->filter(fn($c) => optional($c->ticket)->name == 'Domestik')->count();
        $totalMancanegara = $allClimbings->filter(fn($c) => optional($c->ticket)->name == 'Mancanegara')->count();
        $income = $allClimbings->sum(fn($c) => $c->ticket->price ?? 0);

        // 6. Grafik & Notifikasi (Tetap dipertahankan agar dashboard sinkron)
        $dailyData = \App\Models\Climbing::selectRaw("DATE(CONVERT_TZ(climbings.created_at, '+00:00', '+08:00')) as date, COUNT(*) as count")
            ->where('climbings.created_at', '>=', now()->subDays(13))
            ->groupBy('date')->orderBy('date', 'asc')->get();

        $monthlyData = \App\Models\Climbing::selectRaw('MONTH(climbings.created_at) as month_num, MONTHNAME(climbings.created_at) as month, COUNT(*) as total_pendaki')
            ->whereYear('climbings.created_at', date('Y'))
            ->groupBy('month_num', 'month')->orderBy('month_num', 'asc')->get();

        $notifData = $this->getNotificationData();

        // 7. Return view dengan data paginasi
        return view('admin.tiket', array_merge([
            'climbings' => $paginatedClimbings, 
            'totalTiket' => $totalTiket, 
            'totalDomestik' => $totalDomestik, 
            'totalMancanegara' => $totalMancanegara, 
            'income' => $income, 
            'dailyData' => $dailyData, 
            'monthlyData' => $monthlyData
        ], $notifData));
    }

    // =====================
    // UPDATE HARGA TIKET
    // =====================
    public function updatePrices(Request $request) 
    {
        $request->validate([
            'domestik_price' => 'required|numeric|min:0',
            'mancanegara_price' => 'required|numeric|min:0',
        ]);

        // Update harga di database berdasarkan nama tiket
        \App\Models\Ticket::where('name', 'Domestik')->update(['price' => $request->domestik_price]);
        \App\Models\Ticket::where('name', 'Mancanegara')->update(['price' => $request->mancanegara_price]);

        return back()->with('success', 'Harga tiket berhasil diperbarui!');
    }

    // =====================
    // LOGIN PROCESS
    // =====================
    public function login(Request $request) {
        $credentials = $request->validate(['username' => 'required', 'password' => 'required']);
        if (Auth::guard('admin')->attempt($credentials)) {
            $request->session()->regenerate();
            return redirect()->route('admin.dashboard');
        }
        return back()->withErrors(['username' => 'Username atau password salah.']);
    }

    // =====================
    // GUIDE MANAGEMENT (DIUBAH UNTUK MODAL)
    // =====================
    public function guide() { 
        $guides = \App\Models\Guide::all(); 
        $climbings = \App\Models\Climbing::all(); 
        
        $dailyData = \App\Models\Climbing::selectRaw("DATE(CONVERT_TZ(climbings.created_at, '+00:00', '+08:00')) as date, COUNT(*) as count")
            ->where('climbings.created_at', '>=', now()->subDays(13))
            ->groupBy('date')->orderBy('date', 'asc')->get();

        $monthlyData = \App\Models\Climbing::selectRaw('MONTH(climbings.created_at) as month_num, MONTHNAME(climbings.created_at) as month, COUNT(*) as total_pendaki')
            ->whereYear('climbings.created_at', date('Y'))
            ->groupBy('month_num', 'month')->orderBy('month_num', 'asc')->get();

        $notifData = $this->getNotificationData();

        return view('admin.guide', array_merge([
            'guides' => $guides, 'climbings' => $climbings, 'dailyData' => $dailyData, 'monthlyData' => $monthlyData
        ], $notifData)); 
    }

    public function storeGuide(Request $request) { 
        $request->validate(['name' => 'required', 'phone' => 'required', 'date_of_birth' => 'nullable|date']); 
        \App\Models\Guide::create([
            'name' => $request->name, 
            'email' => $request->email, 
            'phone' => $request->phone, 
            'description' => $request->description, 
            'date_of_birth' => $request->date_of_birth
        ]); 

        // Picu Event Real-time Update Guide
        event(new \App\Events\GuideUpdated());

        return back()->with('success', 'Guide berhasil ditambahkan!'); 
    }

    // DISESUAIKAN: Mengembalikan JSON untuk Modal Edit
    public function editGuide($id) 
    { 
        $guide = \App\Models\Guide::findOrFail($id); 
        return response()->json($guide); 
    }

    // DISESUAIKAN: Update data menggunakan back() agar tetap di halaman yang sama
    public function updateGuide(Request $request, $id) 
    { 
        $guide = \App\Models\Guide::findOrFail($id); 
        $guide->update($request->all()); 

        // Picu Event Real-time Update Guide
        event(new \App\Events\GuideUpdated());

        return back()->with('success', 'Data guide berhasil diperbarui!'); 
    }

    public function destroyGuide($id) { 
        $guide = \App\Models\Guide::findOrFail($id); 
        $guide->delete(); 

        // Picu Event Real-time Update Guide
        event(new \App\Events\GuideUpdated());

        return back()->with('success', 'Guide berhasil dihapus!'); 
    }

    // =====================
    // LOGOUT
    // =====================
    public function logout(Request $request) { 
        Auth::guard('admin')->logout(); 
        $request->session()->invalidate(); 
        $request->session()->regenerateToken(); 
        return redirect()->route('admin.login'); 
    }

    public function index() {}
}