<?php

namespace App\Http\Controllers;

use App;
use App\Provider;
use App\Stype;
use App\Business;
use App\Appoitment;
use App\Service;
use Illuminate\Support\Facades\Route;

use Carbon\Carbon;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    private $business;
 	public function __construct()
    {
        $route = Route::current();
        $this->routeParamters = $route->parameters();

        if(array_key_exists('slug', $this->routeParamters)) {
            $this->business = Business::findSlug($this->routeParamters['slug']);
        }     

        if($route->hasParameter('locale')) {
        	App::setLocale($route->parameter('locale'));
            if ( !in_array($route->parameter('locale'), ['en','ar']) ){
                return abort(404);
            }
            App::setLocale($route->parameter('locale'));
        }
    }
    public function index() 
    {
        // Get Business from DB
        $business = $this->business;

        // Get Business id
        $businessId = $business->business_id;

        // Get Business Name
        $title2 = 'business_name_'.App::getLocale();
        $title2 = $business->$title2;

        // Get Business currency code
        $currencyCode = 'business_currency_currency_code_'.App::getLocale();
        $currencyCode = $business->$currencyCode;

        $sWith = $business->business_start_with == 'services' ? 'services' : 'providers';

        if($sWith == 'services') {
            $iData = Stype::where('service_type_business_business_id',$businessId)->with('services')->get();
        }else {
            $iData = Provider::where('provider_business_business_id',$businessId)->get();
        }

        return view('home',compact('businessId','iData','currencyCode','title2','sWith'));
    }


    public function store(Request $req) {
        $businessId = $this->business->business_id;
        $providerId = $req->input('provider');
        $serviceId  = $req->input('service');
        $time       = $req->input('time');
        $time       = Carbon::parse($time);

        $providerTiming = Provider::where('provider_business_business_id',$businessId)
        ->where('provider_id',$providerId)
        ->whereHas('services', function ($query) use ($serviceId,$businessId){
                $query->where('service_id', $serviceId )
                        ->where('service_business_business_id', $businessId);
            })->firstOrFail()->timing;

        $daysWithCarbon = [
            'sun' => Carbon::SUNDAY,
            'mon' => Carbon::MONDAY,
            'tue' => Carbon::TUESDAY,
            'wed' => Carbon::WEDNESDAY,
            'thu' => Carbon::THURSDAY,
            'fri' => Carbon::FRIDAY,
            'sat' => Carbon::SATURDAY,
        ];
        $allowedMinute = [0,15,30,45];
        foreach ($providerTiming as $timing) {
            $from = Carbon::parse($timing->provider_timing_date_from);
            $to   = Carbon::parse($timing->provider_timing_date_to);
            if($time->dayOfWeek === $daysWithCarbon[$timing->provider_timing_day] && $time->between($from, $to)) {
                $now = Carbon::now();
                if($time->isSameDay($now) && $time->lt($now)){
                    $now->second = 0;
                    // minute will be 0 15 30 45 
                    if ($now->minute > 0 && $now->minute < 15) {
                        $now->minute = 15;
                    }elseif ($now->minute > 15 && $now->minute < 30) {
                        $now->minute = 30;
                    }elseif ($now->minute > 30 && $now->minute < 45) {
                        $now->minute = 45;
                    }elseif ($now->minute > 45) {
                        $now->minute = 0;
                        $now->hour++;
                    }
                    $fromT = $now;   
                }else {
                    $fromT = Carbon::parse($timing->provider_timing_from);
                    $fromT->year   = $time->year;
                    $fromT->month  = $time->month;
                    $fromT->day    = $time->day; 
                }
                $toT   = Carbon::parse($timing->provider_timing_to);
                $toT->year   = $time->year;
                $toT->month  = $time->month;
                $toT->day    = $time->day;
                if($time->between($fromT, $toT) && $time->second == 0 && in_array($time->minute, $allowedMinute)) {

                        $appoitments = Appoitment::where('appoitment_business_business_id',$businessId)
                        ->where('appoitment_provider_provider_id', $providerId)
                        ->whereBetween('appoitment_datetime_from',[$fromT,$toT])->get();

                        foreach($appoitments as $appoitment) {
                            $cfrom = Carbon::parse($appoitment->appoitment_datetime_from);
                            $cto = Carbon::parse($appoitment->appoitment_datetime_to);
                            if( $time->eq($cfrom) || $time->between($cfrom, $cto, false) ) {
                                // error return what you want
                                // now i just redirect to prev page
                                return back();
                            }
                        }
                        // you can do more than store "Appoitment"
                        $service = Service::findOrFail($serviceId);

                        $appoitmentStore = new Appoitment;

                        $appoitmentStore->appoitment_business_business_id = $businessId;
                        $appoitmentStore->appoitment_service_service_id   = $serviceId;
                        $appoitmentStore->appoitment_service_type_id      = $service->service_service_type_id;
                        $appoitmentStore->appoitment_provider_provider_id = $providerId;
                        $appoitmentStore->appoitment_booking_datetime     = Carbon::now();
                        $appoitmentStore->appoitment_datetime_from        = $time;
                        $appoitmentStore->appoitment_datetime_to          = $time->copy()->addMinutes($service->service_period);
                        $appoitmentStore->appoitment_satuts               = 1;

                        if($appoitmentStore->save()) {
                            // success store Appoitment action
                            return back()->with('success', trans('salon.success_appointment'));
                        }
                        
                }
            }
        }

        //error you can do more here
        return back();
        
    }

}
