<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Carbon\Carbon;

class FrontendController extends Controller
{
    public function index()
    {	
        $todayDate = Carbon::now()->today()->toDateString();

        return view('frontend.dashboard', compact('todayDate'));
    }

    public function saveAppoinmentData(Request $request)
    {
        $request->validate([
            'branch_id'=> 'required',
            'provider_id'=> 'required',
            'service_id'=> 'required',
            'name'=> 'required',
            'phone'=> 'required',
            'email'=> 'nullable',
            'problem'=> 'required',
            'appoinment_date'=> 'required',
        ]);

        $data = $request->all();
        $selctedDate = Carbon::parse($request->appoinment_date)->format('Y-m-d');
        $data['appoinment_date'] = $selctedDate;
        //To check appoinment id & already exist or not...
        $singleAppoinmentData = Appoinment::whereDate('appoinment_date', $selctedDate)
                                ->where('phone', $request->phone)->first();
        if(isset($singleAppoinmentData) && $singleAppoinmentData != null){
            return response()->json([
                'error' => 'Sorry, Your appointment has been booked.!',
                'serial_no' => $singleAppoinmentData->appoinment_id
            ]);
        }else{
            //To check serial number...
            $nextSerialNo = Appoinment::whereDate('appoinment_date', $selctedDate)->max('appoinment_id') + 1;
            if($nextSerialNo != 1){
                $data['appoinment_id'] = $nextSerialNo;
            }else{
                $data['appoinment_id'] = 1;
            }
        }

        if($singleAppoinmentData = Appoinment::create($data)){
            return response()->json([
                'success' => 'Appoinment created successfully.',
                'serial_no' => $singleAppoinmentData->appoinment_id
            ]);
        }else{
            return response()->json([
                'error' => 'Sorry, Something is wrong.!'
            ]);
        }
    }

    //To fetch the privacy  policy...
    public function privacyPolicy()
    {   
        return view('frontend.privacyPolicy');
    }
    
    //To fetch the access denied page...
    public function accessDenied()
    {   
        return view('error.accessDenied');
    }

}
