<?php

namespace App\Http\Controllers\TestCenter;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use App\Models\Booking;
use App\Models\TestCenter;
use App\Repositories\SimplyBookRepository;
use App\Repositories\SmsRepository;
use DB;
use Crypt;
use PDF;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use Auth;
use Illuminate\Support\Facades\Mail;
use App\Mail\PdfCreate;
                    
/**
 * Class BookingController.
 */
class BookingController extends Controller
{
    /**
     * @var model
     * @var testCenterModel
     * @var simpleBookRepository
     * @var smsRepository
     */
    protected $model;
    protected $testCenterModel;
    protected $simpleBookRepository;
    protected $smsRepository;

    /**
     * BookingController constructor.
     *
     * @param model $model
     * @param testCenterModel $testCenterModel
     * @param simpleBookRepository $simpleBookRepository
     * @param smsRepository $smsRepository
     */
    public function __construct()
    {
        $this->model = new Booking;
        $this->testCenterModel = new TestCenter;
        $this->simpleBookRepository = new SimplyBookRepository;
        $this->smsRepository = new SmsRepository;
    }

    /**
     * BookingController list method.
     *
     */
    public function index(Request $req) 
    {
    	if($req->post()){
            //dd($req->post());
            $draw = $req->draw;
            $row = $req->start;
            $rowperpage = $req->length; // Rows display per page
            $columnIndex = $req->order[0]['column']; // Column index
            $columnName = $req->columns[$columnIndex]['data'] ? $req->columns[$columnIndex]['data'] : 'id'; // Column name
            $columnSortOrder = $req->order[0]['dir']; // asc or desc
            
            ## Total number of records without filtering
            $outputtotalRecord = $this->model
                                    ->leftJoin('test_centers','test_centers.id','=','bookings.provider_id')
                                    ->leftJoin('services','services.id','=','bookings.service_id')
                                    ->leftJoin('clients','clients.id','=','bookings.client_id')
                                    ->where('bookings.provider_id', Auth::guard('testcenter')->user()->test_center_id)
                                    ->where('bookings.status', 0)
                                    ->get()
                                    ->count();

            ## Total number of record with filtering
            $outputtotalRecordwithFilter = $this->model
                                            ->leftJoin('test_centers','test_centers.id','=','bookings.provider_id')
                                            ->leftJoin('services','services.id','=','bookings.service_id')
                                            ->leftJoin('clients','clients.id','=','bookings.client_id')
                                            ->where('bookings.provider_id', Auth::guard('testcenter')->user()->test_center_id)
                                            ->where('bookings.status', 0);
                                            //->groupBy('bookings.id');

            ## Fetch records
            $outputs = $this->model
                            ->select(DB::raw('bookings.*, bookings.id as sl_no,test_centers.test_center_name, services.name as service_name, clients.name as client_name'))
                            ->leftJoin('test_centers','test_centers.id','=','bookings.provider_id')
                            ->leftJoin('services','services.id','=','bookings.service_id')
                            ->leftJoin('clients','clients.id','=','bookings.client_id')
                            ->where('bookings.provider_id', Auth::guard('testcenter')->user()->test_center_id)
                            ->where('bookings.status', 0)
                            //->groupBy('bookings.id')
                            ->orderBy($columnName, $columnSortOrder)
                            ->skip($row)
                            ->take($rowperpage);

            
            $outputtotalRecordwithFilter = $outputtotalRecordwithFilter->get()->count();
            $outputs = $outputs->get();
            //echo $tests->toSql(); die;
            //echo '<pre>';print_r($quizes);die;
            $data = array();
            if($outputs){
                foreach($outputs as $key=>$output){
                    $bookingId = Crypt::encrypt($output->id);
                    if($output->status == 1) {
                        $status = 'Paid';
                    } else {
                        $status = 'Confirmed'; 
                    }
                    $data[] = array( 
                        "sl_no"=>$key+$row+1,
                        "invoice_number"=>$output->invoice_number,
                        "service_name"=>$output->service_name,
                        "client_name"=>$output->client_name,
                        "amount"=>$output->amount,
                        "currency"=>$output->currency,
                        "invoice_datetime"=>$output->invoice_datetime ? date('d-m-Y H:i:s', strtotime($output->invoice_datetime)) : '',
                        "status"=>$status,
                        "action"=>(($output->invoice_payment_received == 0) ? '<a href="javascript:void(0)" class="make_paid" title="Make Paid" data-id="'.base64_encode($output->id).'" style="padding: 5px;"><i class="fa fa-check-circle" style="color: #0062cc"></i></a>': ''),

                    );
                }
            }
            

            $response = array(
                "draw" => intval($draw),
                "iTotalRecords" => $outputtotalRecord,
                "iTotalDisplayRecords" => $outputtotalRecordwithFilter,
                "aaData" => $data
            );

            echo json_encode($response);die;
        }
        return view('testcenter.pages.booking.list'); 
    }

