<?php

namespace App\Http\Controllers;
use Illuminate\Contracts\Encryption\DecryptException;

use Illuminate\Http\Request;
use App\Http\Requests\BookingRequest;
use App\Plot;
use App\Branch;
use App\Booking;
use App\Nominee;
use App\Commission;
use App\Installment;
use App\Document;
use App\User;
use App\Head;
use App\Payment;
use Crypt;
use App\CancelBooking;
use EF;
use App\Designation;
use App\Department;
use App\ViewBooking;
use DataTables;

class BookingController extends Controller
{

  public static $id;

  public function __construct()
  {

    BookingController::$id=null;
  }

  public function index()
  {

    $condition     = ['Approve','Unapprove'];
    $employee_type = ['Employee'];
    $dealer_type   = ['Dealer','Sub Dealer'];


    $plot            =       new Plot;
    $branch          =       new Branch;
    // $booking         =       new Booking;
    $user            =       new User;
    $commission      =       new Commission;
    $designation     =       new Designation;
    $department      =       new Department;

    $user->getUserListByType($dealer_type);

    $data = [

      'block'                  =>  $plot->getPlotListByColoumn('block_name',[],['unsold']) ,
      'branch'                 =>  $branch->getBranchList(),
      'employee'               =>  $user->getUserListByType($employee_type),
      'dealer'                 =>  $user->getUserListByType($dealer_type),
      // 'booking_list'           =>  $booking->getAllBookings($condition),
      'commission'             =>  $commission,
      'plot_labels'            => EF::plotWhiteLabel(),
      'designation_list'       => $designation->getDesignationList(),
      'department_list'        => $department->getDepartmentList(),

    ];
    $data['booking_view'] = view('components.booking.table_booking',$data);


    return view('booking.manage_booking',$data);
  }



  public function bookingMature($id)
  {

    try
    {
        $id = decrypt($id);
        $booking = new Booking;

      $booking->updateStatus($id,'Unapprove');
    }
    catch (DecryptException $e)
    {

    }


    return redirect('booking');

  }

  public function showDatatableBookings(Request $request)
  {
  
    $condition     = ['Approve','Unapprove'];
    $booking      = new ViewBooking;
    $branch_id = decrypt($request->branch);
    $booking_list = ViewBooking::get();
    
    $count = 0;
    
    
    
    if(isset($branch_id) && $branch_id > 0)
    {
      $booking_list = $booking_list->where('branch_id' , $branch_id);
      
    }

    return DataTables::of($booking_list)

      ->addColumn('count', function($rows) use (&$count) {
          return strval(++$count);

      })
      
    // ->addColumn('booking_details', function($rows) {
    //   return EF::showPlotFormat($rows->plot_detail);
    // })
    ->addColumn('status', function($rows){

      if($rows->status == "Approve") 
      {
        $view = '<span class="badge badge-success">'.EF::getstatus($rows->status).'</span>';
      }
      elseif($rows->status == "Unapprove")
      {
        $view = '<span class="badge badge-primary">'.EF::getstatus($rows->status).'</span>';
      }
      else
      {
        $view = '<span class="badge badge-warning"> '.$rows->status.'</span>';
      }

      return $view;

    })
    
    ->addColumn('salesperson', function($rows) {
      $commission = new Commission;

      $booking_salesperson_list = $commission->getBookingSalesPerson($rows->id);
      $view = '';
      foreach($booking_salesperson_list as $salesperson)
      {
        if($salesperson->user->type == "Employee")
        {
          $view .= '<span class="badge badge-primary">'.strtoupper($salesperson->user->name).'</span>';
        }
      }
    })
    ->addColumn('created_at', function($rows) {
      return EF::dateFormat($rows->created_at);
    })
    ->addColumn('tags', function($rows) {
      return view('booking.actions.booking_tags',[
        'rows' => $rows,
    ]);
    })
    ->addColumn('action', function($rows) {
      $pass_data = array(
        'id'                       => Crypt::encrypt($rows->id),
        'reg_date'                 => EF::dateFormat(($rows->created_at)),
      );

      return view('booking.actions.booking_actions',[
          'rows' => $rows,
          'pass_data' => $pass_data,
      ]);
  })
  ->setRowClass(function ($rows) {

    return strtolower($rows->is_block == 0) == '' ? 'alert-danger' : '';

})
    ->rawColumns(['status','count','salesperson','tags','action'])
    ->make(true);
      
  }
     
