<?php

namespace App\Http\Controllers\Frontend;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Repositories\Frontend\ServiceRepository;
use App\Repositories\Frontend\CityRepository;
use App\Repositories\Frontend\ServiceProviderCityRepository;
use App\Repositories\Frontend\Auth\UserRepository;
use App\Models\Auth\User;
use App\Repositories\Frontend\QuotationRepository;
use App\Repositories\Frontend\QuotationToImagesRepository;
use App\Repositories\Frontend\QuotationToSpRepository;
use Illuminate\Support\Facades\Mail;
use App\Mail\Frontend\quotation\QuotationSend;
use App\Http\Requests\Frontend\Quotation\SendQuotationRequest;
use App\Models\Quotation;
use Session;

header('Cache-Control: no cache'); //no cache
//session_cache_limiter('private_no_expire'); // works
if(!isset($_SESSION))
    session_start();

/**
 * Class HomeController.
 */
class HomeController extends Controller
{
    /**
     * @var ServiceRepository
     */
    protected $servicesRepository;
    //protected $serviceproviderservicerepository;
    protected $serviceprovidercityrepository;
    protected $userrepository;
    protected $quotationRepository;
    protected $qotationToImagesRepository;
    protected $quotationToSpRepository;

    /**
     * UserController constructor.
     *
     * @param ServiceRepository $servicesRepository
     * @param CityRepository $cityRepository
     * @param ServiceProviderCityRepository $serviceProviderCityRepository
     * @param UserRepository $userrepository
     * @param QuotationRepository $quotationRepository
     * @param QuotationToImagesRepository $qotationToImagesRepository
     * @param quotationToSpRepository $quotationToSpRepository
     */
    public function __construct(ServiceRepository $servicesRepository, CityRepository $cityRepository, ServiceProviderCityRepository $serviceprovidercityrepository , UserRepository $userrepository, QuotationRepository $quotationRepository, QuotationToImagesRepository $qotationToImagesRepository, QuotationToSpRepository $quotationToSpRepository)
    {
        $this->servicesRepository = $servicesRepository;
        $this->cityRepository = $cityRepository;
        $this->ServiceProviderCityRepository = $serviceprovidercityrepository;
       // $this->ServiceProviderServiceRepository = $serviceproviderservicerepository;
        $this->UserRepository = $userrepository;
        $this->QuotationRepository = $quotationRepository;
        $this->QuotationToImagesRepository = $qotationToImagesRepository;
        $this->quotationToSpRepository = $quotationToSpRepository;
    }


    /**
     * @return \Illuminate\View\View
     */
    public function index()
    {
        return view('frontend.index');
    }

    /**
     * All service list with search page
     *
     * @return \Illuminate\View\View
     */
    public function service_list(Request $request)
    {
        //Unset Session
        $_SESSION['redirect_url'] = '';
        $_SESSION['slug'] = '';
        $_SESSION['city'] = '';
        $_SESSION['service'] = '';
        return view('frontend.service_list')
                ->withServices($this->servicesRepository->getActive('category_name', 'asc'))
                ->withCities($this->cityRepository->getAll());
    } 

    /**
     * After login redirect with post value
     *
     * @return \Illuminate\View\View
     */
    public function after_login_post(Request $request)
    {
        $slug = '';
        $redirect_url = '';
        $city = '';
        $service = '';
        if($_SESSION['slug']!='') {
            $slug = $_SESSION['slug'];
            return \Redirect::to(url('service-provider-list-post/'.$_SESSION['slug']));
        } else {
            if($_SESSION['redirect_url']!='')
                $redirect_url = $_SESSION['redirect_url'];
            if($_SESSION['city']!='')
                $city = $_SESSION['city'];
            if($_SESSION['service']!='')
                $service = $_SESSION['service'];

            //Unset Session
            $_SESSION['redirect_url'] = '';
            $_SESSION['slug'] = '';
            $_SESSION['city'] = '';
            $_SESSION['service'] = '';
            return view('frontend.after_login_post')
                    ->withCity($city)
                    ->withService($service);
        }
        
    }

