<?php

namespace App\Http\Controllers;

use App\Models\DoctorSchedule;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;
use Exception;

class DoctorScheduleController extends Controller
{
    
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $user = Auth::user();
        
        // Vista normal de horarios, mostrar solo los del doctor en sesión
        if (User::isADoctor($user)) {
            $schedules = DoctorSchedule::where('doctor_id', $user->id)->get();
            return view('doctor.schedules.index', compact('schedules'));
        }
        
        return redirect()->route('home');
    }

    /**
     * Muestra todos los horarios de doctores para los usuarios
     */
    public function viewAllSchedules()
    {
        $schedules = DoctorSchedule::with('doctor')
            ->where('active', true)
            ->get();
            
            
        return view('admin.doctor-schedules.index', compact('schedules'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $dayOptions = [
            0 => __('doctor-schedules.days.sunday'),
            1 => __('doctor-schedules.days.monday'),
            2 => __('doctor-schedules.days.tuesday'),
            3 => __('doctor-schedules.days.wednesday'),
            4 => __('doctor-schedules.days.thursday'),
            5 => __('doctor-schedules.days.friday'),
            6 => __('doctor-schedules.days.saturday')
        ];

        return view('doctor.schedules.create', compact('dayOptions'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'day_of_week' => 'required|integer|between:0,6',
            'start_time' => 'required',
            'end_time' => 'required|after:start_time',
            'timezone' => 'required'
        ]);

        $schedule = new DoctorSchedule();
        $schedule->doctor_id = Auth::user()->id;
        $schedule->day_of_week = $request->day_of_week;
        $schedule->start_time = $request->start_time;
        $schedule->end_time = $request->end_time;
        $schedule->timezone = $request->timezone;
        $schedule->active = true;
        $schedule->save();

        return redirect()->route('doctor.schedules.index')
            ->with('success', __('doctor-schedules.success.created'));
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\DoctorSchedule  $schedule
     * @return \Illuminate\Http\Response
     */
    public function show(DoctorSchedule $schedule)
    {
        $schedule->load('doctor');
        return view('doctor.schedules.show', compact('schedule'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\DoctorSchedule  $schedule
     * @return \Illuminate\Http\Response
     */
    public function edit(DoctorSchedule $schedule)
    {
        $dayOptions = [
            0 => __('doctor-schedules.days.sunday'),
            1 => __('doctor-schedules.days.monday'),
            2 => __('doctor-schedules.days.tuesday'),
            3 => __('doctor-schedules.days.wednesday'),
            4 => __('doctor-schedules.days.thursday'),
            5 => __('doctor-schedules.days.friday'),
            6 => __('doctor-schedules.days.saturday')
        ];

        return view('doctor.schedules.edit', compact('schedule', 'dayOptions'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\DoctorSchedule  $schedule
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, DoctorSchedule $schedule)
    {
        $request->validate([
            'day_of_week' => 'required|integer|between:0,6',
            'start_time' => 'required',
            'end_time' => 'required|after:start_time',
            'timezone' => 'required'
        ]);

        // Mantener el doctor_id original, no modificarlo
        $originalDoctorId = $schedule->doctor_id;
        
        $schedule->day_of_week = $request->day_of_week;
        $schedule->start_time = $request->start_time;
        $schedule->end_time = $request->end_time;
        $schedule->timezone = $request->timezone;
        $schedule->active = $request->has('active');
        
        // Asegurarse que no cambia el doctor_id
        $schedule->doctor_id = $originalDoctorId;
        
        $schedule->save();

        // Determinar a dónde redirigir basado en la ruta de origen
        if (str_starts_with(request()->path(), 'admin/')) {
            return redirect()->route('admin.schedules.index')
                ->with('success', __('doctor-schedules.success.updated'));
        } else {
            return redirect()->route('doctor.schedules.index')
                ->with('success', __('doctor-schedules.success.updated'));
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\DoctorSchedule  $schedule
     * @return \Illuminate\Http\Response
     */
    public function destroy(DoctorSchedule $schedule)
    {
        $schedule->delete();
        
        // Determinar a dónde redirigir basado en la ruta de origen
        if (str_starts_with(request()->path(), 'admin/')) {
            return redirect()->route('admin.schedules.index')
                ->with('success', __('doctor-schedules.success.deleted'));
        } else {
            return redirect()->route('doctor.schedules.index')
                ->with('success', __('doctor-schedules.success.deleted'));
        }
    }

    /**
     * Check doctor availability
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function checkAvailability(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'doctor_id' => 'required',
            'date' => 'required|date_format:Y-m-d',
            'time' => 'required|date_format:H:i',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first()
            ]);
        }

        $doctor = User::findOrFail($request->doctor_id);
        $date = Carbon::parse($request->date);
        $dayOfWeek = $date->dayOfWeek;
        $time = $request->time;

        // Check if doctor has a schedule for this day
        $schedule = DoctorSchedule::where('doctor_id', $request->doctor_id)
            ->where('day_of_week', $dayOfWeek)
            ->where('is_active', true)
            ->first();

        if (!$schedule) {
            return response()->json([
                'success' => false,
                'message' => __('doctor-schedules.no_schedule_for_day')
            ]);
        }

        // Check if the requested time is within the doctor's schedule
        if ($time < $schedule->start_time || $time > $schedule->end_time) {
            return response()->json([
                'success' => false,
                'message' => __('doctor-schedules.outside_working_hours')
            ]);
        }

        // Here you would check for existing appointments
        // This is a simplified version
        
        return response()->json([
            'success' => true,
            'message' => __('doctor-schedules.doctor_available')
        ]);
    }
}