    public function updateInstallmentMode(Request $request)// Installment Mode Exist in Booking table
    {
      try
       {
          $form_collect = $request->input();

          $form_collect['booking_id']  = decrypt($form_collect['booking_id']);

          if($form_collect['gap'] == 1){

           $form_collect['gap'] ='Monthly';

          }
          else if($form_collect['gap'] == 3){

              $form_collect['gap'] = 'Quarterly';
              
          }
          else if($form_collect['gap'] == 6){

              $form_collect['gap'] = 'Bi Annual';
          }
          else{

              $form_collect['gap'] = 'Annual';

          }


          // $form_collect['gap']  = EF::getInstallmentGapLabelValue($form_collect['gap']);      

          $booking = new Booking;

          $booking = $booking->updateInstallmentMode($form_collect); // Installment Mode Exist in Booking table
          if(isset($booking->id)){

            parent::successMessage('Installment Mode Has been Updated.');
            return back();
          }
        }
        catch (DecryptException $e) 
        {

        } 
            parent::errorMessage('Something Wrong Please Try Again.');

        return back();
    }
  public function showReserveBooking()
  {

    $condition = ['Expired','Reserved'];

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


    $booking->verifiyExpireBooking();

    $data = [
      
      'booking_list'           =>  $booking->getAllBookings($branch->getBranchId(), $condition),

    ];

    return view('booking.reserve_booking',
      [

        'branch'       => $branch->getBranchList(),
        'booking_view' => view('components.booking.table_softbooking',$data)

      ]
    );
  }
  public function storeBooking(BookingRequest $request)
  {

    try
    {
      $label_list = EF::getWhiteLabel();

      $form_collect = $request->input();


      //DECRYPTING ENCRYPTED IDS
      $form_collect['user_id']  = decrypt($form_collect['user_id']);

      $form_collect[$label_list['branch']]   = decrypt($form_collect[$label_list['branch']]);

      $form_collect[$label_list['plot']]     = decrypt($form_collect[$label_list['plot']]);

      if(isset($form_collect['reserve_booking']))
      {
          $form_collect['reserve']        = 1;

          // $form_collect['reserve_sdate']  = str_replace('01-01-1970',NULL,$form_collect[$label_list['start_date']]);
          $form_collect['reserve_edate']  = str_replace('01-01-1970',NULL,$form_collect[$label_list['end_date']]);

          $form_collect['status']         = 'Reserved';
          $form_collect['plot_status']    = 'reserve';
          $form_collect['approve_date']   =  NULL;

      }
      else
      {
         $form_collect['reserve']        = 1;

          // $form_collect['reserve_sdate']  = NULL;
          $form_collect['reserve_edate']  = NULL;
          $form_collect['plot_status']    = 'sold';

          $form_collect['status']         = 'Approve';
          $form_collect['approve_date']   =  $form_collect['booking_date'];

      }

      if(isset($form_collect['employee']))
      {
        $count = 0;

          //  COMMISSION SECTION DECRYPTION
          foreach ($form_collect['employee'] as $rows)
          {
              $form_collect['employee'][$count] = decrypt($form_collect['employee'][$count]);

              $count++;
          }
      }

      if(isset($form_collect['dealer']))
      {
          $count = 0;

        foreach ($form_collect['dealer'] as $rows)
        {

            $form_collect['dealer'][$count] = decrypt($form_collect['dealer'][$count]);

            $count++;
        }
      }



      //  END COMMISSION SECTION DECRYPTION

      $booking_obj = new Booking;

      $booking = $booking_obj->storeBooking($form_collect);


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


        parent::setLogMessage($booking->ms.' ('.$booking->plot->plot_id.' '.$booking->plot->type.') article  has been booked.');

        parent::successMessage('Booking has been created.',parent::getLogMessage());

        // return redirect(url('bookingdetail/'.Crypt::encrypt($booking->id)));
      }

      if(isset($form_collect['reserve_booking']))
      {
          return redirect('reservebooking');

      }
      elseif(isset($booking->id))
      {
          return redirect('bookingdetail/'.Crypt::encrypt($booking->id));

      }
    }
    catch (DecryptException $e)
    {

    }

