<?php

namespace App\Http\Controllers;

use App\Models\Climbing;
use App\Models\Ticket;
use App\Models\Group;
use App\Models\Guide;
use Illuminate\Http\Request;
use App\Events\PendakiTerdaftar;

class ClimbingController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | FORM DOMESTIK
    |--------------------------------------------------------------------------
    */

    public function createDomestic()
    {
        $groups = Group::all();
        $guides = Guide::all();
        return view('climbing.domestic', compact('groups', 'guides'));
    }

    public function storeDomestic(Request $request)
    {
        $ticket = Ticket::where('name', 'Domestik')->firstOrFail();

        $validated = $request->validate([
            'name'         => 'required|string|max:255',
            'residence'    => 'required|string|max:255',
            'phone_number' => 'required|string|max:20', 
            'group_id'     => 'nullable|string', 
        ]);

        $finalGroupId = null;
        $finalGuideId = null;

        // LOGIKA PEMISAHAN GUIDE & GRUP
        if ($request->group_id) {
            if (str_starts_with($request->group_id, 'guide_')) {
                // Skenario 1: Pilih Guide Individu
                $finalGuideId = str_replace('guide_', '', $request->group_id);
            } else {
                // Skenario 2: Pilih Grup
                $finalGroupId = $request->group_id;
                // Ambil guide otomatis dari grup agar sinkron
                $group = Group::find($request->group_id);
                if($group) {
                    $finalGuideId = $group->guide_id;
                }
            }
        }

        Climbing::create([
            'name'              => $validated['name'],
            'residence'         => $validated['residence'],
            'phone_number'      => $validated['phone_number'], 
            'ticket_id'         => $ticket->id,
            'group_id'          => $finalGroupId,
            'guide_id'          => $finalGuideId, // <--- INI WAJIB DIISI
            'status'            => 'climbing',
            'check_in_date'     => now(),
            'check_out_date'    => null,
            'ticket_counter_id' => null,
        ]);

        broadcast(new PendakiTerdaftar())->toOthers();

        return back()->with('success', 'Registrasi Domestik berhasil!');
    }

    /*
    |--------------------------------------------------------------------------
    | FORM MANCANEGARA
    |--------------------------------------------------------------------------
    */

    public function createForeign()
    {
        $groups = Group::all();
        $guides = Guide::all();
        return view('climbing.foreign', compact('groups', 'guides'));
    }

    public function storeForeign(Request $request)
    {
        $ticket = Ticket::where('name', 'Mancanegara')->firstOrFail();

        $validated = $request->validate([
            'name'         => 'required|string|max:255',
            'residence'    => 'required|string|max:255',
            'phone_number' => 'required|string|max:20', 
            'group_id'     => 'nullable|string',
        ]);

        $finalGroupId = null;
        $finalGuideId = null;

        if ($request->group_id) {
            if (str_starts_with($request->group_id, 'guide_')) {
                $finalGuideId = str_replace('guide_', '', $request->group_id);
            } else {
                $finalGroupId = $request->group_id;
                $group = Group::find($request->group_id);
                if($group) {
                    $finalGuideId = $group->guide_id;
                }
            }
        }

        Climbing::create([
            'name'              => $validated['name'],
            'residence'         => $validated['residence'],
            'phone_number'      => $validated['phone_number'], 
            'ticket_id'         => $ticket->id,
            'group_id'          => $finalGroupId,
            'guide_id'          => $finalGuideId, // <--- INI WAJIB DIISI
            'status'            => 'climbing',
            'check_in_date'     => now(),
            'check_out_date'    => null,
            'ticket_counter_id' => null,
        ]);

        broadcast(new PendakiTerdaftar())->toOthers();

        return back()->with('success', 'Registrasi Mancanegara berhasil!');
    }

    public function finish($id)
    {
        $climbing = Climbing::findOrFail($id);
        
        $climbing->update([
            'status'            => 'finished', // Ubah ke 'finished' agar sinkron dengan dashboard
            'check_out_date'    => now(),
            'ticket_counter_id' => auth('ticket_counter')->id(),
        ]);

        broadcast(new PendakiTerdaftar())->toOthers();

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