    /**
     * BookingController paid list method.
     *
     */
    public function paid(Request $req) 
    {
        if($req->post()){
            //dd($req->post());
            $draw = $req->draw;
            $row = $req->start;
            $rowperpage = $req->length; // Rows display per page
            $columnIndex = $req->order[0]['column']; // Column index
            $columnName = $req->columns[$columnIndex]['data'] ? $req->columns[$columnIndex]['data'] : 'id'; // Column name
            $columnSortOrder = $req->order[0]['dir']; // asc or desc
            
            ## Total number of records without filtering
            $outputtotalRecord = $this->model
                                    ->leftJoin('test_centers','test_centers.id','=','bookings.provider_id')
                                    ->leftJoin('services','services.id','=','bookings.service_id')
                                    ->leftJoin('clients','clients.id','=','bookings.client_id')
                                    ->where('bookings.provider_id', Auth::guard('testcenter')->user()->test_center_id)
                                    ->where('bookings.status', 1)
                                    ->get()
                                    ->count();

            ## Total number of record with filtering
            $outputtotalRecordwithFilter = $this->model
                                            ->leftJoin('test_centers','test_centers.id','=','bookings.provider_id')
                                            ->leftJoin('services','services.id','=','bookings.service_id')
                                            ->leftJoin('clients','clients.id','=','bookings.client_id')
                                            ->where('bookings.provider_id', Auth::guard('testcenter')->user()->test_center_id)
                                            ->where('bookings.status', 1);
                                            //->groupBy('bookings.id');

            ## Fetch records
            $outputs = $this->model
                            ->select(DB::raw('bookings.*, bookings.id as sl_no,test_centers.test_center_name, services.name as service_name, clients.name as client_name'))
                            ->leftJoin('test_centers','test_centers.id','=','bookings.provider_id')
                            ->leftJoin('services','services.id','=','bookings.service_id')
                            ->leftJoin('clients','clients.id','=','bookings.client_id')
                            ->where('bookings.provider_id', Auth::guard('testcenter')->user()->test_center_id)
                            ->where('bookings.status', 1)
                            //->groupBy('bookings.id')
                            ->orderBy($columnName, $columnSortOrder)
                            ->skip($row)
                            ->take($rowperpage);

            
            $outputtotalRecordwithFilter = $outputtotalRecordwithFilter->get()->count();
            $outputs = $outputs->get();
            //echo $tests->toSql(); die;
            //echo '<pre>';print_r($quizes);die;
            $data = array();
            if($outputs){
                foreach($outputs as $key=>$output){
                    $bookingId = Crypt::encrypt($output->id);
                    if($output->status == 1) {
                        $status = 'Paid';
                    } else {
                        $status = 'Confirmed'; 
                    }
                    $data[] = array( 
                        "sl_no"=>$key+$row+1,
                        "invoice_number"=>$output->invoice_number,
                        "final_invoice_no"=>$output->final_invoice_no,
                        "service_name"=>$output->service_name,
                        "client_name"=>$output->client_name,
                        "amount"=>$output->amount,
                        "currency"=>$output->currency,
                        "payment_datetime"=>$output->payment_datetime ? date('d-m-Y H:i:s', strtotime($output->payment_datetime)) : '',
                        "status"=>$status,
                        "action"=>'<a href="'.route('testcenter.booking.detail', base64_encode($output->id)).'" class="" title="Details" style="padding: 5px;"><i class="fa fa-eye" style="color: #0062cc"></i></a>'.
                            (($output->test_status > 0) ? '<a target="_blank" href="'.route('testcenter.booking.pdf', $bookingId).'" class="" title="Generate PDF" style="padding: 5px;"><i class="fa fa-file" style="color: #0062cc"></i></a>': '<a href="javascript:void(0)" data-id="'.$bookingId.'" class="update_test_status" title="Update Test Status" style="padding: 5px;"><i class="fa fa-exchange" style="color: #0062cc"></i></a>'),

                    );
                }
            }
            

            $response = array(
                "draw" => intval($draw),
                "iTotalRecords" => $outputtotalRecord,
                "iTotalDisplayRecords" => $outputtotalRecordwithFilter,
                "aaData" => $data
            );

            echo json_encode($response);die;
        }
        return view('testcenter.pages.booking.paid_list'); 
    }