    return redirect('booking');
  }

  public function viewBooking($id)
  {
     $booking_id  = decrypt($id);

     $booking     = new Booking;
     $department  = new Department;
     $branch      = new Branch;
     $plot        = new Plot;
     $user        = new User;
     $head        = new Head;
     $designation = new Designation;

     $employee_type = ['Employee'];
     $dealer_type   = ['Dealer'];

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

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

        $user_id = $booking_detail->user->id;


        $nominee = new Nominee;
        $nominee_list  = $nominee->getBookingNok($booking_id,$user_id);

        $installments = new Installment;
        $installment_list  = $installments->getBookingInstallments($booking_id);
        $installments_by_type = @count($installments->getBookingInstallmentByType($booking_id,'Installment'));

        $plan_list = EF::getPlanType();

        $all_installment = @count($installments->getInstallmentByType($booking_id,$plan_list));



        $commission = new Commission;
        $commission_list  = $commission->getBookingCommissions($booking_id);
        $document_charges_count = $commission->getBookingDocumentCharges($booking_id);

        $document         = new Document;
        $document_list    = $document->getBookingDocuments($booking_id);

        $payment         = new Payment;
        $payment_status  =  ['Approve','Unapprove','Reversal','Reject'];
                                  // O MEAN INSTALMMENT TABLE
        $installment_receipt    = $payment->getAllInstallmentPaymentList($booking_id,EF::getGenericTableIndex()['Installment'],$payment_status);
                                  // 1 MEN COMMISSION TABLE
        $sidepayment_receipt    = $payment->getAllCommissionPaymentList($booking_id,EF::getGenericTableIndex()['Commission'],$payment_status);

        $payment_list =  $installment_receipt->merge($sidepayment_receipt);


        $remaining_paid_balance     = $installments->sumPaidBalance($booking_id,'Paid');

        $remaining_plan_amount      = $installments->verificationPlan($booking_detail->id);

        $lagging_amount = $remaining_plan_amount + $remaining_paid_balance;





        $plot_detail = $booking_detail->plot;

        $plot_type   = $plot->getPlotListByColoumn('type',['branch_id' => $booking_detail->branch_id],['unsold']);

        $plot_category = $plot->getPlotListByColoumn('category',['branch_id' => $booking_detail->branch_id, 'type' => $plot_detail->type ],['unsold']);

        $plot_list = $plot->getPlots($booking_detail->branch_id);




        return view('booking.view_booking',
        [


          'unique_id'                   =>  uniqid(),
          'current_branch'              =>  $booking_detail->branch_id,
          'booking'                     =>  $booking_detail,
          'branch'                      =>  $branch->getBranchList(),
          'user'                        =>  $booking_detail->user,
          'plot'                        =>  $plot_detail,
          'nominee_list'                =>  $nominee_list,
          'commission_list'             =>  $commission_list,
          'installment_list'            =>  $installment_list,
          'document_list'               =>  $document_list,
          'head_list'                   =>  $head->getAllHeads(),
          'voucher_id'                  =>  BookingController::$id,
          'lagging_amount'              =>  $lagging_amount,
          'block'                       =>  $plot->getBlockList() ,
          'employee'                    =>  $user->getUserListByType($employee_type),
          'dealer'                      =>  $user->getUserListByType($dealer_type),
          'payment_list'                =>  $payment_list,
          'remaining_plan_amount'       =>  $remaining_plan_amount,
          'installments_by_type'        =>  $installments_by_type,
          'branch_labels'               =>  EF::branchWhiteLabel(),
          'plot_labels'                 =>  EF::plotWhiteLabel(),
          'plot_list'                   =>   $plot_list,
          'plot_category'               =>  $plot_category,
          'plot_type'                   =>  $plot_type,
          'all_installment'             =>  $all_installment,
          'document_charges_count'      =>  $document_charges_count,
          'designation_list'            => $designation->getDesignationList(),
          'department_list'             => $department->getDepartmentList(),
        ]);
     }

    parent::errorMessage('Record not found!');

    return redirect('booking');
  }


  public function viewCancelBooking($id)
  {
   $booking_id = decrypt($id);

   $booking = new Booking;
   $branch  = new Branch;
   $plot    = new Plot;
   $user    = new User;
   $head    = new Head;

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

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

    $user_id = $booking_detail->user->id;

    $commission = new Commission;
    $commission_list  = $commission->getBookingCommissions($booking_id);





    $plot_detail = $booking_detail->plot;



    return view('booking.cancel_bookingdetails',
      [

        'unique_id'                   =>  uniqid(),
        'current_branch'              =>  $booking_detail->branch_id,
        'booking'                     =>  $booking_detail,
        'branch'                      =>  $branch->getBranchList(),
        'user'                        =>  $booking_detail->user,
        'plot'                        =>  $plot_detail,
        'commission_list'             =>  $commission_list,
        'head_list'                   =>  $head->getAllHeads(),
        'voucher_id'                  =>  BookingController::$id,

      ]
    );
  }

  parent::errorMessage('Record not found!');



  return redirect('booking');



}

