<?php

namespace App\Http\Controllers;

use App\CancelOpenFile;
use Illuminate\Http\Request;
 use App\CustomerProperty;
use App\CustomerStatement;
use App\CancelProperty;
use App\UnitRefundHistory;
use App\Inventory;
use App\UnitAdjust;
use App\StatementHistory;
use App\DealerTransaction;
use App\PaymentHeadPriority;
use App\Receipt;
use App\DepositorBank;
use App\CompanyBank;
use App\SurchargeReceipt;
use App\CustomerPropertyTax;
use Illuminate\Support\Facades\Auth;
use App\MultiProject;
use App\OpenFileDealerInfo;
use App\SchedulePlan;
use App\UnitSize;
use App\PriceList;

class AdjustUnitController extends Controller
{
    //
    public function index()
    {
        $data = array();
        $project_ids=   $this->getCookieInfomation();
       
        $ids=[];
        if(is_array($project_ids['multi_projects'])){
            $ids= $project_ids['multi_projects']; 
        }
        else
        $ids[]= $project_ids['multi_projects'];


        // Close File Adjust Pending

        $data['allStatements'] = CustomerProperty::whereHas('cancelProperty', function($q)
        {
            $q->where('after_cancellation_status','adjust-pending');
        
        })
        ->whereIn('multi_project_id', $ids)
        ->with('inventory','customer','dealer','cancelProperty')->orderBy('created_at', 'desc')->paginate(25);
      
        $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::whereHas('cancelProperty', function($q)
        {
            $q->where('after_cancellation_status','adjust-pending');
        
        })
        ->whereIn('multi_project_id', $ids)
        ->count();
          // Close File Adjust Pending


        $data['statement_count_pending_refund'] = CustomerProperty::whereHas('cancelProperty', function($q)
        {
            $q->where('after_cancellation_status','adjust-pending');
        
        })
        ->whereIn('multi_project_id', $ids)
        ->count();
    

        //close file adjust
        $data['allStatementsAdjust'] = CustomerProperty::whereHas('cancelProperty',
         function($q)
        {
            $q->where('after_cancellation_status','adjusted');
        
        })
        ->whereIn('multi_project_id', $ids)
        ->with('inventory','customer','dealer','cancelProperty','unitAdjustHistory')
        ->orderBy('created_at', 'desc')->paginate(25);
      
        // $adjusted_properties = CancelProperty::
        // join('receipts', 'cancel_properties.customer_property_id', '=', 'receipts.customer_property_id')
        //     ->
        //     join('unit_adjusts', 'cancel_properties.id', '=', 'unit_adjusts.cancel_property_id')
        //     ->when($ids[0] !== 'all', function ($query) use ($ids) {
        //         $query->whereIn('multi_project_id', $ids);
        //     })
        //     ->havingRaw('sum(receipts.amount) > ?', ['unit_adjusts.total_received_amount'])
        //     ->get(['cancel_properties.*']);







        $data['statement_count_adjusted'] = CustomerProperty::whereHas('cancelProperty', function($q)
        {
            $q->where('after_cancellation_status','adjusted');
        
        })
        ->whereIn('multi_project_id', $ids)
        ->count();
        //end close file adjust  

        //close files decline
        $data['allStatementsdecline'] = CustomerProperty::whereHas('cancelProperty', function($q)
        {
            $q->where('after_cancellation_status','decline');
        
        })
        ->whereIn('multi_project_id', $ids)
        ->with('inventory','customer','dealer','cancelProperty','unitAdjustHistory')->orderBy('created_at', 'desc')->paginate(25);
      
        $data['statement_count_decline'] = CustomerProperty::whereHas('cancelProperty', function($q)
        {
            $q->where('after_cancellation_status','decline');
        
        })
        ->whereIn('multi_project_id', $ids)
        ->count();
         //end close files decline


        


         //Package open file adjust pending

        //  $data['OpenFileDealerInfo_pending_adjust'] = OpenFileDealerInfo::whereHas('cancelOpenFile', function($q)
        //  {
        //      $q->where('after_cancellation_status','adjust-pending');
         
        //  })
        //  ->whereHas('inventory', function ($query) use($ids){
        //      $query->when($ids[0] !== 'all', function ($query) use ($ids) {
        //          $query->whereIn('multi_project_id', $ids);
        //      });
        //  })
         
        //  ->with('inventory', 'dealerPackage', 'dealer', 'cancelOpenFile')
         
        //  ->orderBy('created_at', 'desc')->paginate(25);
       
        //  $data['OpenFileDealerInfopending_adjustcount'] = OpenFileDealerInfo::whereHas('cancelOpenFile', function($q)
        //  {
        //      $q->where('after_cancellation_status','adjust-pending');
         
        //  })
        //  ->whereHas('inventory', function ($query) use($ids){
        //      $query->when($ids[0] !== 'all', function ($query) use ($ids) {
        //          $query->whereIn('multi_project_id', $ids);
        //      });
        //  })
        //  ->count();

     

  //End Package open file adjust pending



      

        activity('View')->log('Adjust Properties list.');


        
        return view('statement.adjust.index',$data);
    }
    public function edit($id) {
    
        $data['allStatements'] = CustomerProperty::with('inventory','customer','dealer','cancelProperty','unitAdjustHistory')
        ->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');
        activity('Edit')->log($data['allStatements']->inventory->unit_number . ' Property Adjust Request.');
        return view('statement.adjust.edit', $data);
       
    }
    public function editPackageFile($id){
        $data['openfileadjust'] = OpenFileDealerInfo::with('inventory', 'dealerPackage', 'dealer', 'cancelOpenFile')
        ->where([['id','=',$id]])->first();
        
        $pricelist = PriceList::where('id', $data['openfileadjust']->dealerPackage->package->pricelist->id)->first();
        $size = UnitSize::where('id',$data['openfileadjust']->inventory->size->id)->first();
        $price = $pricelist->pricedetail->where('unit_size_id', $size->id)->where('unit_type_id', $data['openfileadjust']->inventory->type->id)->first();
        if (!empty($price)) {
            $scheduleplane = SchedulePlan::first();
            $per = $scheduleplane->down_payment;
            $result = $price->total_price * $per / 100;
        }
        $data['result'] = $result;
        activity('Edit')->log('Edit Adjust Package File');
        return view('openfile.adjust.edit', $data);
    }
    public function update(Request $request) {

 

        // 0 => pending
        // 1 => approve
        // 2 => decline
        $this->validate($request,[
            'id'=>'required',
            
            'status'=>'required',
         ]);
        

       
        // dd($request->all());
        $cancel_property_id = $request->id;
        $cancel_property= CancelProperty::where('id',$request->id)->first(); 
        $receivedAmt = CustomerStatement::where([['customer_property_id',$cancel_property->customer_property_id ],['is_deleted',false]])->sum('received');
        if($request->status == UnitAdjust::ADJUST_DECISION_DECLINE){



            CustomerProperty::where('id', $cancel_property->customer_property_id)->update(['status'=>Customerproperty::approved ,  'cancel_date'  => null]);
     
            $customer_property=  CancelProperty::where('customer_property_id', $cancel_property->customer_property_id)->first();
     
             $customer_property->status=0;
           
            $customer_property->save();
             $property = CustomerProperty::find( $cancel_property->customer_property_id);
     
             Inventory::where('id',$property->inventory_id)->update(['status'=>Inventory::sold]);
            $cancel_property->after_cancellation_status = 'decline';
            $cancel_property->save();
             activity('Decline')->log($property->inventory->unit_number . ' Property Cancel Adjust Request.');
             return redirect()->route('property.adjust.view')
             ->with([
                 'message' => 'Adjust Unit updated Successfully!',
                 'alert-type' => 'success',
                    ]);
             
            }



      
        
        
        
        
        $unitadjust =  UnitAdjust::where('customer_id',$cancel_property->customerProperty->customer_id)->where('customer_property_id',$cancel_property->customer_property_id)->first();
        if (empty($unitadjust)) {
            $this->validate($request,[
                'ua_no' => 'required|unique:unit_adjusts,ua_no',
             ]);
            $unitadjust = new UnitAdjust();
        }
       
        $unitadjust->customer_id = $cancel_property->customerProperty->customer->id;
        $unitadjust->customer_property_id =  $cancel_property->customer_property_id;
        $unitadjust->total_received_amount  = $receivedAmt;
      
       

        $owner = CustomerProperty::where('id',  $cancel_property->customer_property_id)->first();
        $unitadjust->cancel_property_id = $cancel_property->id;
        $unitadjust->ua_no = $request->ua_no;
        $unitadjust->save();
        
        //make statement history
        if ($request->status == UnitAdjust::ADJUST_DECISION_APPROVED) {
          
            // dd('1');
            $data = $this->getUnitDetail($owner);
            $unitadjust->unit_detail = $data;
            $unitadjust->save();
            $update_cancel_property= CancelProperty::where('id',$request->id)->first();

            $update_cancel_property->after_cancellation_status = 'adjusted';
            $update_cancel_property->save();
            $property = CustomerProperty::find( $cancel_property->customer_property_id);
     
            Inventory::where('id',$property->inventory_id)->update(['status'=>Inventory::open]);
            $customer_statements=  CustomerStatement::where('customer_property_id', $cancel_property->customer_property_id)->get();
            foreach($customer_statements as $cs){
            StatementHistory::create(['unit_adjust_id'=>$unitadjust->id,"payment_head"=> $cs->payment_head,"inst_no"=> $cs->inst_no,"inst_track"=>$cs->inst_track,"due_date"=>$cs->due_date,"due"=>$cs->due,"received"=>$cs->received,"balance"=>$cs->balance,"rcpt_no"=>$cs->rcpt_no,"ref_no"=>$cs->ref_no,"rcpt_date"=>$cs->rcpt_date,"rcpt_amount"=>$cs->rcpt_amount,"late_days"=>$cs->late_days,"surcharge"=>$cs->surcharge]);  
        } 
        activity('update')->log( $cancel_property->customerProperty->inventory->unit_number. ' Adjust Approval Request.');
        }
      
        return redirect()->route('property.adjust.view')
        ->with([
            'message' => 'Adjust Unit updated Successfully!',
            'alert-type' => 'success',
               ]);
        //end statement history  
    }

