<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Booking;
use App\Transfer;
use App\Branch;
use App\Installment;
use Illuminate\Contracts\Encryption\DecryptException;
use Crypt;
use App\Bank;
use App\Account;
use PDF;
use App\Nominee;

use EF;
class LetterController extends Controller
{
	private $letters;

	public function __construct()
	{
		$this->letters = [];

	}

    public function index()
    {   

    	$booking = new Booking;
        $branch = new Branch;
        $bank = new Bank;

    	$condition = ['Approve'];

    	$booking_list =  $booking->getAllBookings($condition);

        
        
        return view('letters.letters_view',
        	[
        		'booking_list'      => $booking_list,
                'branch_list'       =>  $branch->getBranchList(),
                'bank_list'         =>  $bank->getAllBanks(),

        	]
    );
       
    }

    public function getLetterData(Request $request)
    {
        $letter_list = implode(',', EF::getLettersList());

        $request->validate([
         'letter_type' => 'In:'.$letter_list,
         ]); 
    	try
        { 

        	
        	if(\Request::ajax())
        	{
        		$data = array('right_view' => false,'bottom_view' => false);
				$this->setLetterDetail($request->booking,$request->date,$request->bank);

        		$type = strtolower(str_replace(' ','_',$request->letter_type));
	        	
	        	$data['right_view']   = $this->getLetterDetailByName($type.'_right');

	        	$data['bottom_view']  = ' '.$this->getLetterDetailByName($type.'_bottom');

	        	return $data;  
        
        	}

        }
        catch(DecryptException $e)
        {

        }
    }
    public function getLetterPdf(Request $request)
    {
       $letter_list = implode(',', EF::getLettersList());
    
        $request->validate([
         'letter_type' => 'In:'.$letter_list,
         ]);

        try
        {  

            // CRYPT 
            $booking_id          = decrypt($request->booking);
            $bank_id             = decrypt($request->bank);
            // END 

            // VARIABLE DECLARATION
            $booking          = new Booking;
            $transfer         = new Transfer;
            $installment      = new Installment;
            $bank             = new Bank;
           

            $date        = Date('Y-m-d');
            $year = Date('Y');
            $month = Date('m');
            $operator    = '<=';

             if($request->date == '')
                 {
                    $data = date('Y-m-d',strtotime($date));
                 }
             else 
                 {
                    $data = date('Y-m-d',strtotime($request->date));
                 }

            $curr_booking   = $booking->getBookingById($booking_id);

            $balance_detail = $booking->getBalanceDetail($booking_id); 

            $bank_details   = $bank->getBankById($bank_id);

            $transfer_details = $transfer->getCurrentTransferByBookingId($booking_id);

            $booking_outstanding  = $installment->getOverDueByBooking($booking_id,$date);

            $installment_due     = $installment->getLatestInstallmentDue($date,'<=',$booking_id,'desc');
            // $current_month_installment_due     = $installment->getCurrentInstallmentDue($year,$month,$booking_id,'asc');



            

            if(isset($curr_booking->id))
            {

                if($request->letter_type == "Thanks Letter")
                {

         

                    $pdf = PDF::loadView('letters.pdf_thanks_letter',[

                    'booking'       => $curr_booking,
                    'user'          => $curr_booking->user,
                    'plot'          => $curr_booking->plot,
                    'date'          => $date,

 

                    ]);

                    return $pdf->setPaper('a4', 'portrait')->stream('Thanks Letter.pdf');
                }


                elseif($request->letter_type == "Possession Letter")
                {

                    $pdf = PDF::loadView('letters.pdf_possession_letter',[

                    'booking'       => $curr_booking,
                    'user'          => $curr_booking->user,
                    'plot'          => $curr_booking->plot,
                    'date'          => $date,

 

                    ]);

                    return $pdf->setPaper('a4', 'portrait')->stream('Possession Letter.pdf');
                }

                elseif($request->letter_type == "Intimation of Possession Letter")
                {

                    $pdf = PDF::loadView('letters.pdf_intimation_possession_letter',[

                    'booking'       => $curr_booking,
                    'user'          => $curr_booking->user,
                    'plot'          => $curr_booking->plot,
                    'date'          => $date,

 

                    ]);

                    return $pdf->setPaper('a4', 'portrait')->stream('Intimation of Possession  Letter.pdf');
                }

                elseif($request->letter_type == "Transfer Rights Letter")
                {

                    if(isset($transfer_details->id))
                    {

                        $pdf = PDF::loadView('letters.pdf_transfer_rights',[

                        'booking'       => $curr_booking,
                        'user'          => $curr_booking->user,
                        'plot'          => $curr_booking->plot,
                        'date'          => $date,
                        'transfer_details' => $transfer_details,

     

                        ]);

                        return $pdf->setPaper('a4', 'portrait')->stream('Transfer Rights  Letter.pdf');
                    }
                }

                elseif($request->letter_type == "Allotment Rights Letter")
                {

                    $pdf = PDF::loadView('letters.pdf_allotment_rights',[

                    'booking'       => $curr_booking,
                    'user'          => $curr_booking->user,
                    'plot'          => $curr_booking->plot,
                    'date'          => $date,

 

                    ]);

                    return $pdf->setPaper('a4', 'portrait')->stream('Allotment Rights Letter.pdf');

                }

                 elseif($request->letter_type == "Payment Reminder Letter")
                {

                   if(isset($installment_due->id))
                   {
                        if(isset($bank_details->id))
                        {
                            // if(isset($current_month_installment_due->due_date)){

                            //     $installment_due_date = $current_month_installment_due->due_date;

                            //     $installment_amount   = ($current_month_installment_due->amount) - ($installment->received_amount);

                            //     $total_amount = $booking_outstanding['balance'] + (($current_month_installment_due->amount) - ($installment->received_amount));
                            // }
                            // else{
                            //     $installment_due_date = false;
                            //     $installment_amount = 0;
                            //     $total_amount = 0;
                            // }

                            $pdf = PDF::loadView('letters.pdf_payment_reminder',[

                             'booking'              => $curr_booking,
                             'user'                 => $curr_booking->user,
                             'plot'                 => $curr_booking->plot,
                             'date'                 => $date,
                             'bank_details'         => $bank_details,
                             'swift_code'           => $bank_details->swift_code,
                             'bank_code'            => $bank_details->branch_code,
                             'bank_name'            => $bank_details->bank_name,
                             'booking_outstanding'  => $booking_outstanding,
                             'installment_due_date' => $installment_due->due_date,
                             'installment_amount'   => ($installment_due->amount) - ($installment->received_amount),
                             'total_amount'         => $booking_outstanding['balance'] + (($installment_due->amount) - ($installment->received_amount)),


                             // 'installment_due_date' => $installment_due_date,
                             // 'installment_amount'   => $installment_amount,
                             // 'total_amount'         => $total_amount,
                    
                            ]);

                            return $pdf->setPaper('a4', 'portrait')->stream('Payment Reminder Letter.pdf');

                        }
                    }
                    else{
                        parent::warningMessage('Not Have Any Pending Dues Exist!');
                        return redirect()->back(); 
                    }
             
            
                }
                elseif($request->letter_type == "Confirmation of Allotment")
                {

                    $booking_details = $booking->getBookingById($curr_booking->id);

                    $balance_detail = $booking_details->getBalanceDetail($booking_details->id);

                    $booking_installments = $installment->getBookingInstallments($booking_details->id);

                    $installment_count = @count($installment->getBookingInstallmentByType($booking_details->id,'Installment'));

                    $nominee = new Nominee;

                    $co_owner = $nominee->getBookingNok($curr_booking->id,$curr_booking->user->id,["Co-Owner"]);



                     if(@count($co_owner) > 0){
                        $co_owner = $co_owner->first()->user;
                     }
                     else{ 
                        $co_owner = '';
                     }
                    if($booking_details->plan_type ==  'One Time')
                    {
                       $payment_term = 'One Time Payment';
                    }
                    else
                    {
                       if($installment_count > 0)
                       {
                           $payment_term = $installment_count.' '.$booking_details->installment_mode.' Installments';
                       }
                       else
                       {
                           $payment_term = ' Monthly Installments';
                       }
                    }


                    $pdf = PDF::loadView('letters.pdf_confirmation_of_allotment',[

                        'booking'       => $curr_booking,
                        'user'          => $curr_booking->user,
                        'plot'          => $curr_booking->plot,
                        'date'          => $date,
                        'installment'   => $booking_installments,'balancedetail' => $balance_detail,
                        'installment'   => $booking_installments,'payment_term'  => $payment_term,
                        'co_owner'      =>$co_owner,
     

                    ]);

                    return $pdf->setPaper('a4', 'portrait')->stream('Confirmation of Allotment  Letter.pdf');
                }
 

        }
    }
        catch (DecryptException $e) 
        {
            
        }

        parent::errorMessage('No such record found.');


       return redirect()->back();    
}