public function updateBooking(BookingRequest $request)
{


  try
  {
    $form_collect = $request->input();

    $label_list = EF::getWhiteLabel();

            //DECRYPTING ENCRYPTED IDS
    $form_collect[$label_list['branch']]   = decrypt($form_collect[$label_list['branch']]);

    $form_collect[$label_list['plot']]     = decrypt($form_collect[$label_list['plot']]);

    $form_collect['booking_id']     = decrypt($form_collect['booking_id']);


    $booking_obj = new Booking;

    $booking = $booking_obj->updateBooking($form_collect);

    if(isset($booking->id))
    {
        parent::setLogMessage($booking->ms.' ('.$booking->plot->plot_id.' '.$booking->plot->type.') article has been updated.');

        parent::successMessage('Booking has been update.',parent::getLogMessage());
    }
  }
  catch (DecryptException $e)
  {

  }

  return redirect()->back();

}

public function transferBooking($id)
{
 $booking_id = decrypt($id);

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

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

 if(isset($booking_detail->id))
 {
  $user_id = $booking_detail->user->id;



  return view('booking.transfer_booking',
    [

      'booking'                 =>  $booking_detail,
      'branch'                  =>  $branch->getBranchList(),
      'user'                    =>  $booking_detail->user,
      'plot'                    =>  $booking_detail->plot,




    ]
  );
}

parent::errorMessage('Record not found!');



return redirect('booking');



}

public function cancelledBooking()
{
   $condition_in = ['Cancel'];

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

   $data = [

    'cancelbooking_list'  =>  $booking->getBookingByBranch($branch->getBranchId(),$condition_in)


   ];

   return view('booking.view_cancel_booking',[
    'view_booking'  =>  view('components.booking.table_cancelbooking',$data)->render(),
    'branch'        =>  $branch->getBranchList(),
  ]
  
   );

}

