<?php

namespace App\Http\Controllers;

use App\NOC;
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\UnitCategory;
use App\UnitFloor;
use App\InventoryCategory;
use DB;
use App\UnitFloorSize;
use PDF;
use File;
use App\DNFBP;
use App\UnitBlock;
use App\Inventory;
use Illuminate\Support\Facades\Auth;
use App\MultiProject;
use App\TransferPropertyType;

// use App\Traits\MultiProjectCookie;


class NOCController extends Controller
{
    // use MultiProjectCookie;
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $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['multi_projects'])){
            $ids= $project_ids['multi_projects']; 
        }
        else
        $ids[]= $project_ids['multi_projects'];
        $allnocs =
        NOC::whereHas('unitNumber', function($query) use($ids){
            $query->whereIn('multi_project_id', $ids);
                 
        })->orderBy('id', 'desc')->get();

        activity('View')->log('View NOC List');


        return view('/noc.index', compact('allnocs'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $customers = Customer::where('is_deleted', false)->get();
        $transfer_type=    TransferPropertyType::all();

        activity('Add')->log('Add New NOC');

        return view('/noc.add',compact('customers','transfer_type'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $messages = ['customer_id.required_if' => 'Customer Name is required', 'unit_number_id.required_if' => 'Property No is
        required', 'membership_no.required_if' => 'Membership No is required.'];

        $validator = Validator::make($request->all() , [
            'noc_no' => 'required|unique:noc,noc_no',
            'customer_id' => 'required',
            // 'contact_no' => 'required',
            // 'father_name_parent' => 'required',
            // 'cnic' => 'required',
            'unit_number_id' => 'required',
            // 'unit_floor_id' => 'required',
            // 'phase' => 'required',
            'membership_no' => 'required',
            'noc_date' => 'required|date',
            'noc_valid_date' => 'required|date|after_or_equal:noc_date',
            'transfer_type' => 'required',
           
            ],
        $messages);


        if ($validator->fails())
        {
        return redirect()->back() 
        ->withErrors($validator)->withInput()
        ->with(['message' => 'Invalid Inputs!', 'alert-type' => 'error', ]);
        }
    // $request->merge(["noc_date"=>date('Y-m-d',strtotime($request->noc_date))]);
      $noc =  NOC::create($request->all());
     
        if ($noc==true)
        {
            return redirect()->route('noc_req')
            ->with(['message' => ' NOC Created Successfully!', 'alert-type' => 'success', ]);
        }
        else {
            return redirect()->back()
            ->withInput()
            ->with(['message' => 'Invalid Inputs!', 'alert-type' => 'error', ]);
        }
        
        
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\NOC  $nOC
     * @return \Illuminate\Http\Response
     */
    public function show(NOC $nOC)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\NOC  $nOC
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $noc = NOC::where('id', $id)->first();
        //dd($noc->unitNumber->floor, $noc->unitNumber->property->membership_no);
        $customers = Customer::where('is_deleted', false)->get();
        $transfer_type= TransferPropertyType::all();

        activity('Edit')->log('Edit NOC File');

        return view('/noc.edit',compact('customers', 'noc','transfer_type'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\NOC  $nOC
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
      //  dd($request->all());

        $messages = ['customer_id.required_if' => 'Customer Name is required', 'unit_number_id.required_if' => 'Property
        No is
        required', 'membership_no.required_if' => 'Membership No is required.'];

        $validator = Validator::make($request->all() , [
        'id' => 'required', 'noc_no' => 'required',
        'customer_id' => 'required',
        // 'contact_no' => 'required',
        // 'father_name_parent' => 'required',
        // 'cnic' => 'required',
        'unit_number_id' => 'required',
        // 'unit_floor_id' => 'required',
        // 'phase' => 'required',
        'membership_no' => 'required',
        'noc_date' => 'required|date',
        'noc_valid_date' => 'required|date|after_or_equal:noc_date',
        'transfer_type' => 'required',
       
        ],
        $messages);
// dd($request->all());

        if ($validator->fails())
        {
        return redirect()->back()
        ->withErrors($validator)->withInput()
        ->with(['message' => 'Invalid Inputs!', 'alert-type' => 'error', ]);
        }
        // $request->merge(["noc_date"=>date('Y-m-d',strtotime($request->noc_date))]);
        // $noc = NOC::where('id',$request->id)->update($request->all());
  
        $noc = NOC::where('id',$request->id)->first();
         $noc->noc_no = $request->noc_no;
           $noc->customer_id = $request->customer_id;
  $noc->unit_number_id = $request->unit_number_id;
  $noc->status = $request->status;
   $noc->noc_date = $request->noc_date;
   
   $noc->noc_valid_date = $request->noc_valid_date;
   $noc->transfer_type = $request->transfer_type;

    $noc->save();
     if ($noc==true)
        {
        return redirect()->route('noc_req')
        ->with(['message' => ' NOC Updated Successfully!', 'alert-type' => 'success', ]);
        }
        else {
        return redirect()->back()
        ->withInput()
        ->with(['message' => 'Invalid Inputs!', 'alert-type' => 'error', ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\NOC  $nOC
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if(is_numeric($id))
        {
        NOC::where('id',$id)->delete();
        }

        activity('Delete')->log('Delete NOC File');

        return redirect()->route('noc_req')->with(['message' => ' NOC Deleted Successfully!', 'alert-type' =>
        'success', ]);
    }

    public function getCustomerInfo(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['multi_projects'])){
            $ids= $project_ids['multi_projects']; 
        }
        else
        $ids[]= $project_ids['multi_projects'];
        
        // dd($ids);


        $customer= Customer::where('id',$request->customer_id)
        
        ->with(
            ['properties' => 
            function($query) use($ids){
            $query->whereIn('multi_project_id', $ids)
            // ->where();
           ->where('status' ,'!=', Customerproperty::block);
        }])
        ->get();
      
        

       

        
        return $customer;
    }

    public function getUnitInfo(Request $request)
    {

    $unit_detail = Inventory::where('id',$request->unit_number_id)->with('size', 'floor', 'property')->first();
       //check 3 things
      // due amount 
       // fine laga 
       // file block or cancel
      
       $due = CustomerStatement::where('customer_property_id',$unit_detail->property->id)->
       where('balance', '>', 0)
       ->value(\DB::raw("SUM(balance)"));
 
       $installemt_unpaid_overdue = CustomerStatement::where('customer_property_id',$unit_detail->property->id)->where('due_date','<=',date('Y-m-d'))
       ->where('balance', '>', 0)
       ->value(\DB::raw("SUM(balance)"));
       
       $data = [
        'unit_detail' => $unit_detail,
        'due' => $due,
        'over_due' =>  $installemt_unpaid_overdue

       ];
    return  $data;

    }

    public function downloadNoc($id)
    {

  

    $data = array();

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

   

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

        $name = $data['noc']
        ->noc_no . ' - NOC';

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

        return $pdf->download($name . '-noc.pdf');
    //   $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 approvedownloadNOC($id) {
        $data = array();
        $data['noc'] = NOC::where('id', $id)->first();
        $pdf = \PDF::loadView('noc.approve-noc-download', $data);

        $name = $data['noc']
        ->noc_no . ' - NOC';

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

        return $pdf->download($name . '-approve_noc.pdf');
    }
    public  function getCookieInfomation(){
        $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;
    
    }
    }


}