    public function updatePackageFile(Request $request) {

        // 0 => pending
        // 1 => approve
        // 2 => decline
        $this->validate($request,[
            'id'=>'required',
            
            'status'=>'required',
         ]);
        

       
        // dd($request->all());
        $cancel_property_id = $request->id;
        $cancel_openfile= CancelOpenFile::where('id',$request->id)->first(); 
        $val=OpenFileDealerInfo::where('id', $cancel_openfile->openfile_dealer_info_id)->first();
       
        if($request->status == UnitAdjust::ADJUST_DECISION_DECLINE){
            $inventory=   Inventory::where('id', $val->invertory_id)->update(['status' => Inventory::sold]);
            $cancel_openfile->after_cancellation_status = 'decline';
            $cancel_openfile->save();
            // CustomerProperty::where('id', $cancel_property->customer_property_id)->update(['status'=>Customerproperty::approved ,  'cancel_date'  => null]);
             activity('Decline')->log($inventory->unit_number . ' Open File Cancel Request.');
             return redirect()->route('property.adjust.view')
             ->with([
                 'message' => 'Adjust Openfile updated Successfully!',
                 'alert-type' => 'success',
                    ]);
             
            } 
        
        $unitadjust =  UnitAdjust::where('customer_id',$cancel_property->customerProperty->customer_id)->where('customer_property_id',$cancel_property->customer_property_id)->first();
        if (empty($unitadjust)) {
            $this->validate($request,[
                'ua_no' => 'required|unique:unit_adjusts,ua_no',
             ]);
            $unitadjust = new UnitAdjust();
        }
       
        $unitadjust->customer_id = $cancel_property->customerProperty->customer->id;
        $unitadjust->customer_property_id =  $cancel_property->customer_property_id;
        $unitadjust->total_received_amount  = $receivedAmt;
      
       

        $owner = CustomerProperty::where('id',  $cancel_property->customer_property_id)->first();
        $unitadjust->cancel_property_id = $cancel_property->id;
        $unitadjust->ua_no = $request->ua_no;
        $unitadjust->save();
        
        //make statement history
        if ($request->status == UnitAdjust::ADJUST_DECISION_APPROVED) {
          
            $data = $this->getUnitDetail($owner);
            $unitadjust->unit_detail = $data;
            $unitadjust->save();
            $update_cancel_property= CancelProperty::where('id',$request->id)->first();

            $update_cancel_property->after_cancellation_status = 'adjusted';
            $update_cancel_property->save();
            $customer_statements=  CustomerStatement::where('customer_property_id', $cancel_property->customer_property_id)->get();
            foreach($customer_statements as $cs){
            StatementHistory::create(['unit_adjust_id'=>$unitadjust->id,"payment_head"=> $cs->payment_head,"inst_no"=> $cs->inst_no,"inst_track"=>$cs->inst_track,"due_date"=>$cs->due_date,"due"=>$cs->due,"received"=>$cs->received,"balance"=>$cs->balance,"rcpt_no"=>$cs->rcpt_no,"ref_no"=>$cs->ref_no,"rcpt_date"=>$cs->rcpt_date,"rcpt_amount"=>$cs->rcpt_amount,"late_days"=>$cs->late_days,"surcharge"=>$cs->surcharge]);  
        } 
        activity('update')->log( $cancel_property->customerProperty->inventory->unit_number. ' Adjust Approval Request.');
        }
      
        return redirect()->route('property.adjust.view')
        ->with([
            'message' => 'Adjust Unit updated Successfully!',
            'alert-type' => 'success',
               ]);
        //end statement history  
    }
    public function getUnitDetail(CustomerProperty $owner)
    {

        $floor_street = '';
        if ($owner->inventory->floor) {
            $floor_street = $owner->inventory->floor->name;
        }
        $block = '';
        if($owner->inventory->floor){
        $block = $owner->inventory->floor->unitBlock ? $owner->inventory->floor->unitBlock->name : '';
        }
       
        $category = '';
        foreach ($owner->inventory->categories as $c) {
            $category =  $category . ' ' . $c->category->name . '' . $c->category->percent;
        }
        $size = $owner->inventory->size ? $owner->inventory->size->name : '';
        $total_price =  $owner->inventory->total_price;
        $net_pay = $owner->net_pay;
        $unit_plot_no = $owner->inventory ? $owner->inventory->unit_number : '';
        $unit_type = $owner->inventory->type->name;
        $area =    $owner->inventory->area;
        $discount = number_format($owner->discount);
        $category_cost = number_format($owner->inventory->extra_amount);
        $booking_type = '';
        if ($owner->booking_type == \App\CustomerProperty::normal) {
            $booking_type = 'Installment';
        } elseif ($owner->booking_type == \App\CustomerProperty::full_payment) {
            $booking_type = 'Full Payment';
        }
        $booking_date = date('d-m-Y', strtotime($owner->original_boooking_date));
        $schedule_start_date = '';
        if ($owner->schedule_start_date) {
            $schedule_start_date = date('d-m-Y', strtotime($owner->schedule_start_date));
        }
        $unit_array = array(
            'floor_street' => $floor_street,
            'unit_plot_no' => $unit_plot_no,
            'block' => $block,
            'unit_type' => $unit_type,
            'category' => $category,
            'area' => $area,
            'size' => $size,
            'discount' => $discount,
            'total_price' => $total_price,
            'category_cost' => $category_cost,
            'net_amt' => $net_pay,
            'booking_type' => $booking_type,
            'booking_date' => $booking_date,
            'schedule_start_date' => $schedule_start_date
        );
        // $out = array_values($unit_array);
        // return json_encode($unit_array);
        return serialize($unit_array);
        // unserialize($data);
    }