public function viewBlockBooking()
{
    $column = 'is_block';
    $value = 1;

    $status = ['Approve','Cancel','Transfer','Unapprove','Reserve'];

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

    $data = [
      
      'block_booking_list'  =>  $booking->getBlockBookingByBranch($branch->getBranchId(),$status)

    ];

    return view('booking.view_block_booking',
      [

        'view_booking'  =>  view('components.booking.table_blockbooking',$data)->render(),
        'branch'        =>  $branch->getBranchList()

      ]
   );

}


public function calculateBookingReceived()
{
  $booking = new Booking;

  $allbookings = $booking->getAllBookings();

}

  public function showCancelBooking($id)
  {
    try
       {
     $booking_id = decrypt($id);

     $booking = new Booking;
     $branch  = new Branch;
     $booking_detail = $booking->getBookingById($booking_id);
     // if(isset($booking_detail->id) && $booking_detail->status == "Approve")
     if(isset($booking_detail->id) && $booking_detail->status == "Approve")
     {
      $user_id = $booking_detail->user->id;



      return view('booking.cancel_booking_request',
        [

          'booking'                 =>  $booking_detail,
          'branch'                  =>  $branch->getBranchList(),
          'user'                    =>  $booking_detail->user,
          'plot'                    =>  $booking_detail->plot,
          'balance_detail'          =>  $booking->getBalanceDetail($booking_detail->id)




        ]
      );
    }

    }
   catch(DecryptException $e)
   {

    }

    return redirect('booking');
  }
  public function showApproveCancelBooking($id)
  {
    try
       {
     $booking_id = decrypt($id);

     $booking = new Booking;
     $cancel  = new CancelBooking;
     $branch  = new Branch;

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


     // if(isset($booking_detail->id) && $booking_detail->status == "Approve")
     if(isset($booking_detail->id))
     {
      $user_id = $booking_detail->user->id;
      $cancel_details = $cancel->getCancelDetailsByBookingId($booking_detail->id);

      if(isset($cancel_details->id))
      {
        return view('booking.approve_cancel_booking',
        [

          'booking'                 =>  $booking_detail,
          'branch'                  =>  $branch->getBranchList(),
          'user'                    =>  $booking_detail->user,
          'plot'                    =>  $booking_detail->plot,
          'balance_detail'          =>  $booking->getBalanceDetail($booking_detail->id),
          'cancel_details'          =>  $cancel_details




        ]
      );
      }


      
    }

    }
   catch(DecryptException $e)
   {

    }

    return redirect('booking');
  }
public function approveBooking(Request $request)
{
  parent::errorMessage('Booking not found.');

  try
  {
    $form_collect = $request->input();

    $form_collect['id'] = decrypt($form_collect['id']);

    $booking = new Booking;

    $data = $booking->approveBooking($form_collect);
    $curr_booking     = $data['booking'];
    // $transaction      = $data['transaction'];

      // if(isset($curr_booking->id) && isset($transaction->id))
     if(isset($curr_booking->id))
      {
        //SET ERROR MESSAGE AUTO JV
          // parent::setLogMessage('Auto '.$transaction->voucher_type.' '.$transaction->voucher_number.' has been created');

          // parent::successMessage('JV has been created.',parent::getLogMessage());
         // END

          // SET ERROR MESSAGE APPROVE BOOKING
          parent::setLogMessage($curr_booking->ms.' ('.$curr_booking->plot->plot_id.'-'.$curr_booking->plot->type.') article booking has been approved.');

          parent::successMessage('Booking has been approved.',parent::getLogMessage(),1);
          // END


      }
      //Approve Date Mistake
      elseif($curr_booking == 2)
      {
          parent::errorMessage('Invalid Approve Date.');

      }
  }
  catch (DecryptException $e)
  {

  }

  return redirect()->back();
}