    /**
     * Quatation post view
     *
     * @param Request values $request,
     *        Service slug $slug 
     *
     * @return \Illuminate\View\View
     */
    public function service_provider_list(Request $request, $slug='')
    {
        $catId = '';
        $city = '';
        $service = '';
        if($slug){
            $catDetails = $this->servicesRepository->getCategoryIdByName($slug);
            $catId = $catDetails->id;
        } else {
            if($request->input('city')) {
                $city = $request->input('city');
            } 
            if($request->input('service')) {
                $service = $request->input('service');
            } 
        }
        
        //Unset Session
        $_SESSION['redirect_url'] = '';
        
        if(!Auth::user()) { //Set Session if not login
            $_SESSION['redirect_url'] = 'frontend.after.login.post';
            if($slug)
                $_SESSION['slug'] = $slug;
            if($city)
                $_SESSION['city'] = $city;
            if($service)
                $_SESSION['service'] = $service;
        }
        //echo 'Session<pre>';print_r($_SESSION);die;
        $data = $this->UserRepository->getServiceProviderOnCityService($city, $service, $catId);
        return view('frontend.service_provider_list_post')
                    ->withServiceslist($data);
                
    }

    /**
     * Service providers details view
     *
     * @param Service provider id  $id 
     *
     * @return \Illuminate\View\View
     */
    public function service_provider_single($id,$city_id = null, $service_id = null) {
        $spId = base64_decode( urldecode( $id ) );
        $data = $this->UserRepository->findById($spId);
        //dd($id.'|'.$city_id.'|'.$service_id);
        return view('frontend.service_provider_single')
                    ->withSpsingle($data)
                    ->withCity($city_id)
                    ->withService($service_id);
    }

    /**
     * Service providers list view
     *
     * @param Request values  $request 
     *
     * @return \Illuminate\View\View
     */
    public function quotation_request(Request $request)
    {
        $spid = json_encode($request->input('splist'));
        $cityId = $request->input('cities');
        if ($cityId != 0) {
             $cityDetails = $this->cityRepository->getAllById($cityId);
        } else {
             $cityDetails = $this->cityRepository->getAll();
        }
            
        $serviceId = $request->input('services');
        if ($serviceId !=0 ) {
            $serviceDetails = $this->servicesRepository->getAllById($serviceId);
        } else {
            $serviceDetails = $this->servicesRepository->getAll();
        }
        
        return view('frontend.quotation_request')
                 ->withSpid($spid)
                 ->withServiceId($serviceId)
                 ->withCityId($cityId)
                 ->withServiceAll($serviceDetails)
                 ->withCityAll($cityDetails);
    }


