<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Customer;
use App\CustomerProperty;
use App\CustomerStatement;
use App\UnitSize;
use App\UnitType;
use App\InstallmentPlan;
use App\Receipt;
use App\Dealer;
use App\UnitCategory;
use App\UnitFloor;
use App\DepositorBank;
use Illuminate\Support\Facades\Auth;
use DB;
use App\Country;
use App\CompanyBank;
use App\Inventory;
use App\DealerType;
use App\SchedulePlan;
use App\UnitFloorSize;
use PDF;
use App\DealerTransaction;
use App\ChartOfAccount;
use App\DealerPaidRebate;
use App\Receiptdocument;
use File;
use App\DNFBP;
use App\UnitBlock;
use App\TaxReceipt;
use App\CustomerPropertyTax;
use App\PurchaseRequest;
use App\PurchaseOrderReceipt;
use App\PaymentHeadPriority;
use App\TokenReceipt;
use App\SurchargeReceipt;
use App\MergingProperty;
use Carbon\Carbon;
use App\CancelProperty;
use App\ProjectType;
use App\OpenFileDealerInfo;
use App\DealerPackage;
use App\DealerPackageReceipt;
use App\DevelopmentCharges;
use App\EmailLog;
use App\EmailSmsType;
use App\EmailSms;
use App\Mail\AddTokenReceiptMail;
use App\MultiProject;
use App\SmtpSetting;
class CustomerStatementController extends Controller
{

    protected $property;
    protected $receipt;
    protected $tokenreceipt;
    protected $statement;
    protected $surcharge_receipt;

    protected $dealer_package_receipt;

    public function __construct()
    {
        $this->property = new CustomerProperty();
        $this->receipt = new Receipt();
        $this->tokenreceipt = new TokenReceipt();
        $this->statement = new CustomerStatement();
        $this->surcharge_receipt = new SurchargeReceipt();
        $this->dealer_package_receipt = new DealerPackageReceipt();

    }
public  function getCookieInfomationold(){
    $data = array();
    try{
    $project_id = request()->cookie('current_project_id');
    $user = Auth::user();
    if (!empty($project_id)) {
        $p_id = decrypt($project_id);
        $multi = MultiProject::where('id', $p_id)->first();
        $multiProjectId = $multi->id;
        if ($multi->name == "Super Admin") {
            $roles = $user
                ->roles()
                ->where('name', 'like', 'admin')
                ->whereHas('projects', function ($query) use ($multiProjectId) {
                    $query->where('multi_project_id', $multiProjectId);
                })
                ->first();
            if (!empty($roles)) {
                $data['multi_projects']  = MultiProject::where('name', 'NOT like', 'Super Admin')->get()->pluck('id')->toArray() // Flatten the collection of IDs into a single array
                ;
                $data['status'] = 'success';
                return   $data;
            } else {
                
                $request = app(Request::class);
               
 $permission=decrypt($request->permission);
 
 $project_ids=       $user->roles()
->whereHas('projects', function ($query)   {
$query->where('name', 'NOT like', 'Super Admin');
})
->get()
->filter(function ($r) use ($permission) {
return $r->hasPermission($permission);
})
->pluck('projects.*.id') // Pluck the 'id' column from the remaining 'projects' models
->flatten() // Flatten the collection of IDs into a single array
->unique()
->toArray()
;

if(sizeof($project_ids) == 0)
{
    $data['status'] = 'error';
    return  $data; 
}
                $data['multi_projects'] = MultiProject::whereIn('id',  $project_ids)->where('name', 'NOT like', 'Super Admin')->get()->pluck('id')
                ->toArray();
                $data['status'] = 'success';
                 return   $data;
            }
        }
        else{
            $roles = $user
                ->roles()
                
                ->whereHas('projects', function ($query) use ($multiProjectId) {
                    $query->where('multi_project_id', $multiProjectId);
                })
                ->first(); 

                if (!empty($roles)) {
                    $data['multi_projects']  = $multi->id;
                    $data['status'] = 'success';
                    return   $data;
                    

                }
        }
    }
    else
    {
        $data['status'] = 'error';
        return  $data; 
    }
}
catch(\Exception $e){
    $data['status'] = 'error';
    return  $data;

}
}
public function getCookieInfomation(){
    $data =  array();
    $request = app(Request::class);
    try{
       
                if($request->has('multipro_id')){
            
            if($request->multipro_id == 'all'){
                $data['multipro_id'] =$request->multipro_id;
            }else if(!empty($request->multipro_id)){
            $data['multipro_id'] =  decrypt($request->multipro_id);
            }
        }
        
        
        $project_id = request()->cookie('current_project_id');
       
        $user = Auth::user();
        $data['multi_projects'] = [];
        if (!empty($project_id)) {
            $p_id = decrypt($project_id);
            $multi = MultiProject::where('id', $p_id)->first();
            $multiProjectId = $multi->id;
            if ($multi->name == "Super Admin") {
                $roles = $user
                    ->roles()
                    ->where('name', 'like', 'admin')
                    ->whereHas('projects', function ($query) use ($multiProjectId) {
                        $query->where('multi_project_id', $multiProjectId);
                    })
                    ->first();
                if (!empty($roles)) {
                    $data['multi_projects']  = MultiProject::where('name', 'NOT like', 'Super Admin')->get();
                    $data['project'] = $multi->name;
                    $data['role'] = 'admin';
                    $data['project_ids'] =  'all';
                    if(isset( $data['multipro_id'])){
                        $data['project_ids'] = $data['multipro_id'];
                        
                    }
                    $data['status'] = 'success';
                    return  $data;
                    

                } else {
                    // $request = app(Request::class);
           
                $permission=decrypt($request->permission);
                
                $project_ids=       $user->roles()
               ->whereHas('projects', function ($query)   {
               $query->where('name', 'NOT like', 'Super Admin');
               })
               ->get()
               ->filter(function ($r) use ($permission) {
               return $r->hasPermission($permission);
               })
               ->pluck('projects.*.id') // Pluck the 'id' column from the remaining 'projects' models
               ->flatten() // Flatten the collection of IDs into a single array
               ->unique()
               ->toArray()
               ;
               
               if(sizeof($project_ids) == 0)
               {
                   $data['status'] = 'error';
                   return  $data; 
               }
                     
               $data['multi_projects'] = MultiProject::whereIn('id',  $project_ids)->where('name', 'NOT like', 'Super Admin')->get();
                    $data['project'] = $multi->name;
                    $data['role'] = 'other';
                    $data['project_ids'] =  $project_ids;
                    if(isset( $data['multipro_id'])){
                        if($data['multipro_id'] != 'all'){
                        $data['project_ids'] = $data['multipro_id'];
                        }
                     
                    }
                   
                    $data['status'] = 'success';
                    return $data;
                }
            }
            else{
                $roles = $user
                    ->roles()
                    
                    ->whereHas('projects', function ($query) use ($multiProjectId) {
                        $query->where('multi_project_id', $multiProjectId);
                    })
                    ->first(); 
                
                    if (!empty($roles)) {
                        $data['multi_projects']  = [];
                        $data['project'] = $multi->name;
                        $data['role'] = 'other';
                        $data['project_ids'] =  $multi->id ;
                        if(isset( $data['multipro_id'])){
                            if($data['multipro_id'] != 'all'){
                                $data['project_ids'] = $data['multipro_id'];
                                }
                        }
                        $data['status'] = 'success';
                        return  $data;
                        
    
                    }
            }
        }
        else
        {
            $data['status'] = 'error';
            return  $data; 
        }
    }
    catch(\Exception $e){
        $data['status'] = 'error';
        return  $data;

    }
}
    public function getAllStatements(Request $request)
    {


        $data = array();
       
        $project_ids=   $this->getCookieInfomation();
        
        if($project_ids['status'] == 'error'){
            return redirect()

            ->back()
            ->with([
                'message' => 'Invalid Inputs!',
                'alert-type' => 'error',
            ]);
        }
        $ids=[];
        if(is_array($project_ids['project_ids'])){
            $ids= $project_ids['project_ids']; 
        }
        else
        $ids[]= $project_ids['project_ids'];
        
        

         
        $data['allStatements'] = CustomerProperty::with('inventory', 'customer', 'dealer')
        ->whereIn('multi_project_id', $ids)
        ->orderBy('created_at', 'desc')->where([['is_deleted', false]])->paginate(25);

        $receivedAmt = array();
        foreach ($data['allStatements'] as $statement) {
            $receivedAmt[$statement->id] =  Receipt::where('customer_property_id', $statement->id)->where('is_approved', 1)->where('is_deleted', false)->sum('amount');
        }

        $data['receivedAmt'] = $receivedAmt;

        $data['unitNumbers'] = Inventory::where([['is_deleted', false], 
        ['status', '!=', Inventory::open]])
        ->whereIn('multi_project_id', $ids)
        ->select('id', 'unit_number')->orderBy('unit_number', 'asc')->get();
        $data['customers'] = Customer::where([['is_deleted', false]])->select('id', 'name')->orderBy('name', 'asc')->get();
        $data['unitSize'] = UnitSize::where([['is_deleted', false], ['status', true]])->select('id', 'name')->orderBy('name', 'asc')->get();

        $data['unitType'] = UnitType::where([['is_deleted', false], ['status', true]])->select('id', 'name')->orderBy('name', 'asc')->get();

        $data['unitBlock'] = UnitBlock::where([['is_deleted', false]])->select('id', 'name')->orderBy('name', 'asc')->get();

        $data['dealers'] = Dealer::where([['is_deleted', false]])->select('id', 'name', 'code')->orderBy('name', 'asc')->get();

        $data['statementCount'] = Customerproperty::where([['is_deleted', false]])
        ->whereIn('multi_project_id', $ids)->count();
    
        $data['multi_projects'] = $project_ids['multi_projects'];
        
        activity('View')->log('Property list.');

        
        if(isset($project_ids['multipro_id'])){
           
            return view('statement.index-update', $data);
        }
        else{
           
            return view('statement.index', $data);
        }
      
      
    }

    public function getAllCancelStatements()
    {

        $project_ids=   $this->getCookieInfomation();
        if($project_ids['status'] == 'error'){
            return redirect()

            ->back()
            ->with([
                'message' => 'Invalid Inputs!',
                'alert-type' => 'error',
            ]);
        }
       
        $ids=[];
        if(is_array($project_ids['project_ids'])){
            $ids= $project_ids['project_ids']; 
        }
        else
        $ids[]= $project_ids['project_ids'];

        $data = array();

        $data['allStatements'] = CustomerProperty::has('cancelProperty')->with('inventory', 'customer', 'dealer', 'cancelProperty')
        ->whereIn('multi_project_id', $ids)
        ->orderBy('created_at', 'desc')->paginate(25);
        // $data['allStatements'] = CustomerProperty::has('cancelProperty')->with('inventory','customer','dealer')->orderBy('created_at', 'desc')->where([['is_deleted',false],['status',CustomerProperty::cancel]])->paginate(25);

        
        //   dd( $data['allStatements']);
        $receivedAmt = array();
        foreach ($data['allStatements'] as $statement) {
            $receivedAmt[$statement->id] = CustomerStatement::where([['customer_property_id', $statement->id], ['is_deleted', false]])->sum('received');
        }
        $data['receivedAmt'] = $receivedAmt;

        $data['statementCount'] = Customerproperty::where([['is_deleted', false], ['status', CustomerProperty::cancel]])
        ->whereIn('multi_project_id', $ids)
        ->count();


        $data['allopenfile']=    OpenFileDealerInfo::has('cancelOpenFile')
        ->whereHas('inventory', function ($query) use($ids){
            $query->whereIn('multi_project_id', $ids);
        })
    
        ->with('inventory', 'dealerPackage', 'dealer', 'cancelOpenFile')->paginate(25);

        // dd($data['allopenfile']);
       


        activity('View')->log('Cancel Statements list.');


        return view('statement.cancel.index', $data);

        
    }

    public function getCancelStatementForm()
    {

        $project_ids=   $this->getCookieInfomation();
        if($project_ids['status'] == 'error'){
            return redirect()

            ->back()
            ->with([
                'message' => 'Invalid Inputs!',
                'alert-type' => 'error',
            ]);
        }
       
        $ids=[];
        if(is_array($project_ids['project_ids'])){
            $ids= $project_ids['project_ids']; 
        }
        else
        $ids[]= $project_ids['project_ids'];

        $data['allStatements'] = CustomerProperty::doesnthave('cancelProperty')->with('inventory', 'customer', 'dealer')
            ->orderBy('created_at', 'desc')->where([['is_deleted', false], ['status', '!=', CustomerProperty::cancel]])
            ->whereIn('multi_project_id', $ids)
            ->get();



        $data['OpenFileDealerInfo'] = OpenFileDealerInfo::whereHas('inventory', function ($query) use($ids) {
            $query->whereIn('multi_project_id', $ids);
        })->get();
        // dd($data['OpenFileDealerInfo'] );

        return view('statement.cancel.create', $data);
      
    }


    public function editCancelStatementForm($id)
    {

        $data['allStatements'] = CustomerProperty::with('inventory', 'customer', 'dealer', 'cancelProperty')
            ->orderBy('created_at', 'desc')->where([['is_deleted', false], ['id', '=', $id]])->first();
        $data['received_amount'] =   CustomerStatement::where([['customer_property_id', $data['allStatements']->id], ['is_deleted', false]])->sum('received');

        return view('statement.cancel.edit', $data);
    }

    public function updateCancelStatementForm(Request $request)
    {
        $customer_property =  CancelProperty::where('customer_property_id', $request->property_no)->first();

        $customer_property->status = $request->property_status;
        $customer_property->fee = $request->fee;

        $customer_property->after_cancellation_status = $request->after_cancellation_status;
        $customer_property->save();
        if ($customer_property->status == 1) {
            CustomerProperty::where('id', $customer_property->customer_property_id)->update(['status' => Customerproperty::cancel, 'cancel_date'  => date('Y-m-d')]);
            $property = CustomerProperty::find($customer_property->customer_property_id);
            Inventory::where('id', $property->inventory_id)->update(['status' => Inventory::hold_company]);
        } else {
            CustomerProperty::where('id', $customer_property->customer_property_id)->update(['status' => Customerproperty::approved,  'cancel_date'  => null]);
            $property = CustomerProperty::find($customer_property->customer_property_id);
            Inventory::where('id', $property->inventory_id)->update(['status' => Inventory::sold]);
        }



        activity('Update Cancel Property Request')->log($customer_property->customer_property_id . ' Property regestered for Cancel.');
        return redirect()
            ->route('statement.cancel')
            ->with([
                'message' => 'Request update successfully!',
                'alert-type' => 'info'
            ]);
    }