      public function getBranchBookings($branch)
    {
        try
        {             
            if(\Request::ajax())
            {
             $booking = new Booking;
             $branch = decrypt($branch);
             $booking_list = $booking->getBookingByColumn('branch_id',$branch);

             $view = '<option value="{{Crypt::encrypt(0)}}">Select Booking</option>';

             foreach($booking_list as $rows)
             {
               $view .= '<option value="'.Crypt::encrypt($rows->id).'">'.$rows->plot->floor.' '.$rows->plot->plot_id.' '.$rows->plot->category.'</option>';
             }
                return $view;
        
            }

        }
        catch(DecryptException $e)
        {

        }
    }


   
    public function setLetterDetail($booking_id,$letter_date,$bank_id)
    {
    	try
        { 
        
                   
                         $date           = Date('Y-m-d');
                         $operator       = '<=';

                         if($letter_date == '')
                         {
                           $data['date'] = date('Y-m-d',strtotime($date));
                         }
                         else 
                         {
                            $data['date'] = date('Y-m-d',strtotime($letter_date));
                         }


        	 
        	$booking          = new Booking;
            $transfer         = new Transfer;
            $installment      = new Installment;
            $bank             = new Bank;
            $account          = new Account;

	        $booking_id = decrypt($booking_id);

            $bank_id = decrypt($bank_id);

            $bank_details = $bank->getBankById($bank_id);

	        $booking_details = $booking->getBookingById($booking_id);

            $transfer_details = $transfer->getCurrentTransferByBookingId($booking_id);


            $booking_outstanding  = $installment->getOverDueByBooking($booking_id,$date);


            $installment_due     = $installment->getLatestInstallmentDue($date,'<=',$booking_id,'asc');
            
            $nominee = new Nominee;

            $co_owner = $nominee->getBookingNok($booking_details->id,$booking_details->user->id,["Co-Owner"]);

           

             if(@count($co_owner) > 0){
                $co_owner = ', '.$co_owner->first()->user->name;
             }
             else{
                $co_owner = '';
             }


	      	$user = $booking_details->user;

	      	$plot = $booking_details->plot;

            $data['booking'] = $booking_details;

            $data['curr_booking'] = $booking_details;

            $installment_count = @count($installment->getBookingInstallmentByType($booking_details->id,'Installment'));
 $payment_term = NULL;

           $balance_detail = $booking_details->getBalanceDetail($booking_details->id);


    $booking_installments = $installment->getBookingInstallments($booking_details->id);
                 if($booking_details->plan_type ==  'One Time')
                 {
                    $payment_term = 'One Time Payment';
                 }
                 else
                 {
                    if($installment_count > 0)
                    {
                        $payment_term = $installment_count.' '.$booking_details->installment_mode.' Installments';
                    }
                    else
                    {
                        $payment_term = ' Monthly Installments';
                    }
                 }

                 $data['payment_term'] = $payment_term;


            $data['user']    = $user;

            $data['plot']    = $plot;

             $data['co_owner']             = $co_owner;
            

            //THANKS LETTER 

           $this->letters['thanks_letter_right'] = '<div class="row"><div class = "col-md-6"><h6>BOOKING DETAILS :</h6><h6>Project Name: '.$booking_details->branch->name.'</h6><h6> Ref: '.$booking_details->reference_number.'</h6> <h6>Name: '.$user->name.' '.$user->fname.'</h6><h6>Mobile: '.$user->contact.'</h6><h6>Email: '.EF::filterEmail($user->email).'</h6><h6>Address: '.$user->temp_address.'</h6></div><div class = "col-md-6"><h6>PLOT DETAILS:</h6><h6> Plot No: '.$plot->plot_id.' '.$plot->block_name.'</h6><h6> Plot Location: '.$plot->location.'</h6><h6>Cnic: '.$booking_details->user->cnic.'</h6></div>';

           $this->letters['thanks_letter_bottom'] = view('letters.pdf_thanks_letter',$data);

           //POSSESSION LETTER
           $this->letters['possession_letter_right'] = $this->letters['thanks_letter_right'];

           $this->letters['possession_letter_bottom'] = view('letters.possession_letter',$data);

           //INTIMATION OF POSSESSION LETTER

            $this->letters['intimation_of_possession_letter_bottom'] = view('letters.pdf_intimation_possession_letter',$data);

            $this->letters['intimation_of_possession_letter_right'] = $this->letters['thanks_letter_right'];


               //ALLOTMENT RIGHTS LETTER 

             $this->letters['allotment_rights_letter_bottom'] = view('letters.pdf_allotment_rights',$data);


            //   $this->letters['allotment_rights_letter_right'] = $this->letters['thanks_letter_right'];

            //   $this->letters['confirmation_of_allotment_bottom'] = view('letters.pdf_confirmation_of_allotment',$data + ['installment' => $booking_installments,'balancedetail' => $balance_detail])->render();

            $this->letters['confirmation_of_allotment_bottom'] = view('letters.pdf_confirmation_of_allotment',$data + ['installment' => $booking_installments,'balancedetail' => $balance_detail]);

            $this->letters['confirmation_of_allotment_right'] = $this->letters['thanks_letter_right'];



            if(isset($transfer_details->id))
            {
                  $data['transfer_details'] = $transfer_details;


                $this->letters['transfer_rights_letter_bottom'] = view('letters.pdf_transfer_rights',$data);

                $this->letters['transfer_rights_letter_right'] =  '<div class="row"><div class = "col-md-6"><h6>BOOKING DETAILS:</h6><h6>Project Name: '.$booking_details->branch->name.'</h6><h6> Ref: '.$booking_details->reference_number.'</h6> <h6>Name: '.$user->name.' '.$user->fname.'</h6><h6>Mobile: '.$user->contact.'</h6><h6>Email: '.EF::filterEmail($user->email).'</h6><h6>Address: '.$user->temp_address.'</h6></div><div class = "col-md-6"><h6>PLOT DETAILS:</h6><h6> Plot No: '.$plot->plot_id.' '.$plot->block_name.'</h6><h6> Plot Location: '.$plot->location.'</h6><h6>TRANSFER DETAILS</h6><h6>Transfered By: '.$transfer_details->getowner->name.'</h6><h6>Owner Cnic: '.$transfer_details->getowner->cnic.'</h6><h6>Transfer Fee: '.$transfer_details->transfer_fee.'</h6></div>';
            }
            else
            {
                $this->letters['transfer_rights_letter_bottom'] = '';

                $this->letters['transfer_rights_letter_right'] = 'No Such Record Found For Selected Booking';

               
            }

         
            
           
           if(isset($installment_due->id))
           {

            if(isset($bank_details->id))
            {

             $accounts_list = $account->getAccountByBank($bank_details->id);
             $data['bank_details']         = $bank_details;
             $data['swift_code']           = $bank_details->swift_code;
             $data['bank_code']            = $bank_details->branch_code;
             $data['bank_name']            = $bank_details->bank_name;
             $data['booking_outstanding']  = $booking_outstanding;
             $data['installment_due_date'] = $installment_due->due_date;
             $data['co_owner']             = $co_owner;
             $data['installment_amount']   = ($installment_due->amount) - ($installment->received_amount);
             $data['total_amount']         = $booking_outstanding['balance'] + $data['installment_amount'];
             $this->letters['payment_reminder_letter_bottom'] = view('letters.pdf_payment_reminder',$data);
             $this->letters['payment_reminder_letter_right'] = $this->letters['thanks_letter_right'];
            }
             
            
           }
            else
            {
                 $this->letters['payment_reminder_letter_bottom'] = '';
                 $this->letters['payment_reminder_letter_right'] = 'No Such Record Found For Selected Booking';

               
            }



		}
        catch(DecryptException $e)
        {

    	}
    }

    public function getLetterDetailByName($name)
    {
    	if(isset($this->letters[$name]))
    	{

    		return $this->letters[$name];
    	}
    	else
    	{
    		return '';
    	}
    }
}