    /**
     * Quatation form submit 
     *
     * @param Request values  $request
     *  
     * @return \Illuminate\View\View
     */
    public function quotation_submit(Request $request, Quotation $quotation)
    {
        $fromname = config('app.admin_name');
        $fromemail = config('app.admin_email');

        $splists = json_decode($request->input('splists'));
        $spData = array();
        foreach($splists as $spId){
           $spData[] = $this->UserRepository->findById($spId);
        }
        
        $quotation =  $this->QuotationRepository->create(array('quotation_message'=>$request->input('quote_msg'), 'posted_id'=>$request->input('postedid'), 'city_id' => $request->input('cities'), 'service_id' => $request->input('services')));
        $quotation_id = $quotation->id;
        if($request->file('uploadfiles')){ 
            foreach ($request->file('uploadfiles') as $key => $value) { 
                $auotationtoimages = $this->QuotationToImagesRepository->create(
                    array(
                        'quotation_id'=>$quotation_id,
                        'image_location'=>$value
                    )

                ); 
            }
        }

        $quoteImages = $quotation->getQuoteImages;

        $selectedImage = [];
        if ($quoteImages) {
            foreach ($quoteImages as $key => $value) {
                array_push($selectedImage, $value->image_location);
            }
        }

        $quotationData = array('message' => $request->input('quote_msg'), 'attachment' => $selectedImage, 'senderemail' => $fromemail, 'sendername' => $fromname);
        foreach($spData as $key => $val){
            //Insert into quatation to service provider table
            $quoteToSp = $this->quotationToSpRepository->create(
                array(
                    'quotation_id'=>$quotation_id,
                    'serviceprovider_id'=>$val->id
                )
            );
            //Mail::to($val->email,'test')->send(new QuotationSend($quotationData));
            /*****************User mail ***************/
            $userdetails = $this->UserRepository->findById(auth()->user()->id);
            $to = $val->email;
            $email_text='   <tr>
                                <td style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px;color: #333; ">
                                   <p>Dear <span style="">'.$val->first_name.' '.$val->last_name.'</span> </p>
                                </td>
                            </tr>
                            <tr>
                                <td style="font-family: sans-serif; color: #333; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
                                   <p>We are informing you that, there is a User updated the Work Done percentage to you quotation job.</p>
                                   <p>Quotation details follows:</p>
                                   <p>Quotation ID: '.$quotation_id.'</p>
                                   <p>User Name: '.$userdetails->first_name.' '.$userdetails->last_name.'</p>
                                   <p>Quotation Date: '.date('Y-m-d H:i:s').'</p>
                                   <p>Quotation Message: '.$request->input('quote_msg').'</p>
                                </td>
                            </tr>
                            <tr>
                                <td style="font-family: Helvetica, arial, sans-serif; font-size: 13px; color: #333333; text-align:left;line-height: 24px;">';
                                    foreach($selectedImage as $val) {
                                        $asset_url = asset('storage/'.$val, true);
            $email_text.='              <img src="'.$asset_url.'" width="100px" style="margin: 10px; " aria-hidden="true">';
                                    }
            $email_text.='      </td>
                                <td style="font-family: sans-serif; color: #333; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
                                   <p>Stay connected with us. We appreciate very much your trust in us.</p>
                                   <p>Please do not hesitate to contact us for any other requests.</p>
                                </td>
                            </tr>';
                    //echo $to; die;
            $data['email_text'] = $email_text;    
            Mail::send('frontend.mail.email_template', $data, function($message) use ($to, $fromemail, $fromname, $selectedImage)
            {
                $message->from($fromemail, $fromname);
                $message->to($to);
                $message->subject('Quotation post mail');
                foreach($selectedImage as $key => $val){
                    $message->attach(storage_path('app/public/'. $val));
                }
            });
            /*********Service provider mail end************/
        }
        /*****************Admin mail ***************/
        $to = 'testdevloper007@gmail.com';
        $email_text='   <tr>
                            <td style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px;color: #333; ">
                               <p>Hi <span style="">Admin</span> </p>
                            </td>
                        </tr>
                        <tr>
                            <td style="font-family: sans-serif; color: #333; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
                               <p>We are informing you that, there is a User updated the Work Done percentage to you quotation job.</p>
                               <p>Quotation details follows:</p>
                               <p>Quotation ID: '.$quotation_id.'</p>
                               <p>User Name: '.$userdetails->first_name.' '.$userdetails->last_name.'</p>
                               <p>Quotation Date: '.date('Y-m-d H:i:s').'</p>
                               <p>Quotation Message: '.$request->input('quote_msg').'</p>
                            </td>
                        </tr>
                        <tr>
                            <td style="font-family: Helvetica, arial, sans-serif; font-size: 13px; color: #333333; text-align:left;line-height: 24px;">';
                            foreach($selectedImage as $val) {
                                    $asset_url = asset('storage/'.$val, true);
        $email_text.='              <img src="'.$asset_url.'" width="100px" style="margin: 10px; " aria-hidden="true">';
                                }   
        $email_text.='      </td>
                            <td style="font-family: sans-serif; color: #333; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
                               <p>Thanks</p>
                            </td>
                        </tr>';
                //echo $to; die;
        $data['email_text'] = $email_text;    
        Mail::send('frontend.mail.email_template', $data, function($message) use ($to, $fromemail, $fromname, $selectedImage)
        {
            $message->from($fromemail, $fromname);
            $message->to($to);
            $message->subject('Quotation post mail');
            foreach($selectedImage as $key => $val){
                $message->attach(storage_path('app/public/'. $val));
            }
        });
        /*********Admin mail end************/
        return response()->json( array('success' => true) );
                
    }
}