    public function detailAdjustStatementHistory($id) {

    
        $unit_adjust= UnitAdjust::where('customer_property_id',$id)->first();
    //     dd($transferproperty->transferhistory);
        $property = CustomerProperty::where('id', $unit_adjust->customer_property_id)->with('inventory','customer','statement','propertyTax')->first();
        $amount = StatementHistory::where('unit_adjust_id',$unit_adjust->id)->sum('received');
      
        $data = unserialize($unit_adjust->unit_detail);
         
        $receivedAmtPer = $amount * 100 /  $data['net_amt'];
        $outstandingAmt = ( $data['net_amt'] - $amount);
        $outstandingAmtPer = $outstandingAmt * 100 / $data['net_amt'];

        $dealers = DealerTransaction::where('product_id',$id)->get();
        $periorities = PaymentHeadPriority::orderby('priority' , 'ASC')->get(['payment_head' , 'priority']);
        $pdc_receipt= Receipt::where('customer_property_id',$unit_adjust->customer_property_id)->where('payment_method',Receipt::cheque)->where('cheaque_status' , Receipt::pending)->sum('amount');
       
        $pdcReceiptPer = $pdc_receipt * 100 /  $data['net_amt'];
        $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', $unit_adjust->customer_property_id)->where('customer_id' , $unit_adjust->customer_id)->where('amount' , 0)->sum('total_surcharge');
        $paidSurcharge = SurchargeReceipt::where('customer_property_id', $unit_adjust->customer_property_id)->where('customer_id' , $unit_adjust->customer_id)->sum('amount');  
        $taxs = CustomerPropertyTax::where('customer_id',$unit_adjust->owner_id)->where('property_id',$unit_adjust->customer_property_id)->get();
       
      

        activity('View')->log('View the Adjust Statement history detail '. $unit_adjust->customerProperty->inventory->unit_number . $unit_adjust->customerProperty->customer->name);
        

        return view('statement.adjust.adjusthistory',compact('taxs','data','unit_adjust','paidSurcharge','waiveOff','property','allotment','provisional','amount','receivedAmtPer','outstandingAmtPer','outstandingAmt','dealers','banks','cBanks','periorities','pdc_receipt','pdcReceiptPer'));
        // return view('customer.transfer-history',compact('taxs','data','transferproperty','paidSurcharge','waiveOff','property','allotment','provisional','amount','receivedAmtPer','outstandingAmtPer','outstandingAmt','dealers','banks','cBanks','periorities','pdc_receipt','pdcReceiptPer'));

    }
    public  function getCookieInfomation(){
        $data = array();
        $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
                    ;
                    return   $data;
                } else {
                    $project_ids = $user->roles()
                        ->with('projects') // 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
                        ->values(); // Reset the array keys
    
                    ;
                    $data['multi_projects'] = MultiProject::whereIn('id',  $project_ids)->where('name', 'NOT like', 'Super Admin')->get()->pluck('id')
                    ->toArray();
                    
                     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;
                        
                        return   $data;
                        
    
                    }
            }
        }
    }
}
