<?php

namespace App\Http\Controllers;

use App\Models\Climbing;
use App\Models\Ticket;
use App\Models\Guide;
use App\Models\Group;
use App\Events\PendakiTerdaftar; // Tambahkan import Event kamu di sini
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class TicketCounterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | AUTH SECTION
    |--------------------------------------------------------------------------
    */

    public function showLogin()
    {
        return view('ticketCounter.login');
    }

    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required'
        ]);

        if (Auth::guard('ticket_counter')->attempt($credentials)) {
            
            // --- TAMBAHAN UNTUK MONITORING ADMIN ---
            $user = Auth::guard('ticket_counter')->user();
            $user->update([
                'last_login_at' => now() // Mencatat jam masuk petugas
            ]);
            // ----------------------------------------

            $request->session()->regenerate();
            return redirect()->route('ticket.dashboard');
        }

        return back()->withErrors([
            'email' => 'Email atau password salah.',
        ]);
    }

    public function logout(Request $request)
    {
        // --- TAMBAHAN UNTUK MONITORING ADMIN ---
        $user = Auth::guard('ticket_counter')->user();
        if ($user) {
            $user->update([
                'last_logout_at' => now() // Mencatat jam keluar petugas
            ]);
        }
        // ----------------------------------------

        Auth::guard('ticket_counter')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('ticket.login');
    }

    /*
    |--------------------------------------------------------------------------
    | DASHBOARD SECTION (FLEKSIBEL TANGGAL & NOTIFIKASI GLOBAL)
    |--------------------------------------------------------------------------
    */

    public function dashboard(Request $request)
    {
        $fromDate = $request->input('from_date');
        $toDate   = $request->input('to_date');

        // 1. DATA UNTUK TABEL (Mengikuti Filter Tanggal)
        $query = \App\Models\Climbing::with(['ticket', 'group.guide', 'guide', 'ticketCounter']);

        if ($fromDate && $toDate) {
            $query->whereBetween('created_at', [
                Carbon::parse($fromDate)->startOfDay(),
                Carbon::parse($toDate)->endOfDay()
            ]);
        } else {
            $query->whereDate('created_at', Carbon::today());
        }

        $climbings = $query->orderByRaw('check_out_date IS NULL DESC')
                            ->orderBy('created_at', 'desc')
                            ->get();

        // 2. DATA UNTUK NOTIFIKASI (Global - Tidak terpengaruh filter tanggal pencarian)
        // Mencari semua pendaki yang belum turun dan sudah lebih dari 25 jam
        $overdueGlobal = \App\Models\Climbing::whereNull('check_out_date')
            ->where('created_at', '<=', now()->subHours(25))
            ->orderBy('created_at', 'desc')
            ->get();

        $guides = \App\Models\Guide::all();
        
        // Income dihitung berdasarkan hasil filter yang aktif
        $income = Ticket::withCount(['climbings' => function($q) use ($fromDate, $toDate) {
            if ($fromDate && $toDate) {
                $q->whereBetween('created_at', [Carbon::parse($fromDate)->startOfDay(), Carbon::parse($toDate)->endOfDay()]);
            } else {
                $q->whereDate('created_at', Carbon::today());
            }
        }])->get()->map(function ($ticket) {
            return [
                'name' => $ticket->name,
                'income' => $ticket->price * $ticket->climbings_count,
            ];
        });

        // WITA Adjustment: Memastikan data dikirim dengan konteks overdue global
        return view('ticketCounter.dashboard', compact(
            'climbings', 
            'overdueGlobal', 
            'guides', 
            'income', 
            'fromDate', 
            'toDate'
        ));
    }

    /*
    |--------------------------------------------------------------------------
    | REGISTRATION SECTION (TAMBAHAN UNTUK INPUT PENDAKI)
    |--------------------------------------------------------------------------
    */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'residence' => 'required',
            'phone_number' => 'required',
            'ticket_id' => 'required',
        ]);

        $climbing = new Climbing();
        $climbing->name = $request->name;
        $climbing->residence = $request->residence;
        $climbing->phone_number = $request->phone_number;
        $climbing->ticket_id = $request->ticket_id;
        $climbing->status = 'climbing';
        $climbing->ticket_counter_id = Auth::guard('ticket_counter')->id();

        // LOGIKA PENENTUAN GUIDE & GRUP
        if ($request->group_id) {
            // Cek jika yang dipilih adalah Individual Guide (mengandung string 'guide_')
            if (str_contains($request->group_id, 'guide_')) {
                $guideId = str_replace('guide_', '', $request->group_id);
                
                $climbing->guide_id = $guideId;
                $climbing->group_id = null; // Set null karena dia individu
            } else {
                // Jika yang dipilih adalah Grup murni
                $climbing->group_id = $request->group_id;
                
                // Ambil guide otomatis dari grup tersebut agar data sinkron
                $group = Group::find($request->group_id);
                if($group) {
                    $climbing->guide_id = $group->guide_id;
                }
            }
        }

        $climbing->save();

        // Sinyal real-time agar admin & loket terupdate
        broadcast(new PendakiTerdaftar())->toOthers();

        return back()->with('success', 'Registrasi pendaki ' . $climbing->name . ' berhasil!');
    }

    /*
    |--------------------------------------------------------------------------
    | FINISH SECTION (PENYESUAIAN REAL-TIME)
    |--------------------------------------------------------------------------
    */
    public function finish($id)
    {
        $climbing = Climbing::findOrFail($id);

        $climbing->update([
            'status' => 'finished',
            'check_out_date' => now(), // Mencatat jam turun WITA otomatis
            // Menambahkan ID petugas yang login untuk audit trail
            'ticket_counter_id' => Auth::guard('ticket_counter')->id(), 
        ]);

        // --- KIRIM SINYAL WEBSOCKET ---
        // Ini akan memicu refresh di halaman Admin & Loket secara otomatis
        broadcast(new PendakiTerdaftar())->toOthers();

        return back()->with('success', 'Pendaki ' . $climbing->name . ' berhasil dikonfirmasi turun.');
    }
}