    /**
     * Bank delete method.
     *
     * @param $req
     *
     * @return json
     */
    public function delete(Request $req) 
    {
        $response = [];
        if($req->post()){
            $id = base64_decode($req->id);
            $this->model->where('id', $id)->delete();             
            $response = array('status'=>200, 'message'=>'success', 'result'=>[]); 
            return response()->json($response);
        }
    }

    /**Status change method.
     *
     * @param $req
     *
     * @return json
     */
    public function status(Request $req) 
    {
        if($req->post()){
            $bookingDetails = $this->model->find(base64_decode($req->id));
            if($bookingDetails){
                $authentication = $this->simpleBookRepository->authentication();
                if($authentication){
                    $payment = $this->simpleBookRepository->payment($authentication, $bookingDetails->invoice_id);
					//dd($payment);
                    if($payment){
                        $this->model->where('id',base64_decode($req->id))->update([
                                'status'=>1, 
								'final_invoice_no'=>$payment['number'] ? $payment['number'] : null,
                                'invoice_payment_received'=>1,
                                'payment_datetime'=>$payment['payment_datetime'] ? $payment['payment_datetime'] : date('Y-m-d H:i:s'),
                                'deposit'=>$payment['deposit'] ? $payment['deposit'] : 0,
                            ]);
                        $response = array('status'=>200, 'message'=>'success', 'result'=>[]);   
                    } else {
                        $response = array('status'=>201, 'message'=>'failure', 'result'=>[]);   
                    }
                } else {
                    $response = array('status'=>201, 'message'=>'failure', 'result'=>[]);
                }                
            } else {
                $response = array('status'=>201, 'message'=>'failure', 'result'=>[]);
            }
            return response()->json($response);
        }
    }

    /**Details method.
     *
     * @param $req
     *
     * @return json
     */
    public function details(Request $req) 
    {
        if($req->id){
            $bookingDetails = $this->model
                                ->leftJoin('clients','clients.id','=','bookings.client_id')
                                ->leftJoin('services','services.id','=','bookings.service_id')
                                ->leftJoin('test_centers','test_centers.id','=','bookings.provider_id')
                                ->where('bookings.id', base64_decode($req->id))
                                ->select(DB::raw('*, bookings.id, clients.name as client_name, services.name as service_name'))
                                ->first();
            $bookingId = Crypt::encrypt(base64_decode($req->id));
            if($bookingDetails){
                return view('testcenter.pages.booking.details')
                    ->withBookingId($bookingId)             
                    ->withBooking($bookingDetails);               
            } else {
                return redirect()->route('testcenter.booking.list');
            }
        }
    }

