<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Commission;
use App\DB;

class CancelBooking extends Model
{
	private $generic_condition;


  

    public function __construct()
    {
           
       $this->setCondition(['is_recycle' => '0']);

     
    }

    public function setCondition($condition = [])
    {
        $this->generic_condition = $condition;
    }

    public function getAllCancelBookings()
    {
        return CancelBooking::where($this->getCondition())->orderBy('id','desc')->with(['booking'])->get();
    }

    public function getAllCancelBookingByBranch($branch_id)
    {
        return CancelBooking::where($this->getCondition())->orderBy('id','desc')->whereHas('booking',function($query) use ($branch_id){

            $query->where('branch_id',$branch_id);

        })->with(['booking'])->get();
    }

    public function getCondition()
    {
        return $this->generic_condition;
    }


    public function isVerifyCancelBooking($cancel_booking_id)
    {
        $data = ['status' => false, 'message' => 'Request has failed.', 'data' => []];

        $cancel_booking = $this->getCancelBookingById($cancel_booking_id);

        if(isset($cancel_booking->id))
        {
            $booking = $cancel_booking->booking;

            if(isset($booking->id))
            {
                $plot = $booking->plot;

                if(($cancel_booking->status == "Pending" && $plot->status == "sold") || ($cancel_booking->status == "Approve" && $plot->status == "unsold"))
                {
                    $side_payment_list = Commission::where(['booking_id' => $booking->id,'is_recycle' => '0'])->whereIn('payment_type',['Refund','Deduction'])->get();
                    if(!in_array('Paid',$side_payment_list->pluck('status')->toArray()))
                    {
                        $data['side_payments'] = $side_payment_list;
                        $data['booking']       = $booking;
                        $data['plot']          = $plot;

                        $data['status'] = true;
                    }
                    else
                    {
                        $data['message'] = 'Remove cancel request has failed due to refund / deduction amount has paid.';
                    }
                }
                else
                {
                    $data['message'] = 'Plot has not available';
                }
            }
            else
            {
                $data['message'] = 'Booking not found.';
            }
        }
        else
        {
            $data['message'] = 'Cancel booking not found.';

        }
        return $data;
    }


    public function removeCancelBooking($id)
    {
        $cancel_booking = $this->getCancelBookingById($id);

        if(isset($cancel_booking->id))
        {
            $verify = $this->isVerifyCancelBooking($cancel_booking->id);

            if($verify['status'] === true)
            {

                $cancel_booking->is_recycle = '1';

                $cancel_booking->update();

                $booking        = $verify['booking'];
                $plot           = $verify['plot'];
                $side_payments  = $verify['side_payments'];

                $booking->status = 'Approve';

                $booking->update();

                $plot->status = 'sold';

                $plot->update();

                foreach ($side_payments as $rows) {
                    
                    $rows->is_recycle = '1';

                    $rows->update();
                }
            }
        }

        return with($cancel_booking);
    }

    public function getCancelBookingById($id)
    {
        return CancelBooking::where(['id' => $id, 'is_recycle' => '0'])->first();
    }

   public function storeCancelBooking($object)
   {
   	 return \DB::transaction(function () use ($object)  {

            $cancelbooking = new CancelBooking;

    
            $cancelbooking->ms                 = $this->generateMsNumber();

            $cancelbooking->booking_id         = $object['booking_id'];
 
            $cancelbooking->deduction_amount   = $object['deduction_amount'];
            
            $cancelbooking->refund_amount      = $object['refund_amount'];


            $cancelbooking->created_at         =  date('Y-m-d',strtotime($object['cancel_date']));


           $cancelbooking->save();

           return with($cancelbooking);


        });

   }
   public function updateCancelBooking($object)
   {
     return \DB::transaction(function () use ($object)  {

             $cancelbooking = $this->getCancelDetailsByBookingId($object['booking_id']);

        if(isset($cancelbooking->id))
       {
         
 
            $cancelbooking->deduction_amount              = $object['deduction_amount'];

            $cancelbooking->ceo_approval                  = $object['approval'];
            $cancelbooking->original_receipts              = $object['receipts'];
            $cancelbooking->original_app_receipts          = $object['application'];
            $cancelbooking->original_agreement_receipts    = $object['agreement'];
            $cancelbooking->original_file_receipts         = $object['file'];
            $cancelbooking->missing_documents             = $object['missing_documents'];            
            $cancelbooking->refund_amount                 = $object['refund_amount'];

            $cancelbooking->created_at         =  date('Y-m-d',strtotime($object['cancel_date']));


           $cancelbooking->update();

              return with($cancelbooking);
        }
          

        


        });

   }
    public function updateStatus($id,$status)
    {
        return \DB::transaction(function () use ($id,$status) {
            
            $condition = $this->getCondition();
            $condition += ['booking_id' => $id];
            $cancelbooking = CancelBooking::where($condition)->first();




            if(isset($cancelbooking->id))
            {
            
                $cancelbooking->status  = $status;
               
                $cancelbooking->update();

            }
            
            return with($cancelbooking);
        });
    }

     public function removeBulkCancelBooking($booking_id)
    {
        return CancelBooking::where('booking_id',$booking_id)->update(['is_recycle' => 1]);

    }
   public function getCancelDetailsByBookingId($id)
   {
        $condition = $this->getCondition();
        $condition  += ['booking_id' => $id];
        return CancelBooking::where($condition)->first();
       
   }
   //GENERATE MS NUMBER
    public function generateMsNumber()
    {
        $insert_id = booking::max('id');
        $serial = 'SL-CANCEL/'.str_pad(($insert_id+1), 4, '0', STR_PAD_LEFT); 
        return $serial;
    }
    
     public function booking()
    {
        return $this->belongsTo(Booking::class,'booking_id')->withDefault();
    }
}