public function updateSoftBooking(Request $request)
{
      parent::errorMessage('Required Validation.');




  try
  {
        $form_collect = $request->input();

        $form_collect['id'] = decrypt($form_collect['id']);

        $booking = new Booking;

        $curr_booking = $booking->updateSoftBooking($form_collect);


      if(isset($curr_booking->id))
      {
          parent::setLogMessage($curr_booking->ms.'('.$curr_booking->plot->plot_id.'-'.$curr_booking->plot->type.') soft booking has been updated.');

                parent::successMessage('Soft Booking has been updated.',parent::getLogMessage());

      }
      else if($curr_booking == 1)
      {
          parent::errorMessage('Artcle has already sold / reserve.');

      }
      elseif($curr_booking == 2)
      {
          parent::errorMessage('Invalid End Date.');

      }
      else
      {
          parent::errorMessage('Something is wrong.');

      }
  }
  catch (DecryptException $e)
  {

  }

  return redirect()->back();
}




public function removeBooking($id)
{
  parent::errorMessage('Booking not found.');

  try
  {
    $id = decrypt($id);

    $booking = new Booking;


    $curr_booking = $booking->removeBooking($id);

    if(isset($curr_booking))
    {
       // SET ERROR MESSAGE APPROVE BOOKING
          parent::setLogMessage($curr_booking->ms.' ('.$curr_booking->plot->plot_id.'-'.$curr_booking->plot->type.') article booking has been deleted.');

          parent::successMessage('Booking has been deleted.',parent::getLogMessage());
          // END
    }
  }
  catch (DecryptException $e)
  {

  }

  return redirect()->back();
}
public function markTag($id,$value,$column)
{
    try
    {
       if(\Request::ajax())
       {
          $booking = new Booking;
          // $booking_id = decrypt($id);
          // $column = decrypt($column);

          $booking_id = $id;
          $column = $column;


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

         if(isset($booking_detail->id))
         {
           $curr_booking = $booking->markTag($booking_detail->id,$value,$column);

           if($column == "is_hotitem")
           {
              $data['flag'] = 0;

              if($curr_booking->is_hotitem)
              {
                 $data['img']  = url('assets/images/icons/starfilled.png');
              }
              else
              {
                $data['img']  = url('assets/images/icons/staroutline.png');
              }


              return $data;
           }
           else if($column == "is_block")
           {
              $data['flag'] = 1;

              if($curr_booking->is_block)
              {
                 $data['img']  = url('assets/images/icons/blockfilled.png');
                $data['column'] = 'is_block';
                 $data['value'] = 1;
               }
              else
              {
                $data['img']  = url('assets/images/icons/blockoutline.png');
                  $data['column'] = 'is_block';
                  $data['value'] = 0;

              }


              return $data;
           }
           else if($column == "is_resale")
           {
              $data['flag'] = 2;

              if($curr_booking->is_resale)
              {
                 $data['img']  = url('assets/images/icons/salefilled.png');
              }
              else
              {
                $data['img']  = url('assets/images/icons/saleoutline.png');
              }


              return $data;
           }
         }
       }


    }
    catch (DecryptException $e)
    {

    }

    return redirect('booking');

}



public function cancelBooking(BookingRequest $request)
{

  try
  {
      $form_collect = $request->input();

      $booking = new Booking;

      $form_collect['booking_id'] = decrypt($form_collect['booking_id']);

        $booking_detail = Booking::find( $form_collect['booking_id']);

        $received = $booking->getBalanceDetail($booking_detail->id);


        if($form_collect['deduction_amount'] > $received['debit'])
        {
           parent::errorMessage('Deduction Amount must be less than equal to booking received amount.');
           return redirect()->back();

        }

        if(isset($booking_detail->id) && $booking_detail->status != "Cancel")
        {
          $curr_booking = $booking->cancelBooking($form_collect);

            if(isset($curr_booking->id))
            {
                // SET ERROR MESSAGE APPROVE BOOKING
                parent::setLogMessage($curr_booking->ms.' ('.$curr_booking->plot->plot_id.'-'.$curr_booking->plot->type.') article booking is posted for cancel.');

                parent::successMessage('Booking has been requested to cancel.',parent::getLogMessage());
                // END

                return redirect('cancelledbooking');
            }
        }
        else
        {
           parent::errorMessage('Cancel request has in process.');
        }
      

  }

  catch (DecryptException $e)
  {

  }

  return redirect()->back();
}