    public function cancelNewStatement(Request $request)
    {


        $validator = Validator::make($request->all(), [
            'property_no' => 'required',
            'status' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect('/cancel-statements/new')
                ->withErrors($validator)
                ->withInput()
                ->with([
                    'message' => 'Invalid Inputs!',
                    'alert-type' => 'error',
                ]);
        }
        // dd( $request->all());


        foreach ($request->property_no as $property) {
            CancelProperty::create(['customer_property_id' => $property, 'fee' => $request->fee]);
        }

       

        $pro = implode(" ", $request->property_no);
        activity('Cancel Property Request')->log($pro . ' Property regestered for Cancel.');
        return redirect()
            ->route('statement.cancel')
            ->with([
                'message' => 'Request cancel added successfully!',
                'alert-type' => 'info'
            ]);
    }

    public function deleteCancelStatementForm(Request $request, $id)
    {


        $customer_property =  CancelProperty::where('customer_property_id', $id)->delete();

        return redirect()
            ->back()
            ->with([
                'message' => 'Request deleted successfully!',
                'alert-type' => 'info'
            ]);
    }



    public function reopenCancelStatement(Request $request)
    {

        // return true;
        // dd($request->all());

        $validator = Validator::make($request->all(), [
            'id' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect('/reopen-cancel-statement')
                ->withErrors($validator)
                ->withInput()
                ->with([
                    'message' => 'Invalid Inputs!',
                    'alert-type' => 'error',
                ]);
        }



        CustomerProperty::where('id', $request->id)->update(['status' => Customerproperty::approved,  'cancel_date'  => null]);

        $customer_property =  CancelProperty::where('customer_property_id', $request->id)->first();

        $customer_property->status = 0;

        $customer_property->save();
        $property = CustomerProperty::find($request->id);

        Inventory::where('id', $property->inventory_id)->update(['status' => Inventory::sold]);

        activity('Update')->log($property->inventory->unit_number . ' Property Cancel.');

        return true;
        return redirect()
            ->route('statement.cancel')
            ->with([
                'message' => 'Statement Reopen  successfully!',
                'alert-type' => 'info'
            ]);
    }



    public function viewBlockProperty()
    {
        $data = array();

        
  $project_ids=   $this->getCookieInfomation();
  if($project_ids['status'] == 'error'){
    return redirect()

    ->back()
    ->with([
        'message' => 'Invalid Inputs!',
        'alert-type' => 'error',
    ]);
}
       
  $ids=[];
  if(is_array($project_ids['project_ids'])){
      $ids= $project_ids['project_ids']; 
  }
  else
  $ids[]= $project_ids['project_ids'];

        $data['allStatements'] = CustomerProperty::with('inventory', 'customer', 'dealer', 'cancelProperty')->where('status', Customerproperty::block)
        ->whereIn('multi_project_id', $ids)
        ->orderBy('created_at', 'desc')->paginate(25);
        // $data['allStatements'] = CustomerProperty::has('cancelProperty')->with('inventory','customer','dealer')->orderBy('created_at', 'desc')->where([['is_deleted',false],['status',CustomerProperty::cancel]])->paginate(25);


        //   dd( $data['allStatements']);
        $receivedAmt = array();
        foreach ($data['allStatements'] as $statement) {
            $receivedAmt[$statement->id] = CustomerStatement::where([['customer_property_id', $statement->id], ['is_deleted', false]])->sum('received');
        }
        $data['receivedAmt'] = $receivedAmt;

        $data['statementCount'] = Customerproperty::where([['is_deleted', false],
         ['status', CustomerProperty::block]])
         ->whereIn('multi_project_id', $ids)
         ->count();

        activity('View')->log('Block Statements list.');




        return view('statement.block.index', $data);
    }
    public function createBlockProperty()
    {
        $project_ids=   $this->getCookieInfomation();
        if($project_ids['status'] == 'error'){
            return redirect()

            ->back()
            ->with([
                'message' => 'Invalid Inputs!',
                'alert-type' => 'error',
            ]);
        }
        $ids=[];
        if(is_array($project_ids['project_ids'])){
            $ids= $project_ids['project_ids']; 
        }
        else
        $ids[]= $project_ids['project_ids'];

        $data['allStatements'] = CustomerProperty::doesnthave('cancelProperty')
        ->with('inventory', 'customer', 'dealer')

            ->orderBy('created_at', 'desc')
            ->whereIn('multi_project_id', $ids)
            ->where([['is_deleted', false], ['status', '!=', CustomerProperty::cancel], ['status', '!=', CustomerProperty::block]])->get();



        return view('statement.block.create', $data);
    }
    public function storeBlockProperty(Request $request)
    {
        // dd($request->all());
        $this->validate($request, [
            'property_no' => 'required',

        ]);
        foreach ($request->property_no as $pro) {
            CustomerProperty::where('id', $pro)->update(['status' => Customerproperty::block, 'block_date' => date('Y-m-d')]);
            $property = CustomerProperty::find($pro);
            Inventory::where('id', $property->inventory_id)->update(['status' => Inventory::block]);
        }
        return redirect()
            ->route('property.block.view')
            ->with([
                'message' => 'Block Added successfully!',
                'alert-type' => 'success'
            ]);
    }
    public function editBlockProperty($id)
    {
    }
    public function updateBlockProperty(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect('/reopen-cancel-statement')
                ->withErrors($validator)
                ->withInput()
                ->with([
                    'message' => 'Invalid Inputs!',
                    'alert-type' => 'error',
                ]);
        }



        CustomerProperty::where('id', $request->id)->update(['status' => Customerproperty::approved,  'block_date'  => null]);


        $property = CustomerProperty::find($request->id);

        Inventory::where('id', $property->inventory_id)->update(['status' => Inventory::sold]);

        activity('Update')->log($property->inventory->unit_number . ' Property Reopen.');

        return true;
        return redirect()
            ->route('property.block.view')
            ->with([
                'message' => 'Property Reopen  successfully!',
                'alert-type' => 'info'
            ]);
    }
    public function deleteBlockProperty($id)
    {
    }




    public function getPendingStatements()
    {

        $project_ids=   $this->getCookieInfomation();
        if($project_ids['status'] == 'error'){
            return redirect()

            ->back()
            ->with([
                'message' => 'Invalid Inputs!',
                'alert-type' => 'error',
            ]);
        }
        $ids=[];
        if(is_array($project_ids['project_ids'])){
            $ids= $project_ids['project_ids']; 
        }
        else
        $ids[]= $project_ids['project_ids'];

        $data['allStatements'] = CustomerProperty::where([['status', CustomerProperty::pending]])
        ->whereIn('multi_project_id', $ids)
        ->with('inventory', 'customer', 'dealer')->orderBy('created_at', 'desc')->get();

        $receivedAmt = array();
        foreach ($data['allStatements'] as $statement) {
            $data['receivedAmt'][$statement->id] = CustomerStatement::where('customer_property_id', $statement->id)->sum('received');
        }

        $data['unitNumbers'] = Inventory::where([['is_deleted', false], ['status', '!=', Inventory::open]])
        ->whereIn('multi_project_id', $ids)
        ->select('id', 'unit_number')->orderBy('unit_number', 'asc')->get();
        $data['customers'] = Customer::where([['is_deleted', false]])->select('id', 'name')->orderBy('name', 'asc')->get();
        $data['dealers'] = Dealer::where([['is_deleted', false]])->select('id', 'name', 'code')->orderBy('name', 'asc')->get();

        $data['statementCount'] = Customerproperty::where([['status', CustomerProperty::pending]])
        ->whereIn('multi_project_id', $ids)
        ->count();
        $data['multi_projects'] = MultiProject::all();

        return view('statement.pending-statement', $data);
    }


    public function getUnitDetail(Request $request)
    {
        $unitNumbers = Inventory::where([['is_deleted', false], ['id', $request->unitId]])->with('floor', 'property')->orderBy('unit_number', 'asc')->first();

        if ($unitNumbers == true)
            echo json_encode(array('output' => $unitNumbers));
        else
            echo json_encode(array('output' => ''));
    }

 public function getCookieInfoAndMultiPro($request){
        $data =  array();
        try{
           
          
            if($request->has('multipro_id')){
                
                if($request->multipro_id == 'all'){
                    $data['multipro_id'] =$request->multipro_id;
                }else if(!empty($request->multipro_id)){
                $data['multipro_id'] =  decrypt($request->multipro_id);
                }
            }
            
            
            $project_id = request()->cookie('current_project_id');
            
            $user = Auth::user();
            $data['multi_projects'] = [];
            if (!empty($project_id)) {
                $p_id = decrypt($project_id);
                $multi = MultiProject::where('id', $p_id)->first();
                $multiProjectId = $multi->id;
                if ($multi->name == "Super Admin") {
                    $roles = $user
                        ->roles()
                        ->where('name', 'like', 'admin')
                        ->whereHas('projects', function ($query) use ($multiProjectId) {
                            $query->where('multi_project_id', $multiProjectId);
                        })
                        ->first();
                    if (!empty($roles)) {
                        $data['multi_projects']  = MultiProject::where('name', 'NOT like', 'Super Admin')->get();
                        $data['project'] = $multi->name;
                        $data['role'] = 'admin';
                        $data['project_ids'] =  'all';
                        if(isset( $data['multipro_id'])){
                            $data['project_ids'] = $data['multipro_id'];
                            
                        }
                        $data['status'] = 'success';
                        return  $data;
                        
    
                    } else {
                        
 $permission=decrypt($request->permission);
 $project_ids=       $user->roles()
->whereHas('projects', function ($query)   {
$query->where('name', 'NOT like', 'Super Admin');
})
->get()
->filter(function ($r) use ($permission) {
return $r->hasPermission($permission);
})
->pluck('projects.*.id')  
->flatten() 
->unique()
->toArray()
;



                        // $project_ids = $user->roles()
                        // ->with(
                        
                        // [
                        //     'projects' => function($query) {
                        //         // add conditions to the roles query here
                        //         $query->where('name', 'NOT like', 'Super Admin');
                        //     },
                            
                        // ])
                        //  // Eager load the related 'projects' models
                        // ->get()
                        // ->pluck('projects.*.id') // Pluck the 'id' column from the related 'projects' models
                        // ->flatten() // Flatten the collection of IDs into a single array
                        // ->unique() // Filter out duplicates
                        // ->toArray(); // Reset the array keys// Reset the array keys
                      if(sizeof($project_ids) == 0)
                      {
                        $data['status'] = 'error';
                        return $data;
                      }
                        
                        $data['multi_projects'] = MultiProject::whereIn('id',  $project_ids)->where('name', 'NOT like', 'Super Admin')->get();
                        $data['project'] = $multi->name;
                        $data['role'] = 'other';
                        $data['project_ids'] =  $project_ids;
                        if(isset( $data['multipro_id'])){
                            if($data['multipro_id'] != 'all'){
                            $data['project_ids'] = $data['multipro_id'];
                            }
                         
                        }
                        $data['status'] = 'success';
                        return $data;
                    }
                }
                else{
                    $roles = $user
                        ->roles()
                        
                        ->whereHas('projects', function ($query) use ($multiProjectId) {
                            $query->where('multi_project_id', $multiProjectId);
                        })
                        ->first(); 
                    
                        if (!empty($roles)) {
                            $data['multi_projects']  = [];
                            $data['project'] = $multi->name;
                            $data['role'] = 'other';
                            $data['project_ids'] =  $multi->id ;
                            if(isset( $data['multipro_id'])){
                                if($data['multipro_id'] != 'all'){
                                    $data['project_ids'] = $data['multipro_id'];
                                    }
                            }
                            $data['status'] = 'success';
                            return  $data;
                            
        
                        }
                }
            }
            else
            {
                $data['status'] = 'error';
                return  $data; 
            }
        }
        catch(\Exception $e){
            $data['status'] = 'error';
            return  $data;
    
        }
    }
    //add new statement
    public function addStatementForm(Request $request)
    {
 
        $floors = UnitFloor::orderby('name', 'asc')->get();
        $blocks = UnitBlock::orderby('name', 'asc')->get();

        $categories = UnitCategory::where([['is_deleted',false]])->orderBy('name','asc')->get();
        //   $unitNumbers_of_dealer_package_file = Inventory::whereHas('dealerPackageOpenFileUnit')->where([['status', '!=', Inventory::sold],['status', '!=', Inventory::hold_company],['status','!=',Inventory::package_open_file_refunded], ['is_deleted', false]])->orderby('unit_number', 'asc')->select('id', 'unit_number AS name')->get();

       
        $data =
        $this->getCookieInfoAndMultiPro($request);
        
        if($data['status'] == 'error'){
            return redirect()
    
            ->back()
            ->with([
                'message' => 'Invalid Inputs!',
                'alert-type' => 'error',
            ]);
        }
        $ids=[];
        if(is_array($data['multi_projects'])){
            $ids= $data['multi_projects']; 
        }
        else
        $ids[]= $data['multi_projects'];

         
        $unitNumbers_of_dealer_package_file = Inventory::join('open_file_dealer_infos', 'inventories.id', '=', 'open_file_dealer_infos.invertory_id')
            ->join('open_file_dealer_end_user_infos', 'open_file_dealer_infos.id', '=', 'open_file_dealer_end_user_infos.openfile_dealer_info_id')
            ->where([['inventories.status', '!=', Inventory::sold],['inventories.status', '!=', Inventory::hold_company],['inventories.status','!=',Inventory::package_open_file_refunded], ['is_deleted', false]])->whereIn('multi_project_id', $ids)->orderby('unit_number', 'asc')->select('inventories.id', 'inventories.unit_number AS name','open_file_dealer_end_user_infos.currency_number AS currency_number','multi_project_id')->get();
        $unitNumbers = Inventory::doesntHave('dealerPackageOpenFileUnit')->where([['status', '!=', Inventory::sold],['status', '!=', Inventory::token_hold], ['is_deleted', false]])->whereIn('multi_project_id', $ids)->orderby('unit_number', 'asc')->select('id', 'unit_number AS name','multi_project_id')->get();

        $unitNumbersTokenHolds = Inventory::where([['status', '=', Inventory::token_hold], ['is_deleted', false]])->whereIn('multi_project_id', $ids)->orderby('unit_number', 'asc')->select('id', 'unit_number AS name','multi_project_id')->get();




        $customers = Customer::where([['status', true], ['is_deleted', false]])->orderby('name', 'asc')->get();

        $dealers = Dealer::where([['status', true], ['is_deleted', false]])->with('dealerType')->orderby('name', 'asc')->select('dealer_type_id', 'id', 'name', 'percentage')->get()->groupBy('dealer_type_id');
        $dealerTypes = DealerType::pluck('name', 'id');
        $banks = DepositorBank::all();
        $cBanks = CompanyBank::all();
        $accounts = ChartOfAccount::orderBy('number', 'ASC')->get();

        $result = Receipt::where([['receipt_no', '!=', null]])->orderby('id', 'desc')->first();

        if ($result)
            $receipt_no = ++$result->receipt_no;
        else
            $receipt_no = '50000';
        $schedule = SchedulePlan::all();
        $schedule = json_decode($schedule);
        $possession_date = $schedule[0]->possession_date;

        $projecttype=   ProjectType::where('status', true)->first();
        return view('statement.add-statement', compact('unitNumbersTokenHolds','categories','unitNumbers_of_dealer_package_file','projecttype','floors', 'customers', 'dealers', 'unitNumbers', 'dealerTypes', 'banks', 'cBanks', 'accounts', 'receipt_no', 'possession_date', 'blocks'));
    }




    //Update new statement
    public function updateStatementForm($id)
    {
// dd('abdul');
        $floors = UnitFloor::orderby('name', 'asc')->get();
        $blocks = UnitBlock::orderby('name', 'asc')->get();

        $property = CustomerProperty::where('id', $id)->with('inventory', 'customer', 'statement')->first();
        $customer_statement = CustomerStatement::where('customer_property_id', $property->id)->get();
        $actual_per_istallment =  $customer_statement->where('payment_head', \App\CustomerStatement::installment)->where('inst_no', 1)->sum('due');

        $remaining_installment_count = 0;
        $per_insta = 0;
        $total_remaining_installment = 0;
        if ($property->booking_type == CustomerProperty::normal) {
            if ($property->schedular_type == CustomerProperty::inst_mon_exclude_ann || $property->schedular_type == CustomerProperty::inst_mon_exclude_quar || $property->schedular_type == CustomerProperty::inst_mon_exclude_semi || $property->schedular_type == CustomerProperty::inst_quar_exclude_semi) {

                
                $installmet = CustomerStatement::where('customer_property_id', $property->id)->where('payment_head', CustomerStatement::installment)->where('due', '>', 0)->where('inst_track', 1)->get();

               
                $installmet_remaining =  $installmet->where('received', 0);
                //  dd(sizeof($installmet));
                $total_sum =  $installmet->sum('due');
                if (sizeof($installmet) > 0) {

                    $per_installment = (float)$total_sum / (int)sizeof($installmet);

                    // $per_insta = (int)$per_installment -  (int)$actual_per_istallment;
                    $per_insta = (int)$per_installment  ;
                }
                // dd($per_insta ,$per_installment ,  $actual_per_istallment);
                $remaining_installment_count = 0;



                foreach ($installmet_remaining as $installment_number) {
                    if (!str_contains($installment_number->inst_no, '-b')) {
                        $remaining_installment_count = $remaining_installment_count + 1;
                    }
                }

                //    dd($installmet);

            } else if ($property->schedular_type == CustomerProperty::inst_mon_w_ann || $property->schedular_type == CustomerProperty::inst_mon_w_semi || $property->schedular_type == CustomerProperty::inst_mon_w_quar || $property->schedular_type == CustomerProperty::inst_quar_w_semi) {


                //  dd('2');
                $installmet = CustomerStatement::where('customer_property_id', $property->id)->where('payment_head', CustomerStatement::installment)->where('due', '>', 0)->where('inst_track', 1)->get();
                // dd(sizeof($installmet));
                $installmet_remaining =  $installmet->where('received', 0);

                $total_sum =  $installmet->sum('due');
                if (sizeof($installmet) > 0) {
                    $per_installment = (float)$total_sum / (int)sizeof($installmet);

                    $per_insta = $per_installment -  $actual_per_istallment;
                }
                // dd($per_insta ,$per_installment ,  $actual_per_istallment);



                $remaining_installment_count = 0;



                foreach ($installmet_remaining as $installment_number) {
                    if (!str_contains($installment_number->inst_no, '-b')) {
                        $remaining_installment_count = $remaining_installment_count + 1;
                    }
                }
            } else {

                //  dd('3');

                $installmet = CustomerStatement::where('customer_property_id', $property->id)->where('payment_head', CustomerStatement::installment)->where('due', '>', 0)->where('inst_track', 1)->get();

                $installmet_remaining =  $installmet->where('received', 0);

                $total_sum =  $installmet->sum('due');
                if (sizeof($installmet) > 0) {
                    $per_installment = (float)$total_sum / (int)sizeof($installmet);
                    $per_insta = $per_installment -  $actual_per_istallment;
                }

                $remaining_installment_count = 0;

                foreach ($installmet_remaining as $installment_number) {
                    if (!str_contains($installment_number->inst_no, '-b')) {
                        $remaining_installment_count = $remaining_installment_count + 1;
                    }
                }
            }
        }
        $received_amount = CustomerStatement::where('customer_property_id', $property->id)->sum('received');




        $check_remaining_installments =     $customer_statement->where('payment_head', CustomerStatement::installment)->where('due', '>', 0)->where('received', 0);
        //installment payment head 3
        //    dd( $check_remaining_installments);

        $unitNumber = Inventory::where([['unit_number', $property->inventory->unit_number], ['is_deleted', false]])->first();
        $remaining_amount =    (int)$property->net_pay - (int)$received_amount;
        $customer = Customer::where([['status', true], ['is_deleted', false], ['id', $property->customer->id]])->first();
        $dealers_involved_in_property = DealerTransaction::where('product_id', $id)->get();
        $dealers = Dealer::where([['status', true], ['is_deleted', false]])->with('dealerType')->orderby('name', 'asc')->select('dealer_type_id', 'id', 'name', 'percentage')->get()->groupBy('dealer_type_id');
        $dealerTypes = DealerType::pluck('name', 'id');
        $banks = DepositorBank::all();
        $cBanks = CompanyBank::all();
        $accounts = ChartOfAccount::orderBy('number', 'ASC')->get();

        $result = Receipt::where([['receipt_no', '!=', null]])->orderby('id', 'desc')->first();

        if ($result)
            $receipt_no = ++$result->receipt_no;
        else
            $receipt_no = '50000';


        $schedule = SchedulePlan::all();
        $schedule = json_decode($schedule);
        $possession_date = $schedule[0]->possession_date;

        // dd($floors,$customers,$dealers,$unitNumbers,$dealerTypes,$banks,$cBanks,$accounts,$receipt_no, $possession_date,$blocks,$property);

     $schedule_plan=   SchedulePlan::first();

        return view('statement.update-statement', compact('schedule_plan','per_insta', 'total_remaining_installment', 'remaining_installment_count', 'floors', 'customer', 'dealers', 'unitNumber', 'dealerTypes', 'banks', 'cBanks', 'accounts', 'receipt_no', 'possession_date', 'blocks', 'property', 'remaining_amount', 'dealers_involved_in_property', 'check_remaining_installments', 'customer_statement'));
    }



    //add new statement
    public function addStatementFormCustomer($id)
    {

        $floors = UnitFloor::orderby('name', 'asc')->get();
        $unitNumbers = [];
        $customers = Customer::where([['status', true], ['is_deleted', false]])->orderby('name', 'asc')->get();

        $dealers = Dealer::where([['status', true], ['is_deleted', false]])->with('dealerType')->orderby('name', 'asc')->select('dealer_type_id', 'id', 'name')->get()->groupBy('dealer_type_id');
        $dealerTypes = DealerType::pluck('name', 'id');
        $banks = DepositorBank::all();
        $cBanks = CompanyBank::all();
        $customer = Customer::where('id', $id)->first();

        return view('statement.add-statement', compact('floors', 'customers', 'dealers', 'unitNumbers', 'dealerTypes', 'banks', 'cBanks', 'customer'));
    }

    public function insertStatement(Request $request)
    {

        $messages = [
            'name.required_if' => 'The Name field is required.',
            'cnic.required_if' => 'The Cnic field is required.',
            'father_name.required_if' => 'The S/O field is required.',
            'mobile_number.required_if' => 'The mobile number field is required.',
            'nominee_name.required_if' => 'The Nominee name field is required.',
            'nominee_so_do_wo.required_if' => 'The Nominee S/O D/O W/O field is required.',
            'nominee_cnic.required_if' => 'The Nominee Cnic field is required.',
            'nominee_relation.required_if' => 'The Nominee Relation field is required.',
            'booking_date.required_if' => 'Down Payment Date required',
            'original_boooking_date.required' => 'Booking Date required',
            'nominee_address.required_if' => 'Nominee Address field is required.',
        ];

        $validator = Validator::make($request->all(), [

            'unit_number' => 'required',
            // 'dealer_id' => 'required',
            'name' => 'nullable|required_if:customer_id,|regex:/^[a-zA-Z\s.,-]+$/u',
            'cnic' => 'nullable|required_if:customer_id,|unique:customers,cnic',
            'father_name' => 'nullable|required_if:customer_id,|regex:/^[a-zA-Z\s.,-]+$/u',
            'mobile_number' => 'nullable|required_if:customer_id,',
            'down_payment' => 'numeric',
            'possession' => 'numeric|nullable',
            'installment' => 'numeric',
            'installment_plan' => 'numeric',
            'booking_date' => 'nullable|required_if:booking_type,1',
            'original_boooking_date' => 'required',
            //'membership_number' => 'required|unique:customer_properties,membership_no',
            //'schedule_start_date' => 'required',
            'nominee_name' => 'nullable|required_if:customer_id,|regex:/^[a-zA-Z\s,.-]+$/u',
            'nominee_so_do_wo' => 'nullable|required_if:customer_id,|regex:/^[a-zA-Z\s,.-]+$/u',
            'nominee_address' => 'nullable|required_if:customer_id,',
            'nominee_relation' => 'nullable|required_if:customer_id,|regex:/^[a-zA-Z\s,.-]+$/u',
            'receipt_no' => 'nullable|unique:receipts,receipt_no',
            'invoice_number' => 'nullable|unique:customer_properties,invoice_number'
        ], $messages);

        //............for validate user cnic from dnfbp...................//

        if ($request->cnic) {
            // code...

            $dnfbp_check_point_customer = DNFBP::where('cnic', str_replace('-', '', $request->cnic))->first();

            if ($dnfbp_check_point_customer == true) {
                return redirect('/add/statement')
                    ->withInput()
                    ->with([
                        'message' => 'This Member cnic is found in list of DNFBP. You cant add this customer record.',
                        'alert-type' => 'error',
                    ]);
            }
        }
        if ($request->nominee_cnic) {
            $dnfbp_check_point_nominee = DNFBP::where('cnic', str_replace('-', '', $request->nominee_cnic))->first();

            if ($dnfbp_check_point_nominee == true) {
                return redirect('/add/statement')
                    ->withInput()
                    ->with([
                        'message' => 'This Member cnic is found in list of DNFBP. You cant add this nominee record.',
                        'alert-type' => 'error',
                    ]);
            }
        }

        //.............end...........................................//



        if ($validator->fails()) {
            
            return redirect('/add/statement')
                ->withErrors($validator)
                ->withInput()
                ->with([
                    'message' => 'Invalid Inputs!',
                    'alert-type' => 'error',
                ]);
        }


      
      
        $statement = $this->property->insertNewStatement($request);

        if (!$statement) {
            return redirect('/add/statement')
                ->withInput()
                ->with([
                    'message' => 'Invalid Inputs!',
                    'alert-type' => 'error',
                ]);
        }

        $inv = Inventory::where('id', $request->unit_number)->first();


        activity('Create')->log('New Property Added ' . ' ' . $inv->unit_number);

        return redirect()
            ->route('statement.detail', ['id' => $statement->id])
            ->with([
                'message' => 'Statement created successfully!',
                'alert-type' => 'info'
            ]);
    }





    public function updateStatements(Request $request)
    {
         
// dd($request->all());
if($request->booking_type !=3) {
        $validator = Validator::make($request->all(), [
            
            'schedule_type' => 'required',
            // 'schedule_start_date' => 'required'
        ]);
    
        if ($validator->fails()) {
            return redirect('/edit/statement/' . $request->property_id)
                ->withErrors($validator)
                ->withInput()
                ->with([
                    'message' => 'Invalid Inputs!',
                    'alert-type' => 'error',
                ]);
        }
    }
        $lastPaidDate = CustomerStatement::where('received', '>', 0)->where('customer_property_id', $request->property_id)->latest()->first();

         
        // if ( $lastPaidDate == true && ($request->schedule_start_date <= $lastPaidDate->due_date || $request->booking_date <= $lastPaidDate->due_date  || $request->possession_date <= $lastPaidDate->due_date || $request->allotment_date <= $lastPaidDate->due_date || $request->confirmation_date <= $lastPaidDate->due_date || $request->development_date <= $lastPaidDate->due_date || $request->file_processing_date <= $lastPaidDate->due_date || $request->registration_date <= $lastPaidDate->due_date )) 
        // {
        //      return redirect('/edit/statement/'.$request->property_id)
        //                     ->withInput()
        //                     ->with([
        //                         'message' => 'Last Installment Paid on '.$lastPaidDate->due_date.'. Please select schedule dates after.',

        //                         'alert-type' => 'error',
        //     ]);
        // }
        // CustomerStatement::where('received' , 0)->where('customer_property_id' , $request->property_id)->delete();

        // dd($request->all());
        $result = $this->property->updateStatements($request);

        if (!$result) {
            return redirect('/statement/edit/' . $request->property_id)
                ->withInput()
                ->with([
                    'message' => 'Invalid Inputs!',
                    'alert-type' => 'error',
                ]);
        }

        activity('Update')->log('Edit the property statement.' . $result->customer->name . ' ' . $result->inventory->unit_number);

        return redirect()
            ->route('statement.detail', ['id' => $request->property_id])
            ->with([
                'message' => 'Statement updated successfully!',
                'alert-type' => 'info'
            ]);
    }



    //show the detail of the Dealer
    public function detailStatement($id)
    {

        $property = CustomerProperty::where('id', $id)->with('inventory', 'customer', 'statement', 'propertyTax')->first();

    //   if(!empty($property)){
        $amount = CustomerStatement::where('customer_property_id', $id)->sum('received');

        $receivedAmtPer = $amount * 100 / $property->net_pay;

        $outstandingAmt = ($property->net_pay - $amount);

        $outstandingAmtPer = $outstandingAmt * 100 / $property->net_pay;

        $dealers = DealerTransaction::where('product_id', $id)->get();

        $periorities = PaymentHeadPriority::orderby('priority', 'ASC')->get(['payment_head', 'priority']);

        $overDue = CustomerStatement::where('customer_property_id', $id)->whereDate('due_date', '<',  \Carbon\Carbon::today())->sum('balance');

        $overDuePer = $overDue * 100 / $property->net_pay;

        $pdc_receipt = Receipt::where('customer_property_id', $id)->where('payment_method', Receipt::cheque)->where('cheaque_status', Receipt::pending)->sum('amount');

        $pdcReceiptPer = $pdc_receipt * 100 / $property->net_pay;

        $allotment = false;
        $provisional = false;

        if ($receivedAmtPer >= 10) {
            $allotment = true;
        }

        if ($receivedAmtPer >= 25) {
            $provisional = true;
        }

        $banks = DepositorBank::all();
        $cBanks = CompanyBank::all();

        $waiveOff = SurchargeReceipt::where('customer_property_id', $property->id)->where('customer_id', $property->customer->id)->where('amount', 0)->sum('total_surcharge');

        $paidSurcharge = SurchargeReceipt::where('customer_property_id', $property->id)->where('customer_id', $property->customer->id)->sum('amount');

        $developmentcharges = CustomerStatement::where([['customer_property_id', $id],['payment_head',CustomerStatement::development]])->sum('due');

        activity('View')->log('View the property info ' . $property->inventory->unit_number . $property->customer->name);

       
        return view('statement.detail-statement', compact('developmentcharges','paidSurcharge', 'waiveOff', 'property', 'allotment', 'provisional', 'amount', 'receivedAmtPer', 'outstandingAmtPer', 'outstandingAmt', 'overDue', 'dealers', 'banks', 'cBanks', 'periorities', 'overDuePer', 'pdc_receipt', 'pdcReceiptPer'));

    //   }
       
       
    }

    //show the edit statement form
    public function editStatementForm($id)
    {

        $property = CustomerProperty::where('id', $id)->with('inventory', 'customer', 'statement')->first();

        $schedule = SchedulePlan::first();
        $info = Inventory::with('size', 'floor', 'type', 'categories')->where('id', $property->inventory->id)->first();
        $receipt = Receipt::where([['customer_property_id', $property->id], ['payment_head', Receipt::down_payment]])->first();

        return view('statement.update-schedule', compact('property', 'schedule', 'info', 'receipt'));
    }

    //show the edit statement form
    public function editMembershipForm($id)
    {

        $property = CustomerProperty::where('id', $id)->with('customer', 'statement', 'inventory')->first();


        return view('statement.edit-statement', compact('property'));
    }

    //show the edit Pending statement form
    public function editPendingStatementForm($id)
    {

        $property = CustomerProperty::where('id', $id)->with('customer', 'statement', 'size', 'type')->first();

        return view('statement.edit-pending-statement', compact('property'));
    }

    //update the membership no.
    public function updatePendingStatement(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'membership_no' => 'required|unique:customer_properties,membership_no,' . $request->id,
            'status' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect('/pending-statement/edit/' . $request->id)
                ->withErrors($validator)
                ->withInput()
                ->with([
                    'message' => 'Invalid Inputs!',
                    'alert-type' => 'error',
                ]);
        }

        $this->property->updateClientId($request);


        activity('Update')->log('Assign client id.');


        return redirect()
            ->route('statement.detail', ['id' => $request->id])
            ->with([
                'message' => 'Statement updated successfully!',
                'alert-type' => 'info'
            ]);
    }