    /**Status change method.
     *
     * @param $req
     *
     * @return json
     */
    public function test_status(Request $req) 
    {
        if($req->post()){
            $bookingId = Crypt::decrypt($req->id);
            $bookingDetails = $this->model->find($bookingId);
            if($bookingDetails){
                $updated = $this->model->where('id', $bookingId)->update(['test_status'=>$req->test_status]);
                if($updated){
                    $gen_str = route('testcenter.booking.pdf', $req->id);
                    $qrcode = QrCode::size(100)
                                ->format('svg')
                                ->generate($gen_str, storage_path('app/qrcodes/'.'qrcode-'.$bookingId.'.svg'));
                    $response = array('status'=>200, 'message'=>'success', 'result'=>[]);   
                } else {
                    $response = array('status'=>201, 'message'=>'failure', 'result'=>[]);   
                }              
            } else {
                $response = array('status'=>201, 'message'=>'failure', 'result'=>[]);
            }
            return response()->json($response);
        }
    }

    /**Generate PDF method.
     *
     * @param $req
     *
     * @return json
     */
    public function generate_pdf(Request $req) 
    {
        if($req->id){
            $bookingId = Crypt::decrypt($req->id);
            //echo '<img src="'.url('storage/qrcode-'.$bookingId.'.svg').'">';die;
            //$pdf = PDF::loadView('pdf.invoice', $data);
            $data['booking'] = $this->model
                                ->leftJoin('clients','clients.id','=','bookings.client_id')
                                ->leftJoin('services','services.id','=','bookings.service_id')
                                ->leftJoin('test_centers','test_centers.id','=','bookings.provider_id')
                                ->where('bookings.id', $bookingId)
                                ->select(DB::raw('*, bookings.id, clients.name as client_name, services.name as service_name'))
                                ->first();
            $pdf = PDF::loadView('testcenter.pages.booking.pdf', $data);
            //$pdf = PDF::loadHTML('<h1>Test</h1>');
			//$bid=rand(1,100);
			
            if(!file_exists(storage_path('app/pdf/qrcode-'.$bookingId.'.pdf'))){
                $pdf->save(storage_path('app/pdf/qrcode-'.$bookingId.'.pdf'));
                //$pdf->save(storage_path('app/pdf/qrcode-72'.$bid.'.pdf'));
                //Send SMS
                if(isset($data['booking']->phone)){
                    $sms = array(
                        "from" => "PHPElk",   /* Can be up to 11 alphanumeric characters */
                        "to" => $data['booking']->phone,  /* The mobile number you want to send to */
                        "message" => "Here is the PDF link. Please Click on this to get your report ".url('pdf/qrcode-'.$bookingId.'.pdf'),
						"dryrun" => "yes"
                    );
                    $sendSMS = $this->smsRepository->sendSMS($sms);
					//var_dump( $sendSMS);
                }
                //Email
                if(isset($data['booking']->email)){
                    /*$emailData = array(
                                'name' => isset($data['booking']->name) ? $data['booking']->name : '',
                                'link' => url('pdf/qrcode-'.$bookingId.'.pdf')
                            );*/
							
					$emailData = array(
                        'name' => isset($data['booking']->client_name) ? $data['booking']->client_name : '',
                        'link' => url('pdf/qrcode-'.$bookingId.'.pdf')
                    );
                    Mail::to($data['booking']->email, '')->send(new PdfCreate($emailData));
                }
            }

            //echo '<iframe src="'.url('pdf/qrcode-'.$bookingId.'.pdf').'"></iframe>'; 
            echo '<body style="margin:0px;padding:0px;overflow:hidden">
                    <iframe src="'.url('pdf/qrcode-'.$bookingId.'.pdf').'" frameborder="0" style="overflow:hidden;height:100%;width:100%" height="100%" width="100%"></iframe>
                </body>';die;
            //return $pdf->stream();
        }
    }
}