public function approveCancelBooking(BookingRequest $request)
{

  try
  {
      $form_collect = $request->input();

    if(isset($form_collect['inlineapproval']))
    {
      $form_collect['approval'] = 1;
    }
    else
    {
          $form_collect['approval'] = 0;
    }
    if(isset($form_collect['inlinereceipts']))
    {
      $form_collect['receipts'] = 1;
    }
    else
    {
         $form_collect['receipts'] = 0;
    }
    if(isset($form_collect['inlineapplication']))
    {
      $form_collect['application'] = 1;
    }
    else
    {
      $form_collect['application'] = 0;
    }
    if(isset($form_collect['inlinefile']))
    {
      $form_collect['file'] = 1;
    }
    else
    {
      $form_collect['file'] = 0;
    }
    if(isset($form_collect['inlineagreement']))
    {
      $form_collect['agreement'] = 1;
    }
    else
    {
      $form_collect['agreement'] = 0;
    }

      $form_collect['booking_id'] = decrypt($form_collect['booking_id']);

      $booking = new Booking;

      $booking_detail = Booking::find( $form_collect['booking_id']);

        $received = $booking->getBalanceDetail($booking_detail->id);


        if($form_collect['deduction_amount'] > $received['debit'])
        {
           parent::errorMessage('Deduction Amount must be less than equal to booking received amount.');
           return redirect()->back();

        }
        $cancel = new CancelBooking;
        $cancel_details = $cancel->getCancelDetailsByBookingId($booking_detail->id);
        if(isset($cancel_details->id))
        {
            $curr_booking = $booking->approveCancelBooking($form_collect);

            if(isset($curr_booking->id))
            {
                // SET ERROR MESSAGE APPROVE BOOKING
                parent::setLogMessage($curr_booking->ms.' ('.$curr_booking->plot->plot_id.'-'.$curr_booking->plot->type.') article booking cancel request has been approved.');

                parent::successMessage('Booking Cancel Request has been approved.',parent::getLogMessage());
                // END

                return redirect('cancelledbooking');
            }
        }
        else{
          parent::errorMessage('Cancel booking not found.');
        }

      

  }

  catch (DecryptException $e)
  {

  }

  return redirect('cancelledbooking');
}

public function getBranchBookingDropDown($id)
{
        if(\Request::ajax())
        {
            $data['booking_view'] = '<option value="'.Crypt::encrypt(0).'">Select Booking</option>';

            try
            {
                $id = decrypt($id);

                $booking = new Booking;

                $booking_list = $booking->getBookingByBranch([$id],['Approve','Cancel']);

                foreach($booking_list as $rows)
                {
                   $data['booking_view'] .= '<option value="'.Crypt::encrypt($rows->id).'">'.$rows->ms.' (' .EF::showPlotFormat($rows->plot).')</option>';
                }


            }
            catch (DecryptException $e)
            {

            }



           return $data;

        }


        return redirect()->back();
}

  public function showdocuments($id)
  {
      if(\Request::ajax())
      {
          $data = '';

          try
          {
              $id               = decrypt($id);
              $count            = 0;

              $booking          = new Booking;
              $installment      = new Installment;

              $document_booking = $booking->getBookingById($id);

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



                 $down_payment = $installment->getBookingInstallmentByType($document_booking->id,'Down Payment');


                if(isset($down_payment[0]) && $down_payment[0]->status === 'Paid')
                {
                  $down_payment = 1;
                }
                else
                {
                  $down_payment = 0;
                }

                $data = view('booking.modals.documentmodal',[
                  'document_booking' => $document_booking,
                  'down_payment' => $down_payment,

                ]);
              }





          }
          catch (DecryptException $e)
          {

          }

          return $data;
      }

      return redirect()->back();
  }





}