    public function updateStatement(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'schedule_type' => 'required',
            'schedule_start_date' => 'required'
        ]);

        if ($validator->fails()) {
            return redirect('/statement/edit/' . $request->property_id)
                ->withErrors($validator)
                ->withInput()
                ->with([
                    'message' => 'Invalid Inputs!',
                    'alert-type' => 'error',
                ]);
        }

        $result = $this->property->updateStatement($request);

        if (!$result) {
            return redirect('/statement/edit/' . $request->property_id)
                ->withInput()
                ->with([
                    'message' => 'Invalid Inputs!',
                    'alert-type' => 'error',
                ]);
        }

        activity('Update')->log('Edit the property statement.' . $result->customer->name . ' ' . $result->inventory->unit_number);

        return redirect()
            ->route('statement.detail', ['id' => $request->property_id])
            ->with([
                'message' => 'Statement updated successfully!',
                'alert-type' => 'info'
            ]);
    }

    public function updateInstallmentStatement(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'schedule_start_date' => 'required'
        ]);

        if ($validator->fails()) {
            return redirect('/membership/edit/' . $request->id)
                ->withErrors($validator)
                ->withInput()
                ->with([
                    'message' => 'Invalid Inputs!',
                    'alert-type' => 'error',
                ]);
        }

        $result = $this->property->updateInstallmentStatement($request);

        if (!$result) {
            return redirect('/membership/edit/' . $request->id)
                ->withInput()
                ->with([
                    'message' => 'Invalid Inputs!',
                    'alert-type' => 'error',
                ]);
        }

        activity('Update')->log('Edit the installment property statement.' . $result->customer->name . ' ' . $result->inventory->unit_number);

        return redirect()
            ->route('statement.detail', ['id' => $request->id])
            ->with([
                'message' => 'Statement updated successfully!',
                'alert-type' => 'info'
            ]);
    }

    //delete the specific Statement
    public function deleteStatement($id)
    {

        // $this->property->deleteProperty($id);

        $pro = CustomerProperty::where('id', $id)->with('inventory', 'customer')->first();

        CustomerProperty::where('id', $id)->update(['is_deleted' => true]);

        Receipt::where('customer_property_id', $pro->id)->update(['is_deleted' => true]);

        $amount = Receipt::where([['customer_id', $pro->customer_id], ['is_deleted', false]])->sum('amount');

        Customer::where('id', $pro->customer_id)->update(['total_paid_amount' => $amount]);

        activity('Delete')->log('Delete the property info ' . $pro->inventory->unit_number . $pro->customer->name);

        return redirect()->route('statement.all')->with([
            'message' => 'Statement deleted Successfully!',
            'alert-type' => 'info',
        ]);
    }



    //download statement
    public function downloadStatement($id)
    {

        $data = array();

        $data['property'] = CustomerProperty::where('id', $id)->with('inventory', 'customer', 'statement')->first();
        $data['amount'] = CustomerStatement::where('customer_property_id', $id)->sum('received');
        $data['receivedAmtPer'] = $data['amount'] * 100 / $data['property']->net_pay;

        $pdf = \PDF::loadView('statement.download-statement', $data);

        $name = '';

        activity('Download')->log('Download Payment schedule ' . $name);

        return $pdf->download($name . '-statement.pdf');
    }

    public function smsForm(Request $request)
    {

        $data = array();

        $data['property'] = CustomerProperty::where('id', $request->property_id)->with('inventory', 'customer', 'statement')->first();

        return view('statement.sms-modal', $data);
    }

    public function sendSMSForm(Request $request)
    {

        SmsController::sendSMS("92" . substr($request->number, 1), $request->message);

        activity('Send')->log('SMS send to ' . $request->number);

        return redirect()->back()->with([
            'message' => 'Sms send Successfully!',
            'alert-type' => 'info',
        ]);
    }

    public function reminderForm(Request $request)
    {

        $data = array();

        $data['property'] = CustomerProperty::where('id', $request->property_id)->first();

        return view('statement.reminder-modal', $data);
    }

    public function updateReminder(Request $request)
    {

        CustomerProperty::where('id', $request->property_id)->update(['reminder_text' => $request->reminder_text, 'reminder_date' => $request->reminder_date]);

        activity('Reminder Update')->log('Reminder updated ' . $request->property);

        return redirect()->back()->with([
            'message' => 'Reminder updated Successfully!',
            'alert-type' => 'info',
        ]);
    }

    //update the statment table
    public function updateTable(Request $request)
    {

        $filters = array();
 
        if ($request->unit != 0)
            $filters['unit'] = $request->unit;
        if ($request->customer != 0)
            $filters['customer'] = $request->customer;
        if ($request->status != 0)
            $filters['status'] = $request->status;
        if ($request->dealer != 0)
            $filters['dealer'] = $request->dealer;
        if ($request->unit_size != 0)
            $filters['unit_size'] = $request->unit_size;
        if ($request->unit_type != 0)
            $filters['unit_type'] = $request->unit_type;
        if ($request->unit_block != 0)
            $filters['unit_block'] = $request->unit_block;
            if ($request->multipro_id != 0)
            $filters['multipro_id'] = $request->multipro_id;

        $data = $this->statement->updateTable($filters);


        return view('statement.update-table', $data);
    }

    //update the statment table
    public function updatePendingTable(Request $request)
    {

        $filters = array();

        if ($request->unit != 0)
            $filters['unit'] = $request->unit;
        if ($request->customer != 0)
            $filters['customer'] = $request->customer;
        if ($request->status != 0)
            $filters['status'] = $request->status;
        if ($request->dealer != 0)
            $filters['dealer'] = $request->dealer;
            if ($request->multipro_id != 0)
            $filters['multipro_id'] = $request->multipro_id;

        $data = $this->statement->updateTable($filters);

        return view('statement.update-pending-table', $data);
    }




    ///////////////////////////RECEIPT VIEWS/////////////////////////////



    public function getDownpaymentReceipts()
    {
        $project_ids=   $this->getCookieInfomation();
        if($project_ids['status'] == 'error'){
            return redirect()

            ->back()
            ->with([
                'message' => 'Invalid Inputs!',
                'alert-type' => 'error',
            ]);
        }
        $ids=[];
        if(is_array($project_ids['project_ids'])){
            $ids= $project_ids['project_ids']; 
        }
        else
        $ids[]= $project_ids['project_ids'];
        

        $data = array();

        $data['receipts'] = Receipt::with('property')
        ->where([['is_approved', 1], ['is_deleted', false]])
        ->whereIn('multi_project_id', $ids)
        ->orderBy('id', 'desc')->orderBy('receipt_date', 'asc')->paginate(50);
        $data['totalAmount'] = Receipt::where([['is_approved', 1], ['is_deleted', false]])
        ->whereIn('multi_project_id', $ids)
        ->count();

        $data['unitNumbers'] = Inventory::where([['is_deleted', false], ['status', '!=', Inventory::open]])
        ->whereIn('multi_project_id', $ids)
        ->select('id', 'unit_number')->orderBy('unit_number', 'asc')->get();
        $data['customers'] = Customer::where('is_deleted', false)->select('id', 'name')->orderBy('name', 'asc')->get();
        $data['dealers'] = Dealer::where('is_deleted', false)->select('id', 'name', 'code')->orderBy('name', 'asc')->get();

        $data['receiptNo'] = Receipt::where('is_deleted', false)
        ->where('is_approved', true)
        ->whereIn('multi_project_id', $ids)
        ->select('id', 'receipt_no')->get();
        // $data['accounts'] = ChartOfAccount::orderBy('number','ASC')->get();

        activity('View')->log('DownPayment Receipt list.');

        return view('receipt.index', $data);
    }




    public function getSurchargeReceipts()
    {

        $data = array();

        $data['receipts'] = SurchargeReceipt::with('property')->where([['is_deleted', false]])->orderBy('id', 'desc')->paginate(25);

        $data['totalAmount'] = SurchargeReceipt::where([['is_deleted', false]])->count();

        $data['unitNumbers'] = Inventory::where([['is_deleted', false], ['status', '!=', Inventory::open]])->select('id', 'unit_number')->orderBy('unit_number', 'asc')->get();
        $data['customers'] = Customer::where('is_deleted', false)->select('id', 'name')->orderBy('name', 'asc')->get();
        $data['dealers'] = Dealer::where('is_deleted', false)->select('id', 'name', 'code')->orderBy('name', 'asc')->get();

        $data['receiptNo'] = SurchargeReceipt::where('is_deleted', false)->select('id', 'receipt_no')->get();
        // $data['accounts'] = ChartOfAccount::orderBy('number','ASC')->get();

        activity('View')->log('Surcharge Receipt list.');

        return view('receipt.surcharge', $data);
    }



    public function getCustomerTaxReceipts()
    {
        $data = array();

        $data['receipts'] = TaxReceipt::orderBy('id', 'desc')->get();

        $data['totalAmount'] = TaxReceipt::count();

        activity('View')->log('Customer Tax  Receipt list.');

        return view('receipt.customer_tax_receipt', $data);
    }

    public function detailCustomerReceipt($id = null)
    {
        $data = array();

        $digit = new \NumberFormatter("en", \NumberFormatter::SPELLOUT);

        $data['receipt'] = TaxReceipt::where('id', $id)->first();

        $data['words'] = $digit->format($data['receipt']->receipt_amount);

        return view('receipt.customer_tax_detail', $data);
    }


    public function getCompanyTaxReceipts()
    {
        $data = array();

        $data['receipts'] = CustomerPropertyTax::where('tax_pay_by', Receipt::company)->orderBy('id', 'desc')->get();

        $data['totalAmount'] = CustomerPropertyTax::where('tax_pay_by', Receipt::company)->count();

        activity('View')->log('Company Tax  Receipt list.');

        return view('receipt.company_tax_receipt', $data);
    }



    public function detailCompanyReceipt($id = null)
    {
        $data = array();

        $digit = new \NumberFormatter("en", \NumberFormatter::SPELLOUT);

        $data['receipt'] = CustomerPropertyTax::where('tax_pay_by', Receipt::company)->where('id', $id)->first();

        $data['words'] = $digit->format($data['receipt']->tax);

        return view('receipt.company_tax_detail', $data);
    }


    public function getInstallmentReceipts()
    {

        $data = array();

        $data['receipts'] = Receipt::with('property')->where([['payment_head', '!=', Receipt::possession_fee], ['payment_head', '!=', Receipt::down_payment], ['is_deleted', false]])->orderBy('id', 'desc')->paginate(25);

        $data['totalAmount'] = Receipt::where([['payment_head', '!=', Receipt::possession_fee], ['payment_head', '!=', Receipt::down_payment], ['is_deleted', false]])->count();

        $data['unitNumbers'] = Inventory::where([['is_deleted', false], ['status', '!=', Inventory::open]])->select('id', 'unit_number')->orderBy('unit_number', 'asc')->get();
        $data['customers'] = Customer::where('is_deleted', false)->select('id', 'name')->orderBy('name', 'asc')->get();
        $data['dealers'] = Dealer::where('is_deleted', false)->select('id', 'name', 'code')->orderBy('name', 'asc')->get();

        $data['receiptNo'] = Receipt::where('is_deleted', false)->select('id', 'receipt_no')->get();
        $data['accounts'] = ChartOfAccount::orderBy('number', 'ASC')->get();

        activity('View')->log('Installment Receipt List');

        return view('receipt.index', $data);
    }

    public function getPendingReceipts()
    {
        $data = array();
        $project_ids=   $this->getCookieInfomation();
        if($project_ids['status'] == 'error'){
            return redirect()

            ->back()
            ->with([
                'message' => 'Invalid Inputs!',
                'alert-type' => 'error',
            ]);
        }
        $ids=[];
        if(is_array($project_ids['project_ids'])){
            $ids= $project_ids['project_ids']; 
        }
        else
        $ids[]= $project_ids['project_ids'];

        $data['receipts'] = Receipt::with('property')
        ->whereIn('multi_project_id', $ids)
        ->where([['is_approved', false], ['is_deleted', false]])
        ->where('cheaque_status', Receipt::pending)->orderBy('receipt_date', 'asc')->get();

        $data['totalAmount'] = Receipt::where([['is_approved', false], ['is_deleted', false], ['cheaque_status', Receipt::pending]])
        ->whereIn('multi_project_id', $ids)
        ->count();

        activity('View')->log('Pending Receipt List');

        return view('receipt.pending', $data);
    }


    public function getCancelReceipts()
    {
        $data = array();

        $data['receipts'] = Receipt::with('property')->where([['is_approved', false], ['is_deleted', false]])->where('cheaque_status', Receipt::cancel)->orderBy('id', 'desc')->get();

        $data['totalAmount'] = Receipt::where([['is_approved', false], ['is_deleted', false], ['cheaque_status', Receipt::cancel]])->count();

        activity('View')->log('Cancel Receipt List');

        return view('receipt.cancel', $data);
    }


    public function approvedReceipt($id)
    {

        $current_receipt = Receipt::find($id);

        $isLessDateReceipt = Receipt::where('receipt_date', '<', $current_receipt->receipt_date)->where('customer_property_id', $current_receipt->customer_property_id)->where('is_approved', false)->where('is_deleted', false)->first();

 
        // customer_property_id
        // $properties = CustomerProperty
        if (!empty($isLessDateReceipt)) {
            return redirect('/receipt/pendings')
                ->withInput()
                ->with([
                    'message' => 'Error ! First approve lower date receipt.',
                    'alert-type' => 'error',
                ]);
        }


        $receipt = $this->receipt->approvedReceipt($id);

        if (!$receipt) {
            return redirect('/receipt/pendings')
                ->withInput()
                ->with([
                    'message' => 'Something went wrong!',
                    'alert-type' => 'error',
                ]);
        }

        $receipt = Receipt::find($id);
        Receipt::where('id', $id)->update(['cheaque_status' => Receipt::approve]);

        activity('Approved')->log('Receipt Approved ' . $receipt->receipt_no);

        return redirect()
            ->route('statement.detail', ['id' => $receipt->customer_property_id])
            ->with([
                'message' => 'Receipt Approved successfully!',
                'alert-type' => 'info'
            ]);
    }

    function cancelledReceipt($id)
    {
        $receipt = Receipt::find($id);
        Receipt::where('id', $id)->update(['cheaque_status' => Receipt::cancel]);
        activity('Cancel')->log('Receipt Cancelled ' . $receipt->receipt_no);

        return redirect()
            ->back()
            ->with([
                'message' => 'Receipt Cancelled successfully!',
                'alert-type' => 'info'
            ]);
    }

    //update the receipt table
    public function updateReceiptTable(Request $request)
    {

        $filters = array();

        if ($request->unit != 0)
            $filters['unit'] = $request->unit;
        if ($request->customer != 0)
            $filters['customer'] = $request->customer;
        if ($request->status != 0)
            $filters['status'] = $request->status;
        if ($request->dealer != 0)
            $filters['dealer'] = $request->dealer;
        if ($request->receipt_no)
            $filters['receipt_no'] = $request->receipt_no;
        if ($request->payment_head)
            $filters['payment_head'] = $request->payment_head;
        if ($request->payment_mode)
            $filters['payment_mode'] = $request->payment_mode;

        $data = $this->receipt->updateTable($filters);

        return view('receipt.update-table', $data);
    }



    //update the receipt table
    public function updateSurchargeReceiptTable(Request $request)
    {

        $filters = array();

        if ($request->unit != 0)
            $filters['unit'] = $request->unit;
        if ($request->customer != 0)
            $filters['customer'] = $request->customer;
        if ($request->status != 0)
            $filters['status'] = $request->status;
        if ($request->dealer != 0)
            $filters['dealer'] = $request->dealer;
        if ($request->receipt_no)
            $filters['receipt_no'] = $request->receipt_no;
        if ($request->payment_head)
            $filters['payment_head'] = $request->payment_head;
        if ($request->payment_mode)
            $filters['payment_mode'] = $request->payment_mode;

        $data = $this->surcharge_receipt->updateTable($filters);

        return view('receipt.surcharge-update-table', $data);
    }


    public function addDealerPackageReceiptForm()
    {
        $project_ids=   $this->getCookieInfomation();
        if($project_ids['status'] == 'error'){
            return redirect()

            ->back()
            ->with([
                'message' => 'Invalid Inputs!',
                'alert-type' => 'error',
            ]);
        }
        $ids=[];
        if(is_array($project_ids['project_ids'])){
            $ids= $project_ids['project_ids']; 
        }
        else
        $ids[]= $project_ids['project_ids'];


        $customers = Customer::where('is_deleted', false)->get();
        $banks = DepositorBank::all();
        $cBanks = CompanyBank::all();
        $result = Receipt::where([['receipt_no', '!=', null]])
        ->whereIn('multi_project_id', $ids)
            ->orderby('receipt_no', 'desc')->first();

        if ($result)
            $receipt_no = ++$result->receipt_no;
        else
            $receipt_no = '50000';



            $result2 = DealerPackageReceipt::where([['receipt_no', '!=', null]])
            
            ->orderby('receipt_no', 'desc')->first();

        if ($result2)
            $delaer_package_receipt_no = ++$result2->receipt_no;
        else
            $delaer_package_receipt_no = '100000';

        $accounts = ChartOfAccount::orderBy('number', 'ASC')->get();

        //get dealers payable records 

        $dealers = Dealer::where([['is_deleted', false]])->get();

        $dealersRecord = array();
        //rebate history
        foreach ($dealers as $d) {
            $dealersRecord[$d->id]['info'] = $d;
            $transactions = DealerTransaction::where('dealer_id', $d->id)->with('property')->get();
            $availableRebate = array();
            foreach ($transactions as $t) {

                if ($t->property) {
                    $rebate = $t->amount - DealerPaidRebate::where([['dealer_id', $d->id], ['property_id', $t->property->id], ['is_deleted', false]])->sum('amount');
                    if ($rebate > 0)
                        $availableRebate[$t->id] = $t->property->inventory ? $t->property->inventory->unit_number : '' . ' - ' . $rebate;
                }
            }
            $dealersRecord[$d->id]['rebate'] = $availableRebate;
        }

        $vendor_pos = PurchaseRequest::WithAndWhereHas('receipts', function ($query) {
            $query->where('is_book', '=', false);
            $query->where('receipt_type', '=', true);
        })
            ->get();

        $vendor_pos = json_decode(json_encode($vendor_pos));

        $unitNumbers = TokenReceipt::where([['is_approved', true], ['is_book', false]])->with('inventory')->select('id', 'unit_id', 'token_amount')->get();


        $merging_properties = MergingProperty::orderBy('id', 'ASC')->get(['id', 'mrf_no']);

        // $adjusted_properties = CancelProperty::where('after_cancellation_status', 'adjusted')->get();








        $adjusted_properties = CancelProperty::join('receipts', 'cancel_properties.id', '=', 'receipts.cancel_property_id')
            ->join('unit_adjusts', 'cancel_properties.id', '=', 'unit_adjusts.cancel_property_id')
            ->havingRaw('sum(receipts.amount) > ?', ['unit_adjusts.total_received_amount'])
            ->get(['cancel_properties.*']);

        return view('receipt.add-receipt-dealer-property', compact('delaer_package_receipt_no','dealers','adjusted_properties', 'customers', 'banks', 'merging_properties', 'cBanks', 'receipt_no', 'accounts', 'dealersRecord', 'vendor_pos', 'unitNumbers'));
    }
    public function addReceiptForm()
    {

        $project_ids=   $this->getCookieInfomation();
        if($project_ids['status'] == 'error'){
            return redirect()

            ->back()
            ->with([
                'message' => 'Invalid Inputs!',
                'alert-type' => 'error',
            ]);
        }
        $ids=[];
        if(is_array($project_ids['project_ids'])){
            $ids= $project_ids['project_ids']; 
        }
        else
        $ids[]= $project_ids['project_ids'];

        $customers = Customer::where('is_deleted', false)->get();
        $banks = DepositorBank::all();
        $cBanks = CompanyBank::all();
        $result = Receipt::where([['receipt_no', '!=', null]])
            ->orderby('receipt_no', 'desc')->first();

        if ($result)
            $receipt_no = ++$result->receipt_no;
        else
            $receipt_no = '50000';



            $result2 = DealerPackageReceipt::where([['receipt_no', '!=', null]])
            ->orderby('receipt_no', 'desc')->first();

        if ($result2)
            $delaer_package_receipt_no = ++$result2->receipt_no;
        else
            $delaer_package_receipt_no = '100000';

        $accounts = ChartOfAccount::orderBy('number', 'ASC')->get();

        //get dealers payable records 

        $dealers = Dealer::where([['is_deleted', false]])->get();

        $dealersRecord = array();
        //rebate history
        foreach ($dealers as $d) {
            $dealersRecord[$d->id]['info'] = $d;
            $transactions = DealerTransaction::where('dealer_id', $d->id)->with('property')->get();
            $availableRebate = array();
            foreach ($transactions as $t) {

                if ($t->property) {
                    $rebate = $t->amount - DealerPaidRebate::where([['dealer_id', $d->id], ['property_id', $t->property->id], ['is_deleted', false]])->sum('amount');
                    if ($rebate > 0)
                        $availableRebate[$t->id] = $t->property->inventory ? $t->property->inventory->unit_number : '' . ' - ' . $rebate;
                }
            }
            $dealersRecord[$d->id]['rebate'] = $availableRebate;
        }

        $vendor_pos = PurchaseRequest::WithAndWhereHas('receipts', function ($query) {
            $query->where('is_book', '=', false);
            $query->where('receipt_type', '=', true);
        })
            ->get();

        $vendor_pos = json_decode(json_encode($vendor_pos));

        $unitNumbers = TokenReceipt::where([['is_approved', true], ['is_book', false]])->with('inventory')->select('id', 'unit_id', 'token_amount')->get();


        $merging_properties = MergingProperty::orderBy('id', 'ASC')->get(['id', 'mrf_no']);

        // $adjusted_properties = CancelProperty::where('after_cancellation_status', 'adjusted')->get();








        $adjusted_properties = CancelProperty::join('receipts', 'cancel_properties.id', '=', 'receipts.cancel_property_id')
            ->join('unit_adjusts', 'cancel_properties.id', '=', 'unit_adjusts.cancel_property_id')
            ->whereIn('multi_project_id', $ids)
            ->havingRaw('sum(receipts.amount) > ?', ['unit_adjusts.total_received_amount'])
            ->get(['cancel_properties.*']);

        return view('receipt.add-receipt', compact('delaer_package_receipt_no','dealers','adjusted_properties', 'customers', 'banks', 'merging_properties', 'cBanks', 'receipt_no', 'accounts', 'dealersRecord', 'vendor_pos', 'unitNumbers'));
    }

        public function registrationLetter($id)
        {
            
        $property = CustomerProperty::where('id', $id)->with('inventory', 'customer', 'statement', 'propertyTax')->first();

        // dd($property->inventory->dealerPackageOpenFileUnit->endUserForm->app_form_no);
            activity('Detail')->log('Detailed Registration Letter');

            return view('openfile.registration-empty-letter',compact('property'));
            // , compact('detail_dealer_openfile'));
        }

    public function updatePropertyForm(Request $request)
    {
        $project_ids=   $this->getCookieInfomation();
        if($project_ids['status'] == 'error'){
            return redirect()

            ->back()
            ->with([
                'message' => 'Invalid Inputs!',
                'alert-type' => 'error',
            ]);
        }
        $ids=[];
        if(is_array($project_ids['project_ids'])){
            $ids= $project_ids['project_ids']; 
        }
        else
        $ids[]= $project_ids['project_ids'];

        $properties = CustomerProperty::where([['customer_id', $request->customer_id], ['is_deleted', false], ['status', CustomerProperty::approved]])
        ->whereIn('multi_project_id', $ids)
        ->with('inventory')->get();

        $receivedAmount = array();
        $lastDate = array();
        $remainingAmount = array();
        $cancel_properties = CustomerProperty::where('status', CustomerProperty::cancel)
        ->whereIn('multi_project_id', $ids)
        ->pluck('id');

        foreach ($properties as $property) {
            $receivedAmount[$property->id] = CustomerStatement::whereNotIn('customer_property_id', $cancel_properties)->where([['customer_property_id', $property->id]])->sum('received');
            $lastDate[$property->id] = Receipt::where('customer_property_id', $property->id)->orderBy('receipt_date', 'desc')->first();
            $remainingAmount[$property->id] = $property->net_pay - $receivedAmount[$property->id];
        }

        return view('receipt.update-property', compact('properties', 'receivedAmount', 'lastDate', 'remainingAmount'));
    }

    public function editUpdatePropertyForm(Request $request)
    {

        // dd($request->all());
        $project_ids=   $this->getCookieInfomation();
        if($project_ids['status'] == 'error'){
            return redirect()

            ->back()
            ->with([
                'message' => 'Invalid Inputs!',
                'alert-type' => 'error',
            ]);
        }
        $ids=[];
        if(is_array($project_ids['project_ids'])){
            $ids= $project_ids['project_ids']; 
        }
        else
        $ids[]= $project_ids['project_ids'];
        

        $receipt = Receipt::where('id', $request->receipt_id)->with('customer', 'property')->first();
        $properties = CustomerProperty::where([['customer_id', $request->customer_id], ['is_deleted', false], ['status', CustomerProperty::approved]])
        ->whereIn('multi_project_id', $ids)
        ->with('inventory')->get();

        $receivedAmount = array();
        $lastDate = array();
        $remainingAmount = array();
        $cancel_properties = CustomerProperty::where('status', CustomerProperty::cancel)
        ->whereIn('multi_project_id', $ids)
        ->pluck('id');

        foreach ($properties as $property) {
            $receivedAmount[$property->id] = CustomerStatement::whereNotIn('customer_property_id', $cancel_properties)->where([['customer_property_id', $property->id]])->sum('received');
            $lastDate[$property->id] = Receipt::where('customer_property_id', $property->id)->orderBy('receipt_date', 'desc')->first();
            $remainingAmount[$property->id] = $property->net_pay - $receivedAmount[$property->id];
        }

        return view('receipt.update-property-edit', compact('receipt','properties', 'receivedAmount', 'lastDate', 'remainingAmount'));
    }


    public function updatePackageForm(Request $request)
    {

        // $properties = CustomerProperty::where([['customer_id', $request->customer_id], ['is_deleted', false], ['status', CustomerProperty::approved]])->with('inventory')->get();


        $dealer_openfile_package = DealerPackage::where([['is_deleted',false],['is_approved',1]])->where('dealer_id',$request->dealer_id)->get();

        

       

        return view('receipt.update-package', compact('dealer_openfile_package'));
    }

    public function insertReceipt(Request $request)
    {

        $request->validate([
            'type' => 'required|integer',
             
        ]);
        if ($request->type == 1) {

            $messages = [
                'bank_name.required_if' => 'Depositor Bank Name is required',
                'company_account.required_if' => 'Company Account is required',
                'cheque_number.required_if' => 'Cheque Number is required.',
                'drawn_date' => 'Drawn Date is required',
                'dealer_adjustment_unit_id' => 'Dealer Payable Rebates is required',
                'vendor_purchase_order_id' => 'Vendor Bill is required',
            ];

            $validator = Validator::make(
                $request->all(),
                [
                    'amount' => 'required|regex:/^[0-9]+$/u',
                    'dealer_id' => 'required',
                    'dealerpackage_id' => 'required',
                    'payment_method' => 'required',
                    'payment_head' => 'required',
                    'receipt_date' => 'required',
                    'bank_name' => 'nullable|required_if:payment_method,2,3',
                    'company_account' => 'nullable|required_if:payment_method,2,3',
                    'drawn_date' => 'nullable|required_if:payment_method,3',
                    'cheque_number' => 'nullable|required_if:payment_method,3|regex:/^[a-zA-Z\s0-9]+$/u',
                    'dealer_adjustment_unit_id' => 'nullable|required_if:adjustment_type,4',
                    'vendor_purchase_order_id' => 'nullable|required_if:adjustment_type,4',
                    'receipt_no' => 'required|unique:receipts,receipt_no',
                    'roll_back_properties' => 'nullable|required_if:adjustment_type,7|regex:/^[0-9]+$/u'
                ],
                $messages
            );



            if ($validator->fails()) {
                return redirect('/add/receipt')
                    ->withErrors($validator)->withInput()
                    ->with(['message' => 'Invalid Inputs!', 'alert-type' => 'error',]);
            }
        
        
        
            $dealerpackage = DealerPackage::where('id', $request->dealerpackage_id)->first();
            $paid_amount=   $dealerpackage->dealerPackagePayment->where('dealer_package_id',$dealerpackage->id)->where('is_approved',1)->sum('amount');    
            $remainingAmount = $dealerpackage->package->total_price - $paid_amount;
            if ($request->amount > $remainingAmount) {
                return redirect('/add/receipt')
                    ->with(['message' => 'entered amount is more then remaining amount!', 'alert-type' => 'error',]);
            }

            if($request->payment_head == Receipt::package_payment ){
                $receipt = $this->dealer_package_receipt->insertReceipt($request);
            }
          
            return redirect()
            ->back()
            ->with(['message' => 'Receipt added Successfully!', 'alert-type' => 'info']);
    
           
        
        
        
        } 
        
 
        
        else if ($request->type == 0) {
            $messages = [
                'bank_name.required_if' => 'Depositor Bank Name is required',
                'company_account.required_if' => 'Company Account is required',
                'cheque_number.required_if' => 'Cheque Number is required.',
                'drawn_date' => 'Drawn Date is required',
                'dealer_adjustment_unit_id' => 'Dealer Payable Rebates is required',
                'vendor_purchase_order_id' => 'Vendor Bill is required',
            ];

            $validator = Validator::make(
                $request->all(),
                [
                    'amount' => 'required|regex:/^[0-9]+$/u',
                    'customer_id' => 'required',
                    'customer_property_id' => 'required',
                    'payment_method' => 'required',
                    'payment_head' => 'required',
                    'receipt_date' => 'required',
                    'bank_name' => 'nullable|required_if:payment_method,2,3',
                    'company_account' => 'nullable|required_if:payment_method,2,3',
                    'drawn_date' => 'nullable|required_if:payment_method,3',
                    'cheque_number' => 'nullable|required_if:payment_method,3|regex:/^[a-zA-Z\s0-9]+$/u',
                    'dealer_adjustment_unit_id' => 'nullable|required_if:adjustment_type,4',
                    'vendor_purchase_order_id' => 'nullable|required_if:adjustment_type,4',
                    'receipt_no' => 'required|unique:receipts,receipt_no',
                    'roll_back_properties' => 'nullable|required_if:adjustment_type,7|regex:/^[0-9]+$/u'
                ],
                $messages
            );



            if ($validator->fails()) {
                return redirect('/add/receipt')
                    ->withErrors($validator)->withInput()
                    ->with(['message' => 'Invalid Inputs!', 'alert-type' => 'error',]);
            }

            // dd($request->all());
            // amount
            $property = CustomerProperty::where('id', $request->customer_property_id)->first();

            $receivedAmount = CustomerStatement::where([['customer_property_id', $request->customer_property_id]])->sum('received');
            $remainingAmount = $property->net_pay - $receivedAmount;
            if ($request->amount > $remainingAmount) {
                return redirect('/add/receipt')
                    ->with(['message' => 'entered amount is more then remaining amount!', 'alert-type' => 'error',]);
            }








            if ($request->payment_head != Receipt::surcharge) {
                $receipt = $this->receipt->insertReceipt($request);
            } else {
                $receipt = $this->surcharge_receipt->insertReceipt($request);
            }


            if (!$receipt) {
                return redirect('/add/receipt')->withInput()
                    ->with(['message' => 'Something went wrong!', 'alert-type' => 'error',]);
            }


            if ($request->payment_method == Receipt::merging) {
                Receipt::where('id', $receipt->id)->update(['merging_property_id' => $request->merging_property_id]);
            }
            // if ($request->payment_method == Receipt::adjustment && $request->adjustment_type == Receipt::roll_back) {
            //     Receipt::where('id', $receipt->id)->update(['adjustment_type ' => $request->adjustment_type]);
            // }


            if ($request->payment_head != Receipt::surcharge) {

                activity('Create')
                    ->log('New Receipt Added ' . $request->receipt_no);
            } else {
                activity('Create')
                    ->log('New Surcharge Receipt Added ' . $request->receipt_no);
            }

            if ($request->payment_head != Receipt::surcharge) {


                if ($request->is_approved) {

                    return redirect()
                        ->route('statement.detail', ['id' => $request->customer_property_id])
                        ->with(['message' => 'Payment added successfully!', 'alert-type' => 'info']);
                } else {
                    return redirect()
                        ->back()
                        ->with(['message' => 'Receipt send for approval!', 'alert-type' => 'info']);
                }
            } else {
                return redirect()
                    ->back()
                    ->with(['message' => 'Receipt added Successfully!', 'alert-type' => 'info']);
            }
        }
    }

    function uploadReceiptDocument(Request $request)
    {

        $receipt_id = $request->input('receipt_id');

        $supported_image = array(
            'gif',
            'jpg',
            'JPG',
            'jpeg',
            'png',
            'PNG',
            'docx',
            'pdf',
        );

        DB::beginTransaction();

        try {

            if ($request->file('files')) {
                foreach ($request->file('files') as $file) {

                    $imagePath = $file;
                    $imageExtension = $imagePath->getClientOriginalExtension();

                    if (!in_array($imageExtension, $supported_image)) {
                        echo json_encode(array('response' => 'invalid_document', 'message' => 'Only jpg|png|JPG|PNG|jpeg|gif|pdf|docx  Aceptable.'));

                        DB::rollback();
                        exit();
                    }

                    if (in_array($imageExtension, array('docx', 'pdf'))) {
                        $imageName = time() . '.' . $imagePath->getClientOriginalName();
                    } else {
                        $imageName = md5(time() . '.' . $imagePath->getClientOriginalName());
                    }

                    $path = $imagePath->storeAs('receipt_documents', $imageName, 'public');


                    Receiptdocument::create([
                        'receipt_id' => $receipt_id,
                        'document_path' => $imageName,
                    ]);
                }

                DB::commit();

                echo json_encode(array('response' => 'yes'));
            } else {
                echo json_encode(array('response' => 'invalid_document', 'message' => 'Please Select files to upload.'));
                DB::rollback();
                exit();
            }
        } catch (\Exception $e) {
            DB::rollback();
            echo json_encode(array('response' => 'invalid_document', 'message' => 'Something went wrong. Please Refresh the page.'));
        }
    }

    public function deleteDocument($id = null)
    {

        $receipt_document = Receiptdocument::find($id);

        if (\File::exists(public_path('storage/receipt_documents/' . $receipt_document->document_path))) {
            \File::delete(public_path('storage/receipt_documents/' . $receipt_document->document_path));
        }

        $receipt_document->delete();

        return redirect()->back();
    }

    public function detailReceipt($id)
    {

        $data = array();

        $banks = DepositorBank::orderBy('name', 'ASC')->get();
        $cBanks = CompanyBank::all();

        $data['banks'] = $banks;
        $data['cBanks'] = $cBanks;

        $data['receipt'] = Receipt::where('id', $id)->first();

        $data['property'] = CustomerProperty::where('id', $data['receipt']->customer_property_id)
            ->with('inventory', 'customer')
            ->first();

        $result = Receipt::where('customer_property_id', $data['property']->id)
            ->sum('amount');

        $data['balance'] = $data['property']->net_pay - $result;

        $digit = new \NumberFormatter("en", \NumberFormatter::SPELLOUT);

        if ($data['receipt']->tax_paid_by == \App\Receipt::company)
            $data['words'] = $digit->format($data['receipt']->amount + $data['receipt']->tax_amount);
        else
            $data['words'] = $digit->format($data['receipt']->amount);


        activity('View')
            ->log('View Receipt record ' . $data['receipt']->receipt_no);

        return view('receipt.detail-receipt', $data);
    }



    public function detailSurchargeReceipt($id)
    {

        $data = array();

        $banks = DepositorBank::orderBy('name', 'ASC')->get();
        $cBanks = CompanyBank::all();

        $data['banks'] = $banks;
        $data['cBanks'] = $cBanks;

        $data['receipt'] = SurchargeReceipt::where('id', $id)->first();

        $data['property'] = CustomerProperty::where('id', $data['receipt']->customer_property_id)
            ->with('inventory', 'customer')
            ->first();

        $result = SurchargeReceipt::where('customer_property_id', $data['property']->id)
            ->sum('amount');

        $data['balance'] = $data['property']->net_pay - $result;

        $digit = new \NumberFormatter("en", \NumberFormatter::SPELLOUT);

        if ($data['receipt']->tax_paid_by == \App\Receipt::company)
            $data['words'] = $digit->format($data['receipt']->amount + $data['receipt']->tax_amount);
        else
            $data['words'] = $digit->format($data['receipt']->amount);


        activity('View')
            ->log('View Surcharge Receipt record ' . $data['receipt']->receipt_no);

        return view('receipt.detail-surcharge-receipt', $data);
    }



    public function editReceiptForm($id)
    {

        $receipt = Receipt::where('id', $id)->with('customer', 'property')->first();
        // dd($receipt);
        $banks = DepositorBank::all();
        $cBanks = CompanyBank::all();

        $properties = CustomerProperty::where('customer_id', $receipt->customer_id)->get();
        $customers = Customer::where('is_deleted', false)->get();

        $receivedAmount = array();
        $lastDate = array();
        $remainingAmount = array();

        foreach ($properties as $property) {
            $receivedAmount[$property->id] = Receipt::where('customer_property_id', $property->id)->sum('amount');
            $lastDate[$property->id] = Receipt::where('customer_property_id', $property->id)->orderBy('receipt_date', 'desc')->first();
            $remainingAmount[$property->id] = $property->net_pay - $receivedAmount[$property->id];
        }
  //get dealers payable records 

  $dealers = Dealer::where([['is_deleted', false]])->get();

  $dealersRecord = array();
  //rebate history
  foreach ($dealers as $d) {
      $dealersRecord[$d->id]['info'] = $d;
      $transactions = DealerTransaction::where('dealer_id', $d->id)->with('property')->get();
      $availableRebate = array();
      foreach ($transactions as $t) {

          if ($t->property) {
              $rebate = $t->amount - DealerPaidRebate::where([['dealer_id', $d->id], ['property_id', $t->property->id], ['is_deleted', false]])->sum('amount');
              if ($rebate > 0)
                  $availableRebate[$t->id] = $t->property->inventory ? $t->property->inventory->unit_number : '' . ' - ' . $rebate;
          }
      }
      $dealersRecord[$d->id]['rebate'] = $availableRebate;
  }

  $vendor_pos = PurchaseRequest::WithAndWhereHas('receipts', function ($query) {
      $query->where('is_book', '=', false);
      $query->where('receipt_type', '=', true);
  })
      ->get();


        $vendor_pos = PurchaseRequest::WithAndWhereHas('receipts', function ($query) {
            $query->where('is_book', '=', false);
            $query->where('receipt_type', '=', true);
        })
            ->get();
            $unitNumbers = TokenReceipt::where([['is_approved', true], ['is_book', false]])->with('inventory')->select('id', 'unit_id', 'token_amount')->get();

        $vendor_pos = json_decode(json_encode($vendor_pos));
        $merging_properties = MergingProperty::orderBy('id', 'ASC')->get(['id', 'mrf_no']);
        $adjusted_properties = CancelProperty::join('receipts', 'cancel_properties.id', '=', 'receipts.cancel_property_id')
            ->join('unit_adjusts', 'cancel_properties.id', '=', 'unit_adjusts.cancel_property_id')
            ->havingRaw('sum(receipts.amount) > ?', ['unit_adjusts.total_received_amount'])
            ->get(['cancel_properties.*']);

        return view('receipt.edit-receipt', compact('dealersRecord','unitNumbers','vendor_pos','adjusted_properties','merging_properties','receipt', 'banks', 'cBanks', 'customers', 'properties', 'receivedAmount', 'lastDate', 'remainingAmount'));
    }

    public function updateReceipt(Request $request)
    {
        

        $validator = Validator::make($request->all(), [
            'amount' => 'required|regex:/^[0-9]+$/u',
            'receipt_date' => 'required',
            'customer_id' => 'required',
            'customer_property_id' => 'required',
            'payment_method' => 'required',
            'payment_head' => 'required',

            'cheque_number' => 'nullable|regex:/^[a-zA-Z\s0-9]+$/u',
            'receipt_no' => 'required',
        ]);


        if ($validator->fails()) {
            return redirect('/receipt/edit/' . $request->id)
                ->withErrors($validator)
                ->withInput()
                ->with([
                    'message' => 'Invalid Inputs!',
                    'alert-type' => 'error',
                ]);
        }

        $result = $this->receipt->updateReceipt($request);
       
        if (!$result) {
            return redirect('/receipt/edit/' . $request->id)
                ->withInput()
                ->with([
                    'message' => 'Something went wrong!',
                    'alert-type' => 'error',
                ]);
        }

        activity('Update')->log('Edit Receipt info ' . $request->receipt_no);

        if($result->is_approved == 1){
         
        return redirect()
            ->route('statement.detail', ['id' => $request->customer_property_id])
            ->with([
                'message' => 'Payment updated successfully!',
                'alert-type' => 'info'
            ]);
        }
        else{
         return   redirect()
            ->route('receipt.pending')
            ->with([
                'message' => 'Receipt updated successfully!',
                'alert-type' => 'info'
            ]);

        }
    }

    public function deleteReceipt($id)
    {

        $receipt = Receipt::where('id', $id)->first();


        Receipt::where('id', $id)->update(['is_deleted' => true]);



        //////////Update Purchase order Receipt//////////////////////////////////

        if ($receipt->adjustment_type == Receipt::vendor) {
            $purchase_order_recepit = PurchaseOrderReceipt::where('purchase_order_id', $receipt->vendor_purchase_order_id)->first();

            $total_pay_amount = ($purchase_order_recepit->total_pay_amount - $receipt->amount);

            $remaining_po_amount = ($purchase_order_recepit->total_amount - $total_pay_amount);

            $dataArray = ['total_pay_amount' => $total_pay_amount, 'remaining_amount' => $remaining_po_amount, 'is_book' => 0];

            if ($remaining_po_amount < $purchase_order_recepit->total_amount) {
                $dataArray['status'] = 2;
            }

            if ($remaining_po_amount == $purchase_order_recepit->total_amount) {
                $dataArray['status'] = 0;
            }

            PurchaseOrderReceipt::where('purchase_order_id', $receipt->vendor_purchase_order_id)->update($dataArray);
        }



        $amount = Receipt::where([['customer_id', $receipt->customer_id], ['is_deleted', false]])->sum('amount');

        Customer::where('id', $receipt->customer_id)->update(['total_paid_amount' => $amount]);

        CustomerStatement::where('receipt_id', $id)->update(['is_deleted' => true]);


        activity('Delete')->log('Delete Receipt info ' . $receipt->receipt_no);

        return redirect()
            ->back()
            ->with([
                'message' => 'Payment deleted successfully!',
                'alert-type' => 'info'
            ]);
    }




    public function deleteSurchargeReceipt($id)
    {

        $receipt = SurchargeReceipt::where('id', $id)->first();

        SurchargeReceipt::where('id', $id)->update(['is_deleted' => true]);

        //////////Update Purchase order Receipt//////////////////////////////////

        if ($receipt->adjustment_type == Receipt::vendor) {
            $purchase_order_recepit = PurchaseOrderReceipt::where('purchase_order_id', $receipt->vendor_purchase_order_id)->first();

            $total_pay_amount = ($purchase_order_recepit->total_pay_amount - $receipt->amount);

            $remaining_po_amount = ($purchase_order_recepit->total_amount - $total_pay_amount);

            $dataArray = ['total_pay_amount' => $total_pay_amount, 'remaining_amount' => $remaining_po_amount, 'is_book' => 0];

            if ($remaining_po_amount < $purchase_order_recepit->total_amount) {
                $dataArray['status'] = 2;
            }

            if ($remaining_po_amount == $purchase_order_recepit->total_amount) {
                $dataArray['status'] = 0;
            }

            PurchaseOrderReceipt::where('purchase_order_id', $receipt->vendor_purchase_order_id)->update($dataArray);
        }



        $amount = SurchargeReceipt::where([['customer_id', $receipt->customer_id], ['is_deleted', false]])->sum('amount');

        Customer::where('id', $receipt->customer_id)->update(['total_paid_amount' => $amount]);

        CustomerStatement::where('receipt_id', $id)->update(['is_deleted' => true]);


        activity('Delete')->log('Delete Surcharge Receipt info ' . $receipt->receipt_no);

        return redirect()
            ->back()
            ->with([
                'message' => 'Payment deleted successfully!',
                'alert-type' => 'info'
            ]);
    }


    public function updateSchedule(Request $request)
    {

        $plan = InstallmentPlan::where([['unit_type', $request->type], ['unit_size', $request->size], ['status', true]])->first();

        return $plan;
    }



    public function getInformationByUnit(Request $request)
    {
        
        $this->validate($request,[
            'unit_number'=>'required',
            'data_id'=>'required|integer'
             
         
         ]);
     

        $unit['info'] = Inventory::with('size', 'type', 'floor', 'categories')->where('id', $request->unit_number)->first();

        if ($request->data_id == 1) {
           
            // $dealer_rebat = $unit['info']->dealerPackageOpenFileUnit->dealerPackage->package->packageDetail->where('unit_type_id',$unit['info']->unit_type_id)->where('unit_size_id',$unit['info']->unit_size_id);
            $dealer_rebat = $unit['info']->dealerPackageOpenFileUnit->dealerPackage->package;
           
            if ($dealer_rebat->rebate_type == 'cash') {
                $dealer_rebat = $dealer_rebat->packageDetail->where('unit_type_id', $unit['info']->unit_type_id)->where('unit_size_id', $unit['info']->unit_size_id);
                $unit['dealer_rebate'] = $dealer_rebat->pluck('dealer_rebate');
                $unit['dealer_rebate'] = $unit['dealer_rebate'][0];
                $unit['dealer_id'] = $unit['info']->dealerPackageOpenFileUnit->dealer_id;
            }
            else if($dealer_rebat->rebate_type == 'openfile') {
                $dealer_rebat = $dealer_rebat->packageDetail->where('unit_type_id', $unit['info']->unit_type_id)->where('unit_size_id', $unit['info']->unit_size_id);
                $unit['dealer_rebate'] = '0';
                $unit['dealer_id'] = $unit['info']->dealerPackageOpenFileUnit->dealer_id;
              
            }
        }

        $unit['schedule'] = SchedulePlan::first();
        $unit['reg'] = UnitFloorSize::where([['unit_floor_id', $unit['info']->unit_floor_id], ['unit_size_id', $unit['info']->unit_size_id]])->first();

        return $unit;
    }

    public function getInformationByUnitEdit(Request $request)
    {
       
        $cus_property =      CustomerProperty::where('id',$request->customer_property_id)->first();
        $unit['info'] = Inventory::with('size', 'type', 'floor', 'categories', 'customer_property')->where('id', $cus_property->inventory_id)->first();


        $customer_statement =  CustomerStatement::where('customer_property_id', $cus_property->id)->get();

        // to get number of installments
        $installment_payment = $customer_statement->where('payment_head', CustomerStatement::installment);
        $count = 0;
        $remaining_installment_number = $customer_statement->where('payment_head', CustomerStatement::installment)->where('due', '>', 0)->where('inst_track', 0)->where('received', 0);
        $remaining_installment_count = 0;

        foreach ($installment_payment as $installment) {
            if (!str_contains($installment->inst_no, '-b')) {
                $count = $count + 1;
            }
        }
        foreach ($remaining_installment_number as $installment_number) {
            if (!str_contains($installment_number->inst_no, '-b')) {
                $remaining_installment_count = $remaining_installment_count + 1;
            }
        }

        $unit['number_of_installments'] =  $count;
        $unit['number_of_installments_remianing'] = $remaining_installment_count;



        //get schedules amount
        $possession_payment_amount = $customer_statement->where('payment_head', \App\CustomerStatement::possession)->sum('due');
        $down_payment_amount = $customer_statement->where('payment_head', \App\CustomerStatement::down_payment)->sum('due');
        $allotment_payment_amount = $customer_statement->where('payment_head', \App\CustomerStatement::allotment)->sum('due');
        $confirmation_payment_amount = $customer_statement->where('payment_head', \App\CustomerStatement::confirmation)->sum('due');
        $booking_payment_amount = $customer_statement->where('payment_head', \App\CustomerStatement::booking)->sum('due');
       
        $file_processing_payment_amount = $customer_statement->where('payment_head', \App\CustomerStatement::file_processing)->sum('due');
        $registration_payment_amount = $customer_statement->where('payment_head', \App\CustomerStatement::registration)->sum('due');
        $per_installment_amount = $customer_statement->where('payment_head', \App\CustomerStatement::installment)->where('inst_no', 1)->sum('due');
        $total_installment_amount = $customer_statement->where('payment_head', \App\CustomerStatement::installment)->sum('due');
      
      
        $per_special_installment_amount = $customer_statement->where('payment_head', \App\CustomerStatement::installment)->where('inst_track',1)->where('inst_no', 1)->sum('due');
        $total_special_installment_amount = $customer_statement->where('payment_head', \App\CustomerStatement::installment)->where('inst_track',1)->sum('due');
      
        
        $ballon_payment_amount=$customer_statement->where('payment_head', \App\CustomerStatement::ballon)->sum('due');
        $balloting_payment_amount=$customer_statement->where('payment_head', \App\CustomerStatement::balloting)->sum('due');
        
        //find schedules percentage
        $total_amount =  $customer_statement->sum('due');

        $unit['total_amount'] = $total_amount;
        $unit['possession_payment_percentage'] =  $possession_payment_amount /  $total_amount * 100;
        $unit['down_payment_percentage'] = $down_payment_amount  /  $total_amount * 100;
        $unit['allotment_payment_percentage'] =  $allotment_payment_amount  /  $total_amount * 100;
        $unit['confirmation_payment_percentage'] = $confirmation_payment_amount  /  $total_amount * 100;
        $unit['booking_payment_percentage'] = $booking_payment_amount  /  $total_amount * 100;
        
        $unit['file_processing_payment_percentage'] = $file_processing_payment_amount  /  $total_amount * 100;
        $unit['registration_payment_percentage'] = $registration_payment_amount /  $total_amount * 100;
        $unit['per_installment_percentage'] =  $per_installment_amount /  $total_amount * 100;
        $unit['total_installment_percentage'] =  $total_installment_amount /  $total_amount * 100;
        $unit['ballon_payment_percentage'] =  $ballon_payment_amount /  $total_amount * 100;
        $unit['balloting_payment_percentage'] =  $balloting_payment_amount /  $total_amount * 100;
        //find paid and unpaid schedules

        $check_remaining_possession_payment  = $customer_statement->where('payment_head', CustomerStatement::possession)->where('due', '>', 0)->where('received', 0)->sum('due');
        $check_remaining_down_payment  = $customer_statement->where('payment_head', CustomerStatement::down_payment)->where('due', '>', 0)->where('received', 0)->sum('due');
        $check_remaining_allotment_payment  = $customer_statement->where('payment_head', CustomerStatement::allotment)->where('due', '>', 0)->where('received', 0)->sum('due');
        $check_remaining_confirmation_payment  = $customer_statement->where('payment_head', CustomerStatement::confirmation)->where('due', '>', 0)->where('received', 0)->sum('due');
        $check_remaining_booking_payment  = $customer_statement->where('payment_head', CustomerStatement::booking)->where('due', '>', 0)->where('received', 0)->sum('due');
        
        $check_remaining_file_processing_payment  = $customer_statement->where('payment_head', CustomerStatement::file_processing)->where('due', '>', 0)->where('received', 0)->sum('due');
        $check_remaining_registration_payment  = $customer_statement->where('payment_head', CustomerStatement::registration)->where('due', '>', 0)->where('received', 0)->sum('due');
        $check_remaining_per_installment_payment  = $customer_statement->where('payment_head', CustomerStatement::installment)->where('due', '>', 0)->where('received', 0)->sum('due');
        $check_remaining_ballon_payment =$customer_statement->where('payment_head', CustomerStatement::ballon)->where('due', '>', 0)->where('received', 0)->sum('due');
        $check_remaining_balloting_payment =$customer_statement->where('payment_head', CustomerStatement::balloting)->where('due', '>', 0)->where('received', 0)->sum('due');


        $unit['check_possession_payment'] =   $check_remaining_possession_payment;
        $unit['check_down_payment'] = $check_remaining_down_payment;
        $unit['check_allotment_payment'] =   $check_remaining_allotment_payment;
        $unit['check_confirmation_payment'] =  $check_remaining_confirmation_payment;
        $unit['check_booking_payment'] = $check_remaining_booking_payment;
         
        $unit['check_file_processing_payment'] = $check_remaining_file_processing_payment;
        $unit['check_registration_payment'] = $check_remaining_registration_payment;
        $unit['check_per_installment'] = $check_remaining_per_installment_payment;
        $unit['check_ballon_payment'] =    $check_remaining_ballon_payment ;
        $unit['check_balloting_payment'] =     $check_remaining_balloting_payment;




        $unit['possession_payment_amount'] = $possession_payment_amount;
        $unit['down_payment_amount'] = $down_payment_amount;

        $unit['allotment_payment_amount'] =  $allotment_payment_amount;
        $unit['confirmation_payment_amount'] = $confirmation_payment_amount;
        $unit['booking_payment_amount'] = $booking_payment_amount;
        
        $unit['file_processing_payment_amount'] = $file_processing_payment_amount;
        $unit['registration_payment_amount'] = $registration_payment_amount;

        $unit['per_installment_amount'] = $per_installment_amount;
        $unit['total_installment_amount'] = $total_installment_amount;
        
       
        $unit['ballon_payment_amount'] =$ballon_payment_amount;
        $unit['balloting_payment_amount'] =  $balloting_payment_amount;



        $unit['receivedAmt'] = CustomerStatement::where('customer_property_id', $cus_property->id)->sum('received');


        $ballon_payment_date = CustomerStatement::where('customer_property_id', $cus_property->id)->where('payment_head', CustomerStatement::ballon)->where('received', 0)->first();

        $unit['ballon_date'] = ($ballon_payment_date == true) ? $ballon_payment_date->due_date : date('Y-m-d');

        $balloting_payment_date = CustomerStatement::where('customer_property_id', $cus_property->id)->where('payment_head', CustomerStatement::balloting)->where('received', 0)->first();

        $unit['balloting_date'] = ($balloting_payment_date == true) ? $balloting_payment_date->due_date : date('Y-m-d');



        $down_payment_date = CustomerStatement::where('customer_property_id', $cus_property->id)->where('payment_head', CustomerStatement::down_payment)->where('received', 0)->first();

        $unit['down_payment_date'] = ($down_payment_date == true) ? $down_payment_date->due_date : date('Y-m-d');

        $possession_date = CustomerStatement::where('customer_property_id', $cus_property->id)->where('payment_head', CustomerStatement::possession)->where('received', 0)->first();

        $unit['possession_date'] = ($possession_date == true) ? $possession_date->due_date : date('Y-m-d');

        $allotment_date = CustomerStatement::where('customer_property_id', $cus_property->id)->where('payment_head', CustomerStatement::allotment)->where('received', 0)->first();

        $unit['allotment_date'] = ($allotment_date == true) ? $allotment_date->due_date : date('Y-m-d');

        $confirmation_date = CustomerStatement::where('customer_property_id', $cus_property->id)->where('payment_head', CustomerStatement::confirmation)->where('received', 0)->first();

        $unit['confirmation_date'] = ($confirmation_date == true) ? $confirmation_date->due_date : date('Y-m-d');
 

        $file_processing_date = CustomerStatement::where('customer_property_id', $cus_property->id)->where('payment_head', CustomerStatement::file_processing)->where('received', 0)->first();

        $unit['file_processing_date'] = ($file_processing_date == true) ? $file_processing_date->due_date : date('Y-m-d');


        $registration_date = CustomerStatement::where('customer_property_id', $cus_property->id)->where('payment_head', CustomerStatement::registration)->where('received', 0)->first();

        $unit['registration_date'] = ($registration_date == true) ? $registration_date->due_date : date('Y-m-d');


        $unit['schedule'] = SchedulePlan::first();
    

        $unit['reg'] = UnitFloorSize::where([['unit_floor_id', $unit['info']->unit_floor_id], ['unit_size_id', $unit['info']->unit_size_id]])->first();

        return $unit;
    }

    //Allotment Letter
    public function getAllotmentLetter($id)
    {

        $data['property'] = CustomerProperty::where('id', $id)->with('customer', 'inventory')->first();

        return view('statement/letter.allotment', $data);
    }

    //Provisional Letter
    public function getProvisionalLetter($id)
    {

        $data['property'] = CustomerProperty::where('id', $id)->with('customer', 'inventory')->first();

        return view('statement/letter.provisional', $data);
    }

    public function getBookingForm($id)
    {

        $data = array();
        $data['statement'] = CustomerProperty::where('id', $id)->with('inventory', 'customer')->first();

        //update print count
        CustomerProperty::where('id', $id)->update(['print_count_m' => $data['statement']->print_count_m + 1]);

        $data['receivedAmt'] = CustomerStatement::where('customer_property_id', $data['statement']->id)->sum('received');
        $data['receipt'] = Receipt::where([['customer_property_id', $data['statement']->id], ['payment_head', Receipt::down_payment]])->first();

        return view('statement.booking-form', $data);
    }

    public function getAllotmentForm($id)
    {

        $data = array();
        $data['statement'] = CustomerProperty::where('id', $id)->with('inventory', 'customer')->first();

        //update print count
        CustomerProperty::where('id', $id)->update(['print_count_c' => $data['statement']->print_count_c + 1]);

        $data['receivedAmt'] = CustomerStatement::where('customer_property_id', $data['statement']->id)->sum('received');
        $data['receipt'] = Receipt::where([['customer_property_id', $data['statement']->id], ['payment_head', Receipt::down_payment]])->first();

        return view('statement.allotment', $data);
    }

    // public function getSaleAgreementForm($id) {

    //     $data = array();
    //     $data['statement'] = CustomerProperty::where('id',$id)->with('inventory','customer','statement')->first();

    //     $data['receivedAmt'] = CustomerStatement::where('customer_property_id',$data['statement']->id)->sum('received');
    //     $data['receipt'] = Receipt::where([['customer_property_id',$data['statement']->id],['payment_head',Receipt::down_payment]])->first();



    //     $digit = new \NumberFormatter("en", \NumberFormatter::SPELLOUT);
    //     $data['receivedAmtWord']  = $digit->format($data['receivedAmt']);

    //     $data['remainingAmount'] = $data['statement']->net_pay - $data['receivedAmt'];
    //     $data['remainingAmountWord'] = $digit->format($data['remainingAmount']);
    //     $data['netAmountWord'] = $digit->format($data['statement']->net_pay);
    //     $data['down_payment_words'] = $digit->format($data['statement']->down_payment);


    //     return view('statement.sale-agreement',$data);
    // }
    public function getSaleAgreementForm($id)
    {

        $data = array();

        /*MI code starts here*/
        $payment_heads = CustomerStatement::orderBy('payment_head')->where('customer_property_id', $id)->distinct()
            ->pluck('payment_head');



        foreach ($payment_heads as $ph) {

            if ($ph == CustomerStatement::down_payment) {

                $data['payment_heads'][] = CustomerStatement::where('customer_property_id', $id)
                    ->where('payment_head', '=', CustomerStatement::down_payment)
                    ->select('payment_head', 'inst_no', 'due_date', DB::raw('SUM(due) AS due_amount'))
                    ->get();
            }

            if ($ph == CustomerStatement::installment) {

                for ($i = 1; $i <= 16; $i++) {


                    $data['payment_heads'][] = CustomerStatement::where('customer_property_id', $id)->where('payment_head', '=', CustomerStatement::installment)->where(function ($query) use ($i) {
                        return $query->where('inst_no', 'like', $i . '-%')->orWhere('inst_no', '=', $i);
                    })->select('payment_head', 'inst_no', 'due_date', DB::raw('SUM(due) AS due_amount'))
                        ->get();
                }
            }
        }

        /*echo "<pre>";
        print_r($data);
        exit;*/


        $data['customer'] = CustomerProperty::where('id', $id)->with('customer')
            ->first();
        /*MI code ends here*/

        $data['statement'] = CustomerProperty::where('id', $id)->with('inventory', 'customer', 'statement')
            ->first();

        $data['receivedAmt'] = CustomerStatement::where('customer_property_id', $data['statement']->id)
            ->sum('received');

        $data['receipt'] = Receipt::where([['customer_property_id', $data['statement']->id], ['payment_head', Receipt::down_payment]])
            ->first();

        $digit = new \NumberFormatter("en", \NumberFormatter::SPELLOUT);
        $data['receivedAmtWord'] = $digit->format($data['receivedAmt']);

        $data['remainingAmount'] = $data['statement']->net_pay - $data['receivedAmt'];
        $data['remainingAmountWord'] = $digit->format($data['remainingAmount']);
        $data['netAmountWord'] = $digit->format($data['statement']->net_pay);
        $data['down_payment_words'] = $digit->format($data['statement']->down_payment);

        return view('statement.sale-agreement', $data);
    }
    public function getTermConditionForm($id)
    {

        $data = array();
        $data['statement'] = CustomerProperty::where('id', $id)->with('inventory', 'customer')->first();

        $data['receivedAmt'] = CustomerStatement::where('customer_property_id', $data['statement']->id)->sum('received');
        $data['receipt'] = Receipt::where([['customer_property_id', $data['statement']->id], ['payment_head', Receipt::down_payment]])->first();

        return view('statement.term-condition', $data);
    }

    public function downloadForm($id)
    {

        $data = array();


        $data['property'] = CustomerProperty::where('id', $id)->with('inventory', 'customer', 'statement', 'propertyTax')->first();
        $data['amount'] = CustomerStatement::where('customer_property_id', $id)->sum('received');

        $data['receivedAmtPer'] = $data['amount'] * 100 / $data['property']->net_pay;


        $data['overDue'] = CustomerStatement::where('customer_property_id', $id)->whereDate('due_date', '<',  \Carbon\Carbon::today())->sum('balance');



        $pdf = \PDF::loadView('statement.membership-download', $data);

        $name = $data['property']->customer->name . ' - statement';


        activity('Download')->log('Download membership form ' . $name);


        return $pdf->download($name . '-membership.pdf');
    }

    public function printReceipt($id)
    {

        $data = array();
        $data['receipt'] = Receipt::where('id', $id)->first();

        $data['property'] = CustomerProperty::where('id', $data['receipt']->customer_property_id)->with('inventory', 'customer')->first();

        $result = Receipt::where('customer_property_id', $data['property']->id)->sum('amount');

        $data['balance'] = $data['property']->net_pay - $result;

        // $digit = new \NumberFormatter("en", \NumberFormatter::SPELLOUT);
        // $data['words'] = $digit->format($data['receipt']->amount);

        $data['qrimage'] =  \QrCode::format('png')
            ->merge('plugins/images/logoColor.png', 0.5, true)
            ->size(100)
            ->errorCorrection('H')
            ->generate($data['property']->membership_no . ' - ' . $data['receipt']->receipt_no . ' - ' . $data['receipt']->amount);

        $receipt_count = CustomerStatement::where('receipt_id', $id)->count();

        $ins_count = CustomerStatement::where([['customer_property_id', $data['property']->id], ['payment_head', Receipt::installment], ['received', '>', 0]])->count();

        $data['installment_no'] = $this->receipt->getInsNo($data['receipt']->customer_property_id, $id);


        Receipt::where('id', $id)->update(['print_count' => $data['receipt']->print_count + 1]);


        return view('receipt.print-receipt', $data);
    }

    public function downloadReceipt($id)
    {

        $data = array();
        $data['receipt'] = Receipt::where('id', $id)->first();

        $data['property'] = CustomerProperty::where('id', $data['receipt']->customer_property_id)->with('inventory', 'customer')->first();

        $result = Receipt::where('customer_property_id', $data['property']->id)->sum('amount');

        $data['balance'] = $data['property']->net_pay - $result;

        // $digit = new \NumberFormatter("en", \NumberFormatter::SPELLOUT);
        // $data['words'] = $digit->format($data['receipt']->amount);

        $data['qrimage'] =  \QrCode::format('png')
            ->merge('plugins/images/logoColor.png', 0.5, true)
            ->size(100)
            ->errorCorrection('H')
            ->generate($data['property']->membership_no . ' - ' . $data['receipt']->receipt_no . ' - ' . $data['receipt']->amount);

        $receipt_count = CustomerStatement::where('receipt_id', $id)->count();

        $ins_count = CustomerStatement::where([['customer_property_id', $data['property']->id], ['payment_head', Receipt::installment], ['received', '>', 0]])->count();

        $data['installment_no'] = $this->receipt->getInsNo($data['receipt']->customer_property_id, $id);

        Receipt::where('id', $id)->update(['download_count' => $data['receipt']->download_count + 1]);

        $pdf = PDF::loadView('receipt.download-receipt', $data);

        $name = $data['property']->customer->name;


        activity('Download')->log('Download receipt  ' . $name . ' ' . $data['receipt']->receipt_no);

        return $pdf->download($name . '-' . $data['receipt']->receipt_no . '-receipt.pdf');
        //  return view('sale/registration.download-form',$data);
    }




    public function getCookieInfoAndMultiProold($request){
        $data =  array();
        try{
           
          
            if($request->has('multipro_id')){
                
                if($request->multipro_id == 'all'){
                    $data['multipro_id'] =$request->multipro_id;
                }else if(!empty($request->multipro_id)){
                $data['multipro_id'] =  decrypt($request->multipro_id);
                }
            }
            
            
            $project_id = request()->cookie('current_project_id');
           
            $user = Auth::user();
            $data['multi_projects'] = [];
            if (!empty($project_id)) {
                $p_id = decrypt($project_id);
                $multi = MultiProject::where('id', $p_id)->first();
                $multiProjectId = $multi->id;
                if ($multi->name == "Super Admin") {
                    $roles = $user
                        ->roles()
                        ->where('name', 'like', 'admin')
                        ->whereHas('projects', function ($query) use ($multiProjectId) {
                            $query->where('multi_project_id', $multiProjectId);
                        })
                        ->first();
                    if (!empty($roles)) {
                        $data['multi_projects']  = MultiProject::where('name', 'NOT like', 'Super Admin')->get();
                        $data['project'] = $multi->name;
                        $data['role'] = 'admin';
                        $data['project_ids'] =  'all';
                        if(isset( $data['multipro_id'])){
                            $data['project_ids'] = $data['multipro_id'];
                            
                        }
                        $data['status'] = 'success';
                        return  $data;
                        
    
                    } else {
                        $project_ids = $user->roles()
                        ->with(
                        
                        [
                            'projects' => function($query) {
                                // add conditions to the roles query here
                                $query->where('name', 'NOT like', 'Super Admin');
                            },
                            
                        ])
                         // Eager load the related 'projects' models
                        ->get()
                        ->pluck('projects.*.id') // Pluck the 'id' column from the related 'projects' models
                        ->flatten() // Flatten the collection of IDs into a single array
                        ->unique() // Filter out duplicates
                        ->toArray(); // Reset the array keys// Reset the array keys
                         
                        $data['multi_projects'] = MultiProject::whereIn('id',  $project_ids)->where('name', 'NOT like', 'Super Admin')->get();
                        $data['project'] = $multi->name;
                        $data['role'] = 'other';
                        $data['project_ids'] =  $project_ids;
                        if(isset( $data['multipro_id'])){
                            if($data['multipro_id'] != 'all'){
                            $data['project_ids'] = $data['multipro_id'];
                            }
                         
                        }
                        $data['status'] = 'success';
                        return $data;
                    }
                }
                else{
                    $roles = $user
                        ->roles()
                        
                        ->whereHas('projects', function ($query) use ($multiProjectId) {
                            $query->where('multi_project_id', $multiProjectId);
                        })
                        ->first(); 
                    
                        if (!empty($roles)) {
                            $data['multi_projects']  = [];
                            $data['project'] = $multi->name;
                            $data['role'] = 'other';
                            $data['project_ids'] =  $multi->id ;
                            if(isset( $data['multipro_id'])){
                                if($data['multipro_id'] != 'all'){
                                    $data['project_ids'] = $data['multipro_id'];
                                    }
                            }
                            $data['status'] = 'success';
                            return  $data;
                            
        
                        }
                }
            }
            else
            {
                $data['status'] = 'error';
                return  $data; 
            }
        }
        catch(\Exception $e){
            $data['status'] = 'error';
            return  $data;
    
        }
    }
    public function getDueAmtProperties(Request $request)
    {
        $request->merge([
            'multipro_id' =>'all',
             
        ]);
        $data =
        $this->getCookieInfoAndMultiPro($request);
        if($data['status'] == 'error'){
            return redirect()

            ->back()
            ->with([
                'message' => 'Invalid Inputs!',
                'alert-type' => 'error',
            ]);
        }
        $ids=[];
        if(is_array($data['project_ids'])){
            $ids=    $data['project_ids'];
           }
           else
           {
            $ids[]=    $data['project_ids'];
           }

        //current month due amounts
        $data['due'] = $this->statement->getDueAmount(2000,$ids);

        return view('statement.due-properties', $data);
    }

    public function approveAllReceipt()
    {
        $project_ids=   $this->getCookieInfomation();
        if($project_ids['status'] == 'error'){
            return redirect()

            ->back()
            ->with([
                'message' => 'Invalid Inputs!',
                'alert-type' => 'error',
            ]);
        }
        $ids=[];
        if(is_array($project_ids['project_ids'])){
            $ids= $project_ids['project_ids']; 
        }
        else
        $ids[]= $project_ids['project_ids'];


        $receipt = $this->receipt->approvedAllReceipt($ids);

        if (!$receipt) {
            return redirect('/receipt/pendings')
                ->withInput()
                ->with([
                    'message' => 'Something went wrong!',
                    'alert-type' => 'error',
                ]);
        }

        activity('Approved')->log('All Receipt Approved ');

        return redirect()->back()
            ->with([
                'message' => 'Receipt Approved successfully!',
                'alert-type' => 'info'
            ]);
    }


    public function validateReceiptAmount(Request $request)
    {


        $cancel_properties = CustomerProperty::where('status', CustomerProperty::cancel)->pluck('id');

        //  if($request->payment_head !=  Receipt::surcharge) 
        //  {
        //     $token_amount = 0;

        //     $tokenamount = Inventory::where([['id',$request->unit_id],['is_deleted',false]])
        //     ->first();

        //     if ($tokenamount == true) 
        //     {
        //         $token_amount = $tokenamount->token_amount;
        //     }

        //     $customer_statement = CustomerStatement::whereNotIn('customer_property_id' , $cancel_properties)->where([['customer_property_id',$request->property_id],['payment_head',$request->payment_head]]);

        //     $received_amount = $customer_statement->sum('received');

        //     $total_amount_of_head = $customer_statement->sum('due');

        //     $amount = ($received_amount + $request->entered_amount);

        //     $response =  ($total_amount_of_head - $amount );

        //     $value = 0;

        //     if ($response < 0 ) 
        //     {
        //      $value = 1;
        //     }

        //     $remaining = ( $total_amount_of_head - $amount );

        //     $total = $received_amount + ( $total_amount_of_head - $received_amount );
        // }
        // else
        // {
        //   $total_surcharge =   CustomerStatement::whereNotIn('customer_property_id' , $cancel_properties)->where([['customer_property_id',$request->property_id]])->sum('surcharge');

        //   $received =   SurchargeReceipt::whereNotIn('customer_property_id' , $cancel_properties)->where([['customer_property_id',$request->property_id]])->sum('total_surcharge');

        //    $remaining = ( $total_surcharge - $received ) > 0 ? $total_surcharge - $received  : 0;

        // }



        // $payment_head = null;

        // if($request->payment_head ==  Receipt::down_payment)
        // {
        //     $payment_head = 'Down Payment';
        // }
        // elseif($request->payment_head ==  Receipt::possession_fee)
        // {
        //     $payment_head = 'Possession';
        // }
        // elseif($request->payment_head ==  Receipt::installment)
        // {
        //     $payment_head = 'Installment';
        // }

        // elseif($request->payment_head ==  Receipt::allotment)
        // {
        //     $payment_head = 'Allotment';
        // }
        // elseif($request->payment_head ==  Receipt::confirmation)
        // {
        //     $payment_head = 'Confirmation';
        // }

        // elseif($request->payment_head ==  Receipt::booking)
        // {
        //     $payment_head = 'Booking';
        // }

        // elseif($request->payment_head ==  Receipt::development)
        // {
        //     $payment_head = 'Development';
        // }
        // elseif($request->payment_head ==  Receipt::file_processing)
        // {
        //     $payment_head = 'File Processing';
        // }
        // elseif($request->payment_head ==  Receipt::registration)
        // {
        //     $payment_head = 'Registration';
        // }
        // elseif($request->payment_head ==  Receipt::surcharge)
        // {
        //     $payment_head = 'Surcharge';
        // }
        // else
        // {
        //     $payment_head = 'Other';
        // }


        $property_payment_head_name = [];
        $property_payment_head_val = [];
        $payment_heads_for_property = CustomerStatement::whereNotIn('customer_property_id', $cancel_properties)->where('customer_property_id', $request->property_id)->where('due', '!=', 0)->select('payment_head')->distinct()->get();
        
       $customer_property= CustomerProperty::where('id',$request->property_id)->first();

        
        foreach ($payment_heads_for_property as $property_payment_head) {
            if ($property_payment_head->payment_head ==  Receipt::down_payment) {

                if( $customer_property->booking_type == CustomerProperty::full_payment){
                    $property_payment_head_name[] = 'Full Payment';
                }
                else{
                    $property_payment_head_name[] = 'Down Payment';
                }
               
                
                $property_payment_head_val[] = Receipt::down_payment;

            } elseif ($property_payment_head->payment_head ==  Receipt::possession_fee) {
                $property_payment_head_name[] = 'Possession';
                $property_payment_head_val[] = Receipt::possession_fee;
            } elseif ($property_payment_head->payment_head ==  Receipt::installment) {
                $property_payment_head_name[] = 'Installment';
                $property_payment_head_val[] = Receipt::installment;
            } elseif ($property_payment_head->payment_head ==  Receipt::allotment) {
                $property_payment_head_name[] = 'Allotment';
                $property_payment_head_val[] = Receipt::allotment;
            } elseif ($property_payment_head->payment_head ==  Receipt::confirmation) {
                $property_payment_head_name[] = 'Confirmation';
                $property_payment_head_val[] = Receipt::confirmation;
            } elseif ($property_payment_head->payment_head ==  Receipt::booking) {
                $property_payment_head_name[] = 'Booking';
                $property_payment_head_val[] = Receipt::booking;
            } elseif ($property_payment_head->payment_head ==  Receipt::ballon) {
                $property_payment_head_name[] = 'Ballon';
                $property_payment_head_val[] = Receipt::ballon;
            }
            elseif ($property_payment_head->payment_head ==  Receipt::balloting) {
                $property_payment_head_name[] = 'Balloting';
                $property_payment_head_val[] = Receipt::balloting;
            }
            elseif ($property_payment_head->payment_head ==  Receipt::file_processing) {
                $property_payment_head_name[] = 'File Processing';
                $property_payment_head_val[] = Receipt::file_processing;
            } elseif ($property_payment_head->payment_head ==  Receipt::registration) {
                $property_payment_head_name[] = 'Registration';
                $property_payment_head_val[] = Receipt::registration;
            } elseif ($property_payment_head->payment_head ==  Receipt::surcharge) {
                $property_payment_head_name[] = 'Surcharge';
                $property_payment_head_val[] = Receipt::surcharge;
            } else {
                $property_payment_head_name[] = 'Other';
                $property_payment_head_val[] = Receipt::other;
            }
        }

        $property_payment_head = [
            'payment_head_name' =>   $property_payment_head_name,
            'payment_head_val' =>    $property_payment_head_val,

        ];
        echo json_encode(array('array_property_payment_head' => $property_payment_head));
    }
    public function getPaymentHeadAmount(Request $request)
    {

        $request->validate([
            'entered_amount' => ['required', 'numeric'],

        ]);

        $cancel_properties = CustomerProperty::where('status', CustomerProperty::cancel)->pluck('id');

        if ($request->payment_head !=  Receipt::surcharge) {
            $token_amount = 0;

            $tokenamount = Inventory::where([['id', $request->unit_id], ['is_deleted', false]])
                ->first();

            if ($tokenamount == true) {
                $token_amount = $tokenamount->token_amount;
            }

            $customer_statement = CustomerStatement::whereNotIn('customer_property_id', $cancel_properties)->where([['customer_property_id', $request->property_id], ['payment_head', $request->payment_head]]);

            $received_amount = $customer_statement->sum('received');

            $total_amount_of_head = $customer_statement->sum('due');

            $amount = ($received_amount +  $request->entered_amount);

            $response =  ($total_amount_of_head - $amount);

            $value = 0;

            if ($response < 0) {
                $value = 1;
            }

            $remaining = ($total_amount_of_head - $amount);

            $total = $received_amount + ($total_amount_of_head - $received_amount);
        } else {
            $total_surcharge =   CustomerStatement::whereNotIn('customer_property_id', $cancel_properties)->where([['customer_property_id', $request->property_id]])->sum('surcharge');

            $received =   SurchargeReceipt::whereNotIn('customer_property_id', $cancel_properties)->where([['customer_property_id', $request->property_id]])->sum('total_surcharge');

            $remaining = ($total_surcharge - $received) > 0 ? $total_surcharge - $received  : 0;
        }



        $payment_head = null;

        if ($request->payment_head ==  Receipt::down_payment) {
            $payment_head = 'Down Payment';
        } elseif ($request->payment_head ==  Receipt::possession_fee) {
            $payment_head = 'Possession';
        } elseif ($request->payment_head ==  Receipt::installment) {
            $payment_head = 'Installment';
        } elseif ($request->payment_head ==  Receipt::allotment) {
            $payment_head = 'Allotment';
        } elseif ($request->payment_head ==  Receipt::confirmation) {
            $payment_head = 'Confirmation';
        } elseif ($request->payment_head ==  Receipt::booking) {
            $payment_head = 'Booking';
        } elseif ($request->payment_head ==  Receipt::ballon) {
            $payment_head = 'Ballon';
        }
         elseif ($request->payment_head ==  Receipt::balloting) {
                $payment_head = 'Balloting';
         
        } elseif ($request->payment_head ==  Receipt::file_processing) {
            $payment_head = 'File Processing';
        } elseif ($request->payment_head ==  Receipt::registration) {
            $payment_head = 'Registration';
        } elseif ($request->payment_head ==  Receipt::surcharge) {
            $payment_head = 'Surcharge';
        } else {
            $payment_head = 'Other';
        }



        echo json_encode(array('remaining' =>  $remaining, 'payment_head' => $payment_head));
    }

    public function editGetPaymentHeadAmount(Request $request)
    {

        $request->validate([
            'entered_amount' => ['required', 'numeric'],

        ]);
        $receipt = Receipt::where('id', $request->receipt_id)->with('customer', 'property')->first();

        $cancel_properties = CustomerProperty::where('status', CustomerProperty::cancel)->pluck('id');

        if ($request->payment_head !=  Receipt::surcharge) {
            $token_amount = 0;

            $tokenamount = Inventory::where([['id', $request->unit_id], ['is_deleted', false]])
                ->first();

            if ($tokenamount == true) {
                $token_amount = $tokenamount->token_amount;
            }

            $customer_statement = CustomerStatement::whereNotIn('customer_property_id', $cancel_properties)->where([['customer_property_id', $request->property_id], ['payment_head', $request->payment_head]]);

            $received_amount = $customer_statement->sum('received');

            $total_amount_of_head = $customer_statement->sum('due');

            $amount = ($received_amount +  $request->entered_amount);

            $response =  ($total_amount_of_head - $amount);

            $value = 0;

            if ($response < 0) {
                $value = 1;
            }

            $remaining = ($total_amount_of_head - $amount);

            $total = $received_amount + ($total_amount_of_head - $received_amount);
        } else {
            $total_surcharge =   CustomerStatement::whereNotIn('customer_property_id', $cancel_properties)->where([['customer_property_id', $request->property_id]])->sum('surcharge');

            $received =   SurchargeReceipt::whereNotIn('customer_property_id', $cancel_properties)->where([['customer_property_id', $request->property_id]])->sum('total_surcharge');

            $remaining = ($total_surcharge - $received) > 0 ? $total_surcharge - $received  : 0;
        }


        $edit = 0;
        $amount = 0;

        if($receipt->customer_property_id  == $request->property_id && $receipt->payment_head  == $request->payment_head){

            $remaining  =   $remaining - $receipt->amount ;
            $edit = 1;
            $amount =$receipt->amount ;
        }

        $payment_head = null;

        if ($request->payment_head ==  Receipt::down_payment) {
            $payment_head = 'Down Payment';
        } elseif ($request->payment_head ==  Receipt::possession_fee) {
            $payment_head = 'Possession';
        } elseif ($request->payment_head ==  Receipt::installment) {
            $payment_head = 'Installment';
        } elseif ($request->payment_head ==  Receipt::allotment) {
            $payment_head = 'Allotment';
        } elseif ($request->payment_head ==  Receipt::confirmation) {
            $payment_head = 'Confirmation';
        } elseif ($request->payment_head ==  Receipt::booking) {
            $payment_head = 'Booking';
        } elseif ($request->payment_head ==  Receipt::ballon) {
            $payment_head = 'Ballon';
        }
         elseif ($request->payment_head ==  Receipt::balloting) {
                $payment_head = 'Balloting';
         
        } elseif ($request->payment_head ==  Receipt::file_processing) {
            $payment_head = 'File Processing';
        } elseif ($request->payment_head ==  Receipt::registration) {
            $payment_head = 'Registration';
        } elseif ($request->payment_head ==  Receipt::surcharge) {
            $payment_head = 'Surcharge';
        } else {
            $payment_head = 'Other';
        }



        echo json_encode(array('remaining' =>  $remaining, 'payment_head' => $payment_head,'edit'=>$edit,'amount'=>$amount));
    }
    public function getPurchaseOrderPayment(Request $request)
    {
        $purchase_order_id =  $request->input('purchase_order');

        $remainingAmount = 0;

        if ($request) {

            $receipt = PurchaseOrderReceipt::where('purchase_order_id', $purchase_order_id)->first();

            $amount = Receipt::where([['vendor_purchase_order_id', $purchase_order_id], ['is_deleted', false]])->sum('amount');

            if ($receipt == true) {
                $remainingAmount = ($receipt->total_amount - $amount);
            }
        }

        echo json_encode(array('response' =>  $remainingAmount));
    }



    public function getUnitToken(Request $request)
    {
        $unit_id =  $request->input('unit_id');

        $remainingAmount = 0;

        if ($request) {
            $token_amount = Inventory::where([['is_deleted', false], ['status', Inventory::token_hold], ['id', $unit_id]])->first();

            if ($token_amount == true) {
                $remainingAmount = $token_amount->token_amount;
            }
        }

        echo json_encode(array('response' =>  $remainingAmount));
    }





    public function validatePurchaseOrderAmount(Request $request)
    {

        $purchase_order_id =  $request->input('vendor_purchase_order_id');
        $entered_amount =  $request->input('entered_amount');
        $response = 'valid';
        $remaining_amount = PurchaseOrderReceipt::where('purchase_order_id', $purchase_order_id)
            ->first()->total_amount;

        $amount = Receipt::where([['vendor_purchase_order_id', $purchase_order_id], ['is_deleted', false]])->sum('amount');

        if ($entered_amount > $remaining_amount || $entered_amount > ($remaining_amount - $amount)) {
            $response = 'invalid';
        }

        echo json_encode(array('response' =>   $response, 'amount' => 'PO-' . $purchase_order_id . ' is ' . ($remaining_amount - $amount)));
    }


    public function addTokenReceiptForm()
    {


        $unitNumbers = Inventory::where([['is_deleted', false], ['status', Inventory::token_hold]])->select('id', 'unit_number')->orderBy('unit_number', 'asc')->get();

        $banks = DepositorBank::all();
        $cBanks = CompanyBank::all();
        $result = Receipt::where([['receipt_no', '!=', null]])->orderby('receipt_no', 'desc')->first();

        if ($result)
            $receipt_no = ++$result->receipt_no;
        else
            $receipt_no = '50000';

        $accounts = ChartOfAccount::orderBy('number', 'ASC')->get();

        //get dealers payable records

        $dealers = Dealer::where([['is_deleted', false]])->get();

        $dealersRecord = array();
        //rebate history
        foreach ($dealers as $d) {
            $dealersRecord[$d->id]['info'] = $d;
            $transactions = DealerTransaction::where('dealer_id', $d->id)->with('property')->get();
            $availableRebate = array();
            foreach ($transactions as $t) {

                if ($t->property) {
                    $rebate = $t->amount - DealerPaidRebate::where([['dealer_id', $d->id], ['property_id', $t->property->id], ['is_deleted', false]])->sum('amount');
                    if ($rebate > 0)
                        $availableRebate[$t->id] = $t->property->inventory ? $t->property->inventory->unit_number : '' . ' - ' . $rebate;
                }
            }
            $dealersRecord[$d->id]['rebate'] = $availableRebate;
        }

        $vendor_pos = PurchaseRequest::WithAndWhereHas('receipts', function ($query) {
            $query->where('is_book', '=', false);
            $query->where('receipt_type', '=', true);
        })
            ->get();

        $vendor_pos = json_decode(json_encode($vendor_pos));



        return view('tokenReceipt.add-token-receipt', compact('unitNumbers', 'banks', 'cBanks', 'receipt_no', 'accounts', 'dealersRecord', 'vendor_pos'));
    }


    public function updateTokenPropertyForm(Request $request)
    {


        $propertie = Inventory::where([['id', $request->unit_id], ['is_deleted', false]])->first();


        return view('tokenReceipt.update-property', compact('propertie'));
    }

    public function insertTokenReceipt(Request $request)
    {
        //    dd($request->all());

        //   die;

        $messages = [
            'bank_name.required_if' => 'Depositor Bank Name is required',
            'company_account.required_if' => 'Company Account is required',
            'cheque_number.required_if' => 'Cheque Number is required.',
            'drawn_date' => 'Drawn Date is required',
            'dealer_adjustment_unit_id' => 'Dealer Payable Rebates is required',
            'vendor_purchase_order_id' => 'Vendor Bill is required',
        ];

        $validator = Validator::make(
            $request->all(),
            [
                'unit_id' => 'required|unique:token_receipt,unit_id',
                'payment_head' => 'required',
                'token_amount' => 'required|regex:/^[0-9]+$/u',
                'payment_method' => 'required',
                'bank_name' => 'nullable|required_if:payment_method,2,3',
                'company_account' => 'nullable|required_if:payment_method,2,3',
                'drawn_date' => 'nullable|required_if:payment_method,3',
                'cheque_number' => 'nullable|required_if:payment_method,3|regex:/^[a-zA-Z\s0-9]+$/u',
                'dealer_adjustment_unit_id' => 'nullable|required_if:adjustment_type,4',
                'vendor_purchase_order_id' => 'nullable|required_if:adjustment_type,4',
                'receipt_no' => 'required',
                'receipt_date' => 'required',
            ],
            $messages
        );



        if ($validator->fails()) {
            return redirect()->route('token.receipt.addView')
                ->withErrors($validator)->withInput()
                ->with(['message' => 'Invalid Inputs!', 'alert-type' => 'error',]);
        }
        DB::beginTransaction();
        try {
            $token_receipt = TokenReceipt::create([
                'unit_id' => $request->unit_id,
                'payment_head' => $request->payment_head,
                'token_amount' => $request->token_amount,
                'payment_method' => $request->payment_method,
                'bank_name' => $request->bank_name,
                'company_account' => $request->company_account,
                'drawn_date' => $request->drawn_date,
                'instrument_no' => $request->cheque_number,
                'adjustment_type' => $request->adjustment_type,
                'vendor_purchase_order_id' => $request->vendor_purchase_order_id,
                'adjustment_detail' => $request->adjustment_detail,
                'dealer_adjustment_unit_id' => $request->dealer_adjustment_unit_id,
                'receipt_number' => $request->receipt_no,
                'receipt_date' => $request->receipt_date,
                'notes' => $request->notes,
                'is_approved' => $request->is_approved,

            ]);
            DB::commit();
            
            $type =   EmailSmsType::where('name', 'like', 'Add Token Receipt')->first();

            if (!empty($type)) {
                $inventory=       Inventory::where('id', $request->unit_id)->first();
                $detail =   $type->detail->where('content_type', EmailSms::content_type_sms)->first();
                if (!empty($detail)) {

                    if ($detail->status == EmailSms::status_on) {
                        $msg = $detail->content;
                        $message = __($msg, [
                            // 'name' => $customer->name,
                            'receivedamount' =>  $request->token_amount,
                            'unitnumber' => $inventory->unit_number,
                            // 'balance' => $balance,
                            // 'membership' => $property->membership_no

                        ]);
                        $dealer =  Dealer::where('id',$inventory->dealer_id)->first();

                        if(!empty($dealer)){
                        if ($request->notify_sms && $dealer->phone_number) {

                            SmsController::sendSMS("92" . substr($dealer->phone_number, 1), $message);
                        }
                        if ($request->notify_email && $dealer->email) {

                            //   Mail::to($customer->email)->send(new Membership($message));
                            $smtp = SmtpSetting::where('status', 1)->first();
                            $transport = (new \Swift_SmtpTransport($smtp->smtp_host, $smtp->smtp_port))
                                ->setUsername($smtp->smtp_username)
                                ->setPassword($smtp->smtp_password);
                            $mailer = new \Swift_Mailer($transport);
                            $email = (new AddTokenReceiptMail($message))
                                ->subject('Property Approved')
                                ->from($smtp->from_email, $smtp->from_name)
                                ->to($dealer->email)
                                ->view('emails.addtokenreceipt');
                            $email_message = $email->render();
                            $swiftMessage = (new \Swift_Message())
                                ->setSubject('Property Approved')
                                ->setFrom($smtp->from_email, $smtp->from_name)
                                ->setTo($dealer->email)
                                ->setBody($email_message, 'text/html');
                            $response = $mailer->send($swiftMessage);
                            $email_log =  new EmailLog;
                            $email_log->smpt_setting_id = $smtp->id;
                            $email_log->receiver_email = $dealer->email;
                            $email_log->content = $message;
                            $email_log->title = 'Add Token Receipt';
                            $email_log->mailable_class = 'new AddTokenReceiptMail';
                            $email_log->mail_view = 'emails.addtokenreceipt';

                            if ($response) {

                                $email_log->status = 1;
                            } else {
                                $email_log->status = 1;
                            }
                            $email_log->save();
                        }
                    }
                    }
                }

            }
            activity('Insert')->log('Insert Token Receipt');
            return redirect()->route('token.receipt.pending')->with('success', 'Token Receipt Added Successfully!');
        } catch (\Exception $e) {

            DB::rollback();
            //dd($e);
            return redirect()->route('token.receipt.addView')->with('success', 'Something went wrong.');
        }
    }

    public function getTokenReceipts()
    {

        $data = array();

        $data['receipts'] = TokenReceipt::with('inventory')->where('is_approved', 1)->orderBy('id', 'desc')->paginate(25);

        $data['totalAmount'] = TokenReceipt::where([['is_approved', 1]])->count();

        $data['unitNumbers'] = Inventory::where([['status', '!=', Inventory::open]])->select('id', 'unit_number')->orderBy('unit_number', 'asc')->get();

        $data['receiptNo'] = TokenReceipt::where('is_approved', true)->select('id', 'receipt_number')->get();
        // $data['accounts'] = ChartOfAccount::orderBy('number','ASC')->get();

        activity('View')->log('Token Receipt list.');

        return view('tokenReceipt.index', $data);
    }


    public function detailTokenReceipt($id)
    {

        $data = array();



        $banks = DepositorBank::orderBy('name', 'ASC')->get();
        $cBanks = CompanyBank::all();

        $data['banks'] = $banks;
        $data['cBanks'] = $cBanks;



        $data['tokenreceipt'] = TokenReceipt::with('inventory')->where('id', $id)->first();


        activity('View')
            ->log('View Token Receipt record ' . $data['tokenreceipt']->receipt_no);

        return view('tokenReceipt.detail-receipt', $data);
    }

    public function deleteTokenReceipt($id)
    {

        $tokenReceipt = TokenReceipt::where('id', $id)->first();

        $tokenReceipt->delete();

        return redirect()
            ->back()
            ->with([
                'message' => 'Token Receipt deleted successfully!',
                'alert-type' => 'info'
            ]);
    }

    public function getTokenPendingReceipts()
    {

        $data = array();


        $data['receipts'] = TokenReceipt::with('inventory')->where([['is_approved', 0]])->orderBy('id', 'desc')->paginate(25);

        $data['totalAmount'] = Receipt::where([['is_approved', false], ['is_deleted', false]])->count();


        activity('View')->log('Pending Token Receipt List');

        return view('tokenReceipt.pending', $data);
    }




    public function approvedAllTokenReceipt()
    {

        $receipts = TokenReceipt::where('is_approved', 0)->get();

        foreach ($receipts as $receipt) {


            TokenReceipt::where('id', $receipt->id)->update([

                'is_approved' => 1

            ]);
        }

        return redirect()
            ->back()
            ->with([
                'message' => 'All Token Receipt Approved successfully!',
                'alert-type' => 'info'
            ]);
    }



    public function approvedTokenReceipt($id)
    {

        TokenReceipt::where('id', $id)->update(['is_approved' => 1]);

        activity('Approved')->log('Token Receipt Approved ');

        return redirect()
            ->route('token.receipt.pending')
            ->with([
                'message' => 'Token Receipt Approved successfully!',
                'alert-type' => 'info'
            ]);
    }


    public function updateTokenReceiptTable(Request $request)
    {

        $filters = array();

        if ($request->receipt_no)
            $filters['receipt_no'] = $request->receipt_no;
        if ($request->payment_mode)
            $filters['payment_mode'] = $request->payment_mode;


        $data = $this->tokenreceipt->updateTable($filters);

        return view('tokenReceipt.update-table', $data);
    }

    public function getAllRefendToken()
    {

        $data = array();

        $data['receipts'] = TokenReceipt::with('inventory')->where('is_approved', 2)->orderBy('id', 'desc')->paginate(25);

        $data['totalAmount'] = TokenReceipt::where([['is_approved', 1]])->count();

        $data['unitNumbers'] = Inventory::where([['status', '!=', Inventory::open]])->select('id', 'unit_number')->orderBy('unit_number', 'asc')->get();

        $data['receiptNo'] = TokenReceipt::where('is_approved', true)->select('id', 'receipt_number')->get();
        // $data['accounts'] = ChartOfAccount::orderBy('number','ASC')->get();

        activity('View')->log('Token Receipt list.');

        return view('tokenReceipt.refend-token', $data);
    }


    public function getRefendTokenForm()
    {

        $data = array();

        $data['unitNumbers'] = TokenReceipt::with('inventory')->where('is_approved', 1)->orderBy('id', 'desc')->get();

        return view('tokenReceipt.add-refend-token', $data);
    }

    public function refendTokenStatus(Request $request)
    {


        $validator = Validator::make($request->all(), [
            'unit_no' => 'required',
            'status' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect('/refend-token/add')
                ->withErrors($validator)
                ->withInput()
                ->with([
                    'message' => 'Invalid Inputs!',
                    'alert-type' => 'error',
                ]);
        }

        TokenReceipt::where('unit_id', $request->unit_no)->update(['is_approved' => 2]);


        activity('Update')->log('Refund Token Receipt.');


        return redirect()
            ->route('refend.token')
            ->with([
                'message' => 'Refund Token successfully!',
                'alert-type' => 'info'
            ]);
    }


    public function getCustomerTax()
    {
        $data = array();

        $data['receipts'] = TaxReceipt::orderBy('id', 'desc')->get();

        $data['totalAmount'] = TaxReceipt::count();

        activity('View')->log('Customer Tax list.');

        return view('receipt.customer_tax', $data);
    }

    public function updateMergingProperty(Request $request)
    {
        $mer_pro = $request->mer_pro;

        $merging_properties = MergingProperty::where('id', $mer_pro)->orderBy('id', 'ASC')->get();

        $properties = array();
        $mergedAmount = array();

        foreach ($merging_properties as $list) {

            $already_merge_amount =  Receipt::where('merging_property_id', $list->id)->where('is_approved', 1)->where('is_deleted', false)->sum('amount');

            if ($already_merge_amount < $list->merging_assessed_value) {
                $properties[] = $list;
                $mergedAmount[$list->id] = Receipt::where('merging_property_id', $list->id)->where('is_approved', 1)->where('is_deleted', false)->sum('amount');
            }
        }

        return view('receipt.update-merging-property', compact('properties', 'mergedAmount'));
    }


    public function addDevelopmentCharges(){
        $project_ids=   $this->getCookieInfomation();
        if($project_ids['status'] == 'error'){
            return redirect()

            ->back()
            ->with([
                'message' => 'Invalid Inputs!',
                'alert-type' => 'error',
            ]);
        }
       
        $ids=[];
        if(is_array($project_ids['project_ids'])){
            $ids= $project_ids['project_ids']; 
        }
        else
        $ids[]= $project_ids['project_ids'];

        $allStatements = CustomerProperty::with('inventory', 'customer', 'dealer')
        ->orderBy('created_at', 'desc')
        ->where([['is_deleted', false],['status',CustomerProperty::approved],
        ['development_fee',0]])
        ->whereIn('multi_project_id', $ids)
        ->get();
        return view('statement.development-charges.add', compact('allStatements'));

    }

    public function getInformationByInventoryNumber(Request $request)
    {
        $this->validate($request,[
            'unit_number'=>'required',
           
             
         
         ]);

         
        $unit['info'] = Inventory::with(['size', 'type', 'floor', 'categories','property' => function ($query) {
            $query->where('block_date',NULL)
            ->where('cancel_date',NULL);
            
        }])
        
        ->where([['id', $request->unit_number]])->first();

        
        $unit['schedule'] = SchedulePlan::first();
        return $unit;
    }
    public function storeDevelopmentCharges(Request $request,DevelopmentCharges $customer){


        $this->validate($request,[
            'unit_number'=>'required',
           'schedule_type'=>'required|integer',
           'customer_property_id'=>'required|integer'
             
         
         ]);
           if($request->schedule_type == CustomerProperty::inst_custom){
              $this->validate($request, [
                'custom_date.*' => 'required',
                'custom_amount.*' => 'required',
                ]);
            }
            if($request->schedule_type == CustomerProperty::full_payment){
                $this->validate($request, [
                  'development_date' => 'required',
                  'development_charges' => 'required',
                  ]);
              }

           $return_value =   $customer->insertDevelopmentCharges($request);
           
           if($return_value){
            return redirect()
            ->route('development-charges.pending')
            ->with([
                'message' => 'Development Charges Added Succesfully!',
                'alert-type' => 'success'
            ]);
            
           }
           else{
            return redirect()
            ->back()
            ->with([
                'message' => 'SomeThing went wrong!',
                'alert-type' => 'error'
            ]);
           }
          


    }

    public function pendingDevelopmentCharges(){


    //  $data['deve_charges'] =   DevelopmentCharges::with('customer','customerProperty')
    //  ->where('is_approved', 0)->get();
       
    $project_ids=   $this->getCookieInfomation();
    if($project_ids['status'] == 'error'){
        return redirect()

        ->back()
        ->with([
            'message' => 'Invalid Inputs!',
            'alert-type' => 'error',
        ]);
    }
       
    $ids=[];
    if(is_array($project_ids['project_ids'])){
        $ids= $project_ids['project_ids']; 
    }
    else
    $ids[]= $project_ids['project_ids'];
    $data['deve_charges'] = DevelopmentCharges::with(['customer', 'customerProperty' => function ($query) use ($ids) {
        $query->whereIn('multi_project_id', $ids);

    }])
    ->where('is_approved', 0)
    ->get();


     $receivedAmt = array();
     foreach ($data['deve_charges'] as    $statement) {
        $unserilz_data=  unserialize($statement->charges_detail);
            if ($statement->schedule_type == CustomerProperty::full_payment) {
               
                $data['receivedAmt'][$statement->id] = $unserilz_data['due'];
            } elseif ($statement->schedule_type == CustomerProperty::inst_custom) {
                $deve_fee = 0;
                foreach( $unserilz_data['due_date'] as $index => $value) {
                   
                    $deve_fee= $unserilz_data['due'][$index] + $deve_fee;
                }
                $data['receivedAmt'][$statement->id] = $deve_fee;
            }


        //  $data['receivedAmt'][$statement->id] = CustomerStatement::where('customer_property_id', $statement->id)->sum('received');
     }
             
        return view('statement.development-charges.pending', $data);
    }

    public function approvedDevelopmentCharges($id){
        $development_charges = DevelopmentCharges::where('id', $id)->first();

        return view('statement.development-charges.edit-pending', compact('development_charges'));
    }

    public function updateApprovedDevelopmentCharges(Request $request, CustomerProperty $customer){
        $this->validate($request, [
            'id' => 'required',
            'status' => 'required',
            ]);
      
     
        $return_value=    $customer->insertDevelopmentCharges($request);
        if($return_value['status']){
            return redirect()
            ->route('statement.detail',$return_value['id'])
            ->with([
                'message' => 'Development Charges Added Succesfully!',
                'alert-type' => 'success'
            ]);
            
           }
           else{
            return redirect()
            ->back()
            ->with([
                'message' => 'SomeThing went wrong!',
                'alert-type' => 'error'
            ]);
           }
    }
}
