<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use App\Inventory;
use App\UnitCategory;
use App\UnitSize;
use App\UnitFloor;
use App\UnitType;
use App\UnitFloorSize;
use App\Dealer;
use App\GeneralJournalEntry;
use App\AccountClass;
use App\CustomerProperty;
use App\Receipt;
use App\CustomerStatement;
use App\MultiProject;
use DB;
use \Carbon\Carbon;
use App\UnitBlock;
use App\PriceList;
use Illuminate\Support\Facades\Auth;
use App\ProjectType;
use App\Traits\MultiProjectCookie;
use Illuminate\Support\Facades\Gate;


class InventoryController extends Controller
{
    use MultiProjectCookie;
    protected $inventory;

    public function __construct()
    {

        $this->inventory = new Inventory();
    }


    public function allInventories(Request $request)
    {

        try {
            $data =  array();
            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);
                }
            }
            $permissions = $request->permission;

            $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'];
                        }

                        return  $this->getInventory($data, $request);
                    } else {
                        $permission = decrypt($request->permission);
                        $project_ids =       $user->roles()
                            ->whereHas('projects', function ($query) {
                                $query->where('name', 'NOT like', 'Super Admin');
                            })
                            // ->where('name', 'NOT like', '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();

                        // $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

                        $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'];
                            }
                        }
                        return  $this->getInventory($data, $request);
                    }
                } else {

                    // $roles = $user
                    //     ->roles()

                    //     ->whereHas('projects', function ($query) use ($multiProjectId) {
                    //         $query->where('multi_project_id', $multiProjectId);
                    //     })
                    //     ->first(); 

                    $permission = decrypt($request->permission);

                    $roles = $user->roles()
                        ->whereHas('projects', function ($query) use ($multiProjectId) {
                            $query->where('multi_project_id', $multiProjectId);
                        })
                        ->get()
                        ->filter(function ($r) use ($permission) {
                            return $r->hasPermission($permission);
                        })
                        ->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'];
                            }
                        }
                        return  $this->getInventory($data, $request);
                    }
                }
            }
        } catch (\Exception $e) {

            return redirect()

                ->back()
                ->with([
                    'message' => 'Invalid Inputs!',
                    'alert-type' => 'error',
                ]);
        }
    }

    public function getInventory($data, $request)
    {


        $id = [];


        if (is_array($data['project_ids'])) {
            $id =    $data['project_ids'];
        } else {
            $id[] =    $data['project_ids'];
        }

        $data['projecttype'] = request()->cookie('project_type');
        if (!empty($data['projecttype'])) {
            $data['projecttype'] =  decrypt($data['projecttype']);
        }


        $data['allInventories'] =  Inventory::where([['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })
            ->select('inventories.unit_number', 'inventories.id', 'inventories.status', 'inventories.total_price', 'inventories.unit_size_id', 'inventories.multi_project_id')
            ->paginate(25);


        $data['floors'] = UnitFloor::where([['is_deleted', false]])->select('id', 'name')->orderBy('name', 'asc')->get();
        $data['sizes'] = UnitSize::where([['is_deleted', false]])->select('id', 'name')->orderBy('name', 'asc')->get();
        $data['unitNumbers'] = Inventory::where([['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->select('id', 'unit_number')->orderBy('unit_number', 'asc')->get();


        $data['inventoryCount'] = Inventory::where([['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->count();

        //Total Unit Count

        $data['total_units_count'] = Inventory::where('is_deleted', false)->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->count();
        $data['booked_units_count'] = Inventory::where([['is_deleted', false], ['status', Inventory::sold]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->count();
        $data['un_booked_units_count'] = Inventory::where([['is_deleted', false], ['status', '!=', Inventory::sold]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->count();



        $multi_type= $data['project_ids'];
            
        if( $data['project_ids'] != 'all'){
       $v=     MultiProject::where('id',$data['project_ids'])->first();
       $multi_type=$v->project_type_id;
        }
        $data['multiproject_type'] =  $multi_type;
       


        $data['total_units_area'] = 0;
        $data['booked_units_area'] = 0;
        $data['un_booked_units_area'] = 0;
        $data['total_units_area_2'] = 0;
        $data['booked_units_area_2'] = 0;
        $data['un_booked_units_area_2'] = 0;
        if($data['multiproject_type'] != 'all'){
        //Total Area Sum
         
        $result1 = Inventory::where([['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->pluck('unit_size_id')->toArray();
       
        foreach ($result1 as $r1) {
            $unit_size1 = UnitSize::where('id', $r1)->first();

            $data['total_units_area'] += $unit_size1 ? $unit_size1->name : 0;
        }
        $result2 = Inventory::where([['is_deleted', false], ['status', Inventory::sold]])
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereIn('multi_project_id', $id);
            })->pluck('unit_size_id')->toArray();
       
        foreach ($result2 as $r2) {
            $unit_size2 = UnitSize::where('id', $r2)->first();

            $data['booked_units_area'] += $unit_size2 ? $unit_size2->name : 0;
        }
        $result3 = Inventory::where([
            ['is_deleted', false],
            ['status', '!=', Inventory::sold]
        ])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->pluck('unit_size_id')->toArray();
         
     
        foreach ($result3 as $r3) {
            $unit_size3 = UnitSize::where('id', $r3)->first();
            $data['un_booked_units_area'] += $unit_size3 ? $unit_size3->name : 0;
        }
    }
    else if($data['multiproject_type'] == 'all')
    {

        // marla
        $result4 = Inventory::where([['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })
        ->whereHas('multiProject', function ($query) {
            $query->where('project_type_id',ProjectType::society );
        })
        ->pluck('unit_size_id')->toArray();
       
        foreach ($result4 as $r4) {
            $unit_size4 = UnitSize::where('id', $r4)->first();

            $data['total_units_area'] += $unit_size4 ? $unit_size4->name : 0;
        }
        $result5 = Inventory::where([['is_deleted', false], ['status', Inventory::sold]])
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereIn('multi_project_id', $id);
            })
            ->whereHas('multiProject', function ($query) {
                $query->where('project_type_id',ProjectType::society );
            })
            ->pluck('unit_size_id')->toArray();
       
        foreach ($result5 as $r5) {
            $unit_size5 = UnitSize::where('id', $r5)->first();

            $data['booked_units_area'] += $unit_size5 ? $unit_size5->name : 0;
        }
        $result6 = Inventory::where([
            ['is_deleted', false],
            ['status', '!=', Inventory::sold]
        ])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })
        ->whereHas('multiProject', function ($query) {
            $query->where('project_type_id',ProjectType::society );
        })
        ->pluck('unit_size_id')->toArray();
     
        foreach ($result6 as $r6) {
            $unit_size6 = UnitSize::where('id', $r6)->first();
            $data['un_booked_units_area'] += $unit_size6 ? $unit_size6->name : 0;
        }

        //Sqrft

        $result7 = Inventory::where([['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })
        ->whereHas('multiProject', function ($query) {
            $query->where('project_type_id',ProjectType::high_rise );
        })
        ->pluck('unit_size_id')->toArray();
       
        foreach ($result7 as $r7) {
            $unit_size7 = UnitSize::where('id', $r7)->first();

            $data['total_units_area_2'] += $unit_size7 ? $unit_size7->name : 0;
        }
        $result8 = Inventory::where([['is_deleted', false], ['status', Inventory::sold]])
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereIn('multi_project_id', $id);
            })
            ->whereHas('multiProject', function ($query) {
                $query->where('project_type_id',ProjectType::high_rise );
            })
            ->pluck('unit_size_id')->toArray();
       
        foreach ($result8 as $r8) {
            $unit_size8 = UnitSize::where('id', $r8)->first();

            $data['booked_units_area_2'] += $unit_size8 ? $unit_size8->name : 0;
        }
        $result9 = Inventory::where([
            ['is_deleted', false],
            ['status', '!=', Inventory::sold]
        ])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })
        ->whereHas('multiProject', function ($query) {
            $query->where('project_type_id',ProjectType::high_rise );
        })
        ->pluck('unit_size_id')->toArray();
     
        foreach ($result9 as $r9) {
            $unit_size9 = UnitSize::where('id', $r9)->first();
            $data['un_booked_units_area_2'] += $unit_size9 ? $unit_size9->name : 0;
        }

    }
        // end total area sum

        //Total Unit Amount
        $data['total_units_amount'] = Inventory::where('is_deleted', false)->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereIn('multi_project_id', $id);
            })->sum('total_price');
        $data['booked_units_amount'] = Inventory::where([['is_deleted', false], ['status', Inventory::sold]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->sum('total_price');
        $data['un_booked_units_amount'] = Inventory::where([['is_deleted', false], ['status', '!=', Inventory::sold]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->sum('total_price');
        $data['total_cost_booked_units'] = CustomerProperty::where([
            ['is_deleted', false],
            ['status', '!=', CustomerProperty::cancel]
        ])
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereHas('inventory', function ($q) use ($id) {
                    $q->whereIn('multi_project_id', $id);
                });
            })
            ->sum('net_pay');





        activity('View')->log('Inventory list.');

       

        if (isset($data['multipro_id']) && $request->has('multipro_id')) {

       
       
           
            return view('inventory.index-update', $data);
        } else {
       
            
            return view('inventory.index', $data);
        }
    }
    public function refreshDatatable(Request $request)
    {
        $data =  array();
        $id = $request->value;
        $inventoryQuery = Inventory::where('is_deleted', false);
        if ($id !== 'all') {
            $inventoryQuery->whereIn('multi_project_id', $id);
        }
        $id = [];
        if ($data['project'] == 'Super Admin' &&  $data['role'] == 'admin') {
            $id = 'all';
        } else {
            $id[] =    $data['project_ids'];
        }


        $data['allInventories'] =  Inventory::where([['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })
            ->select('inventories.unit_number', 'inventories.id', 'inventories.status', 'inventories.total_price', 'inventories.unit_size_id', 'inventories.multi_project_id')
            ->paginate(25);


        $data['floors'] = UnitFloor::where([['is_deleted', false]])->select('id', 'name')->orderBy('name', 'asc')->get();
        $data['sizes'] = UnitSize::where([['is_deleted', false]])->select('id', 'name')->orderBy('name', 'asc')->get();
        $data['unitNumbers'] = Inventory::where([['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->select('id', 'unit_number')->orderBy('unit_number', 'asc')->get();

        $data['inventoryCount'] = Inventory::where([['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->count();

        //Total Unit Count

        $data['total_units_count'] = Inventory::where('is_deleted', false)->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->count();
        $data['booked_units_count'] = Inventory::where([['is_deleted', false], ['status', Inventory::sold]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->count();
        $data['un_booked_units_count'] = Inventory::where([['is_deleted', false], ['status', '!=', Inventory::sold]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->count();
        //Total Area Sum
        $result = Inventory::where([['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->pluck('unit_size_id')->toArray();
        $data['total_units_area'] = 0;
        foreach ($result as $r) {
            $unit_size = UnitSize::where('id', $r)->first();

            $data['total_units_area'] += $unit_size ? $unit_size->name : 0;
        }
        $result = Inventory::where([['is_deleted', false], ['status', Inventory::sold]])
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereIn('multi_project_id', $id);
            })->pluck('unit_size_id')->toArray();
        $data['booked_units_area'] = 0;
        foreach ($result as $r) {
            $unit_size = UnitSize::where('id', $r)->first();

            $data['booked_units_area'] += $unit_size ? $unit_size->name : 0;
        }
        $result = Inventory::where([
            ['is_deleted', false],
            ['status', '!=', Inventory::sold]
        ])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->pluck('unit_size_id')->toArray();
        $data['un_booked_units_area'] = 0;
        foreach ($result as $r) {
            $unit_size = UnitSize::where('id', $r)->first();
            $data['un_booked_units_area'] += $unit_size ? $unit_size->name : 0;
        }
        //Total Unit Amount
        $data['total_units_amount'] = Inventory::where('is_deleted', false)->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->sum('total_price');
        $data['booked_units_amount'] = Inventory::where([['is_deleted', false], ['status', Inventory::sold]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->sum('total_price');
        $data['un_booked_units_amount'] = Inventory::where([['is_deleted', false], ['status', '!=', Inventory::sold]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->sum('total_price');
        $data['total_cost_booked_units'] = CustomerProperty::where([
            ['is_deleted', false],
            ['status', '!=', CustomerProperty::cancel]
        ])
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereHas('inventory', function ($q) use ($id) {
                    $q->whereIn('multi_project_id', $id);
                });
            })
            ->sum('net_pay');

        activity('View')->log('Inventory list.');
        return response()->json($data);
    }
    public function updateAllInventories(Request $request)
    {

        $data =  array();
        $id = $request->value;
        $inventoryQuery = Inventory::where('is_deleted', false);
        if ($id !== 'all') {
            $inventoryQuery->whereIn('multi_project_id', $id);
        }

        $data['allInventories'] =  Inventory::where([['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })
            ->select('inventories.unit_number', 'inventories.id', 'inventories.status', 'inventories.total_price', 'inventories.unit_size_id', 'inventories.multi_project_id')
            ->get();


        $data['floors'] = UnitFloor::where([['is_deleted', false]])->select('id', 'name')->orderBy('name', 'asc')->get();
        $data['sizes'] = UnitSize::where([['is_deleted', false]])->select('id', 'name')->orderBy('name', 'asc')->get();
        $data['unitNumbers'] = Inventory::where([['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->select('id', 'unit_number')->orderBy('unit_number', 'asc')->get();

        $data['inventoryCount'] = Inventory::where([['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->count();

        //Total Unit Count

        $data['total_units_count'] = Inventory::where('is_deleted', false)->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->count();
        $data['booked_units_count'] = Inventory::where([['is_deleted', false], ['status', Inventory::sold]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->count();
        $data['un_booked_units_count'] = Inventory::where([['is_deleted', false], ['status', '!=', Inventory::sold]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->count();
        //Total Area Sum
        $result = Inventory::where([['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->pluck('unit_size_id')->toArray();
        $data['total_units_area'] = 0;
        foreach ($result as $r) {
            $unit_size = UnitSize::where('id', $r)->first();

            $data['total_units_area'] += $unit_size ? $unit_size->name : 0;
        }
        $result = Inventory::where([['is_deleted', false], ['status', Inventory::sold]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->pluck('unit_size_id')->toArray();
        $data['booked_units_area'] = 0;
        foreach ($result as $r) {
            $unit_size = UnitSize::where('id', $r)->first();

            $data['booked_units_area'] += $unit_size ? $unit_size->name : 0;
        }
        $result = Inventory::where([['is_deleted', false], ['status', '!=', Inventory::sold]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->pluck('unit_size_id')->toArray();
        $data['un_booked_units_area'] = 0;
        foreach ($result as $r) {
            $unit_size = UnitSize::where('id', $r)->first();
            $data['un_booked_units_area'] += $unit_size ? $unit_size->name : 0;
        }
        //Total Unit Amount
        $data['total_units_amount'] = Inventory::where('is_deleted', false)->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->sum('total_price');
        $data['booked_units_amount'] = Inventory::where([['is_deleted', false], ['status', Inventory::sold]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->sum('total_price');
        $data['un_booked_units_amount'] = Inventory::where([['is_deleted', false], ['status', '!=', Inventory::sold]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->sum('total_price');
        $data['total_cost_booked_units'] = CustomerProperty::where([
            ['is_deleted', false],
            ['status', '!=', CustomerProperty::cancel]
        ])
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereHas('inventory', function ($q) use ($id) {
                    $q->whereIn('multi_project_id', $id);
                });
            })
            ->sum('net_pay');
        activity('View')->log('Inventory list.');
        return view('inventory.index-update', $data);
    }

    public function allOpenInventories()
    {

        $data =  array();

        $data['allInventories'] = $this->inventory->getAllOpenInventories();

        $data['floors'] = UnitFloor::where([['is_deleted', false]])->select('id', 'name')->orderBy('name', 'asc')->get();
        $data['sizes'] = UnitSize::where([['is_deleted', false]])->select('id', 'name')->orderBy('name', 'asc')->get();
        $data['unitNumbers'] = Inventory::where([['is_deleted', false]])->select('id', 'unit_number')->orderBy('unit_number', 'asc')->get();

        $data['inventoryCount'] = Inventory::where([['is_deleted', false]])->where('status', Inventory::open)->count();



        //Total Unit Count

        $data['total_units_count'] = Inventory::where('is_deleted', false)->count();
        $data['booked_units_count'] = Inventory::where([['is_deleted', false], ['status', Inventory::sold]])->count();
        $data['un_booked_units_count'] = Inventory::where([['is_deleted', false], ['status', '!=', Inventory::sold]])->count();

        //Total Area Sum

        $result = Inventory::where([['is_deleted', false]])->pluck('unit_size_id')->toArray();
        $data['total_units_area'] = 0;
        foreach ($result as $r) {
            $unit_size = UnitSize::where('id', $r)->first();

            $data['total_units_area'] += $unit_size ? $unit_size->name : 0;
        }


        $result = Inventory::where([['is_deleted', false], ['status', Inventory::sold]])->pluck('unit_size_id')->toArray();
        $data['booked_units_area'] = 0;
        foreach ($result as $r) {
            $unit_size = UnitSize::where('id', $r)->first();

            $data['booked_units_area'] += $unit_size ? $unit_size->name : 0;
        }


        $result = Inventory::where([['is_deleted', false], ['status', '!=', Inventory::sold]])->pluck('unit_size_id')->toArray();
        $data['un_booked_units_area'] = 0;
        foreach ($result as $r) {
            $unit_size = UnitSize::where('id', $r)->first();
            $data['un_booked_units_area'] += $unit_size ? $unit_size->name : 0;
        }


        //Total Unit Amount

        $data['total_units_amount'] = Inventory::where('is_deleted', false)->sum('total_price');
        $data['booked_units_amount'] = Inventory::where([['is_deleted', false], ['status', Inventory::sold]])->sum('total_price');
        $data['un_booked_units_amount'] = Inventory::where([['is_deleted', false], ['status', '!=', Inventory::sold]])->sum('total_price');

        $data['total_cost_booked_units']  = CustomerProperty::where([['is_deleted', false], ['status', '!=', CustomerProperty::cancel]])->sum('net_pay');



        activity('View')->log('Inventory list.');

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

    public function beforeAddInventoryFormAdmin(Request $request){
  if(Gate::allows('isSuperAdmin')) {
    try {
        $data =
            $this->getCookieInfoAndMultiPro($request);
        if ($data['status'] == 'error') {
            return response()->json([
                'success' => false,
                'errors' => "Something went wrong",
            ]);
        }
        $id = [];
        if (is_array($data['project_ids'])) {
            $id =    $data['project_ids'];
        } else {
            $id[] =    $data['project_ids'];
        }


      


        $projecttype = request()->cookie('project_type');
        if (!empty($projecttype)) {
            $projecttype =  decrypt($projecttype);
        }
        $categories = UnitCategory::where([['is_deleted', false]])->orderBy('name', 'asc')->get();
        $sizes = UnitSize::where([['is_deleted', false]])->orderBy('name', 'asc')->get();     
        $blocks = UnitBlock::where([['is_deleted', false]])->get();
        $project_id = request()->cookie('current_project_id');
        $user = Auth::user();
        $multi_projects = $data['multi_projects'];
        
    } catch (\Exception $e) {
        return redirect()

            ->back()
            ->with([
                'message' => 'Something went wrong!',
                'alert-type' => 'error',
            ]);
    }

  

    
       
        $floors = UnitFloor::where([['is_deleted', false]])->where('project_type_id', $projecttype)->get();
        $pricelist = PriceList::where('project_type_id', $projecttype)->get();
        $types = UnitType::where([['is_deleted', false], ['projecttype_id', $projecttype]])->get();
       return view('inventory.before-add-inventory-admin-form', compact('multi_projects', 'categories', 'sizes', 'floors', 'types', 'blocks', 'pricelist', 'projecttype'));
    
    
        }
        else{

            abort(403, 'Unauthorized action.');
            // return redirect()->back()->with([
            //     'message' => 'SomeThing went wrong!',
            //     'alert-type' => 'error',
            // ]);;
        }
    }

    public function addInventoryForm(Request $request)
    {

        // $projecttype =   ProjectType::where('status', true)->first();

        try {
            $data =
                $this->getCookieInfoAndMultiPro($request);
            if ($data['status'] == 'error') {
                return response()->json([
                    'success' => false,
                    'errors' => "Something went wrong",
                ]);
            }
            $id = [];
            if (is_array($data['project_ids'])) {
                $id =    $data['project_ids'];
            } else {
                $id[] =    $data['project_ids'];
            }


          


            $projecttype = request()->cookie('project_type');
            if (!empty($projecttype)) {
                $projecttype =  decrypt($projecttype);
            }
            $categories = UnitCategory::where([['is_deleted', false]])->orderBy('name', 'asc')->get();
            $sizes = UnitSize::where([['is_deleted', false]])->orderBy('name', 'asc')->get();
            // $types = UnitType::where([['is_deleted', false], ['projecttype_id', $projecttype]])->get();
          
            $blocks = UnitBlock::where([['is_deleted', false]])->get();

            // $pricelist = PriceList::where('project_type_id', $projecttype)->get();
            $project_id = request()->cookie('current_project_id');
            $user = Auth::user();
             $multi_projects = $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)) {
            //             $multi_projects = MultiProject::where('name', 'NOT like', 'Super Admin')->get();
            //         } else {
            //             $permission = decrypt($request->permission);
            //             $project_ids =       $user->roles()
            //                 // ->where('name', 'NOT like', 'admin')
            //                 ->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();



            //             $multi_projects = MultiProject::whereIn('id',  $project_ids)->where('name', 'NOT like', 'Super Admin')->get();
            //         }
            //     }
            // }
        } catch (\Exception $e) {
            return redirect()

                ->back()
                ->with([
                    'message' => 'Something went wrong!',
                    'alert-type' => 'error',
                ]);
        }

        if(Gate::allows('isSuperAdmin')) {
 
            $validator = Validator::make($request->all(), [
                'multipro_id' => 'required',
            ]);

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

        if($request->has('multipro_id')) {
                    
           
            $multi_pro=    MultiProject::where('id',$data['multipro_id'])->first();
            $projecttype =  $multi_pro->project_type_id;
           $id= encrypt($multi_pro->id);
            $pricelist = PriceList::where('project_type_id', $projecttype)->get();
            $types = UnitType::where([['is_deleted', false], ['projecttype_id', $projecttype]])->get();
            $floors = UnitFloor::where([['is_deleted', false]])->where('project_type_id', $projecttype)->get();
            return 
            view('inventory.add-inventory', compact('id','multi_projects', 'categories', 'sizes', 'floors', 'types', 'blocks', 'pricelist', 'projecttype'));
            // return view('inventory.add-inventory-update', compact('multi_projects', 'categories', 'sizes', 'floors', 'types', 'blocks', 'pricelist', 'projecttype'));

        } else {
           
            $floors = UnitFloor::where([['is_deleted', false]])->where('project_type_id', $projecttype)->get();
            $pricelist = PriceList::where('project_type_id', $projecttype)->get();
            $types = UnitType::where([['is_deleted', false], ['projecttype_id', $projecttype]])->get();
           return view('inventory.add-inventory', compact('multi_projects', 'categories', 'sizes', 'floors', 'types', 'blocks', 'pricelist', 'projecttype'));
        }

      
    }

    public function getUnitTypeAndPriceList(Request $request)
    {       
        $multi_project =   MultiProject::where('id', $request->id)->first();
        $multi_project->project_type_id;

        $types = UnitType::where([['is_deleted', false], ['projecttype_id', $multi_project->project_type_id]])->get();
        $pricelist = PriceList::where('project_type_id', $multi_project->project_type_id)->get();
    }



    //insert new inventory
    public function insertInventory(Request $request)
    {
        
        try {

            if (empty($request->unit_number)) {
                $request->merge([
                    'unit_number' =>  rand('0000', '9999'),
                ]);
            }
            $validator = Validator::make($request->all(), [
                'type' => 'required',
                'unit_number' => 'unique:inventories,unit_number|required|regex:/^[a-zA-Z0-9\s,-.]+$/u',
                'unit_floor_id' => 'nullable|required_if:type,0',
                'total_price' => 'required|regex:/^[0-9]+$/u',
                'status' => 'required',
                'unit_type_id' => 'required',
                'net_amount' => 'required',
                'price_list_id' => 'required',
                'unit_size' => 'required',
                'multipro_id' => 'required'
            ]);
            
            $pro_id =  $request->cookie('current_project_id');
            if (empty($pro_id)) {
                return redirect()

                    ->back()
                    ->with([
                        'message' => 'Something went wrong!',
                        'alert-type' => 'error',
                    ]);
            }

            $pro_id = decrypt($pro_id);
            $multi_pro = MultiProject::whereRaw("id = IF(name='Super Admin', $pro_id, -1)")->first();
            
            if (!empty($multi_pro)) {
                $validator = Validator::make($request->all(), [
                    'multipro_id' => 'required',
                ]);
                if ($validator->fails()) {
                    return redirect()
                         ->back()
                        ->withErrors($validator)
                        ->withInput()
                        ->with([
                            'message' => 'Invalid Inputs!',
                            'alert-type' => 'error',
                        ]);
                }

                $request->merge(['multipro_id' =>  decrypt($request->multipro_id)]);
            } else {
                $request->merge(['multipro_id' =>  $pro_id]);
            }


            $multi_pro = MultiProject::where('id',  $request->multipro_id)->first();


           
            
          
            if ($multi_pro->project_type_id == ProjectType::society) {
              
                $validator = Validator::make($request->all(), [
                    'type' => 'required',
                    'unit_number' => 'unique:inventories,unit_number|required|regex:/^[a-zA-Z0-9\s,-.]+$/u',
                    'unit_floor_id' => 'nullable|required_if:type,0',
                    'total_price' => 'required|regex:/^[0-9]+$/u',
                    'status' => 'required',
                    'unit_size_id' => 'required',
                    'unit_type_id' => 'required',
                    'net_amount' => 'required',
                    'price_list_id' => 'required',
                    'multipro_id' => 'required'
                ]);
            }

            if ($multi_pro->project_type_id == ProjectType::high_rise) {
               
                $validator = Validator::make($request->all(), [
                    'type' => 'required',
                    'unit_number' => 'unique:inventories,unit_number|required|regex:/^[a-zA-Z0-9\s,-.]+$/u',
                    'unit_floor_id' => 'nullable|required_if:type,0',
                    'total_price' => 'required|regex:/^[0-9]+$/u',
                    'status' => 'required',
                    'unit_size_id' => 'required',
                    'unit_type_id' => 'required',
                    'net_amount' => 'required',
                    'price_list_id' => 'required',
                    'multipro_id' => 'required'
                ]);
            }
            if ($validator->fails()) {
                return redirect()
                ->back()
                    ->withErrors($validator)
                    ->withInput()
                    ->with([
                        'message' => 'Invalid Inputs!',
                        'alert-type' => 'error',
                    ]);
            }



           

            //create new inventory
            $inventory = $this->inventory->addNewInventory($request, $multi_pro->project_type_id);

            activity('Create')->log('New inventory added ' . $inventory->unit_number);


            return redirect()
                ->route('inventory.detail', ['id' => $inventory->id])
                ->with([
                    'message' => 'Inventory created successfully!',
                    'alert-type' => 'info'
                ]);
        } catch (\Exception $e) {
            return redirect()
                  ->back()
                ->withInput()
                ->with([
                    'message' => 'Invalid Inputs!',
                    'alert-type' => 'error',
                ]);
        }
    }

    //inventory detail
    public function detailInventory($id)
    {

        $inventory = Inventory::with('categories', 'size', 'floor', 'type', 'priceList','multiProject')->where('id', $id)->first();

        $projecttype = ProjectType::where('status', true)->first();
        activity('View')->log('See the inventory Detail ' . $inventory->unit_number);

        return view('inventory.detail-inventory', compact('inventory', 'projecttype'));
    }


    //show the edit  Inventory form
    public function editInventoryForm($inventory_id)
    {
         

        // try {
            $data =
                $this->getCookieInfoAndMultiPro();
            if ($data['status'] == 'error') {
                return response()->json([
                    'success' => false,
                    'errors' => "Something went wrong",
                ]);
            }
            $id = [];
            if (is_array($data['project_ids'])) {
                $id =    $data['project_ids'];
            } else {
                $id[] =    $data['project_ids'];
            }


          


            // $projecttype = request()->cookie('project_type');
            // if (!empty($projecttype)) {
            //     $projecttype =  decrypt($projecttype);
            // }
        // $projecttype =   ProjectType::where('status', true)->first();








        $inventory = Inventory::with('floor')->where('id', $inventory_id)->first();
        $projecttype =$inventory->multiProject->type->id;
        // dd($inventory,$id);
        $list_amount = 0;
        if (  $projecttype == ProjectType::high_rise) {
            if (!empty($inventory->priceList)) {
                $list_amount = $inventory->priceList->pricedetail->where('unit_floor_id',  $inventory->unit_floor_id)->where('unit_type_id', $inventory->unit_type_id)->first();
                $list_amount = $list_amount ? $list_amount->per_size_price : 0;
            }
        }
        // dd( $list_amount);
        $categories = UnitCategory::where([['is_deleted', false]])->orderBy('name', 'asc')->get();
        $sizes = UnitSize::where([['is_deleted', false]])->orderBy('name', 'asc')->get();
        $types = UnitType::where([['is_deleted', false]])->get();
        $floors = UnitFloor::where([['is_deleted', false]])->get();
        $blocks = UnitBlock::where([['is_deleted', false]])->get();
        $dealers = Dealer::where([['status', true], ['is_deleted', false]])->get();

        $multi_projects = $data['multi_projects'];
        $selected_categories = array();
        foreach ($inventory->categories as $r) {
            array_push($selected_categories, $r->unit_category_id);
        }

        $pricelist = PriceList::where('project_type_id',   $projecttype)->get();
    // }
        // catch (\Exception $e) {
        //     return redirect()

        //         ->back()
        //         ->with([
        //             'message' => 'Something went wrong!',
        //             'alert-type' => 'error',
        //         ]);
        // }
        //reg_no,projects remove from controller becasue we are not passing it from controller and also not using in view
       
        return view('inventory.edit-inventory', compact('list_amount', 'multi_projects', 'projecttype', 'pricelist', 'inventory', 'categories', 'sizes', 'floors', 'types', 'selected_categories', 'dealers', 'blocks'));
    

}

    //update inventory
    public function updateInventory(Request $request)
    {
       
         
        $validator = Validator::make($request->all(), [
            'type' => 'required',
            'id' => 'required',
            //
            'unit_floor_id' => 'nullable|required_if:type,0',
            'total_price' => 'required|regex:/^[0-9]+$/u',
            'status' => 'required',
            'unit_type_id' => 'required',
            'net_amount' => 'required',
            'price_list_id' => 'required',
            // 'multipro_id' => 'required',
            'unit_size_id' => 'required',
        ]);
       
        if ($validator->fails()) {
            return redirect('/inventory/edit/' . $request->id)
                ->withErrors($validator)
                ->withInput()
                ->with([
                    'message' => 'Invalid Inputs!',
                    'alert-type' => 'error',
                ]);
        }

        $inventory = Inventory::find($request->id);
        $projecttype =    $projecttype =$inventory->multiProject->type->id  ;
        // if ($projecttype == ProjectType::society) {
        //     $validator = Validator::make($request->all(), [

        //     ]);
        // }

        // if ($projecttype->id == ProjectType::high_rise) {
        //     $validator = Validator::make($request->all(), [
        //         // 'size' => 'required',
        //         'unit_size_id' => 'required',
        //     ]);
        // }
      

       

        if (!empty($request->unit_number) && $inventory->unit_number != $request->unit_number) {
            $this->validate($request, [

                'unit_number' => 'unique:inventories,unit_number|required|regex:/^[a-zA-Z0-9\s,-.]+$/u',
            ]);
        } else {
            $request->merge([
                'unit_number' =>  $inventory->unit_number,
            ]);
        }
    //  $multi=   decrypt($request->multipro_id);
        $request->merge([
            'multipro_id' =>     $inventory->multi_project_id,
        ]);

        //update new inventory
        $this->inventory->updateInventory($request, $projecttype);

        // $UnitFloor = UnitFloor::where([['is_deleted',false],['id','=',$request->unit_floor_id]])->first();

        //  if($UnitFloor->name != 'N/A')
        //  {
        //      $inventory->update(['inventory_type' => Inventory::allocated ]);
        //  }



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

        activity('Update')->log('Edit the Inventory info ' . $inv->unit_number);



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

    //delete the specific inventory
    public function deleteInventory($id)
    {

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

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

        activity('Delete')->log('delete the Inventory info ' . $inv->unit_number);



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

    public function getRateByFloor(Request $request)
    {




        // $rate = UnitFloorSize::where([['unit_floor_id',$request->floor],['unit_type_id',$request->type]])->first()->rate;

        $pricelist = PriceList::where('id', $request->pricelist_id)->first();

        if ($request->project_type == ProjectType::society) {
            $size = UnitSize::where('id', $request->size)->first();
            $price = $pricelist->pricedetail->where('unit_size_id', $size->id)->where('unit_type_id', $request->type)->first();
            if (!empty($price)) {
                return $price->total_price;
            }
            return 0;
        } elseif ($request->project_type == ProjectType::high_rise) {

            // $size = UnitSize::where('id',$request->size)->first();
            // $price = $pricelist->pricedetail->where('unit_size_id', $size->id)->where('unit_type_id',$request->type)->first();
            // if (!empty($price)) {
            //     return $price->total_price;
            // }
            // return 0;
            $price = $pricelist->pricedetail->where('unit_type_id', $request->type)->where('unit_floor_id', $request->floor)->first();

            if (!empty($price)) {
                return $price->per_size_price;
            }
            return 0;
        }
        return 0;
        // return $rate * (float)$size->name;

    }

    public function getTypeByFloor(Request $request)
    {




        // $rate = UnitFloorSize::where([['unit_floor_id',$request->floor],['unit_type_id',$request->type]])->first()->rate;

        $pricelist = PriceList::where('id', $request->pricelist_id)->first();

        if ($request->project_type == ProjectType::high_rise) {


            $detail = $pricelist->pricedetail->where('unit_floor_id', $request->floor);

            $name = [];
            $id = [];
            foreach ($detail as  $d) {

                $name[] = $d->unittype->name;
                $id[] = $d->unittype->id;
            }
            $data = [
                'name' => $name,
                'id' => $id
            ];
            return $data;
        }
        return 0;
        // return $rate * (float)$size->name;

    }

    public function getFloorByPricelist(Request $request)
    {




        // $rate = UnitFloorSize::where([['unit_floor_id',$request->floor],['unit_type_id',$request->type]])->first()->rate;

        $pricelist = PriceList::where('id', $request->price_list_id)->first();


        $size = UnitSize::where('id', $request->size)->first();
        $detail = $pricelist->pricedetail;
        $floor_name = [];
        $floor_id = [];
        foreach ($pricelist->pricedetail as $d) {

            $floor_name[] =     $d->unitfloor->name;
            $floor_id[] =  $d->unitfloor->id;
        }



        $data = [
            'name' => $floor_name,
            'id' => $floor_id
        ];
        return $data;
        // return $rate * (float)$size->name;

    }


    public function getNillFloor(Request $request)
    {

        if ($request->type == 1) {

            DB::beginTransaction();

            try {

                $UnitFloor = UnitFloor::where([['is_deleted', false], ['name', '=', 'N/A']])->with('unitFloors')->first();

                $block = UnitBlock::where([['is_deleted', false], ['name', '=', 'N/A']])->first();

                if ($block == false) {
                    $block = UnitBlock::create(['name' => 'N/A']);
                }

                if ($UnitFloor == false) {
                    $UnitFloor =   UnitFloor::create(['name' => 'N/A', 'unit_block_id' => $block->id]);
                }


                if ($UnitFloor == true) {
                    UnitFloor::where([['is_deleted', false], ['name', '=', 'N/A']])->update(['unit_block_id' => $block->id]);
                    DB::commit();
                    echo json_encode(array('output' => $UnitFloor));
                }
            } catch (\Exception $e) {
                DB::rollback();
                return false;
            }
        } else {
            $allUnitFloors = UnitFloor::where([['is_deleted', false], ['name', '!=', 'N/A']])->with('unitFloors')->get();
            echo json_encode(array('output' => $allUnitFloors));
        }
    }


    public function getFloorByUnitNumber(Request $request)
    {

        $floor_id = $request->floor;


        $unitNumbers = Inventory::where([['status', '!=', Inventory::sold], ['is_deleted', false]])
            ->whereHas('floor', function ($query) use ($floor_id) {
                $query->where('id', $floor_id);
            })->orderby('unit_number', 'asc')->select('id', 'unit_number AS name')->get();

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



    public function getFloorByBlock(Request $request)
    {

        $floor = UnitFloor::where('unit_block_id', $request->block)->where('is_deleted', false)->get(['id', 'name']);

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



    public function updateTable(Request $request)
    {

        $data =
            $this->getCookieInfoAndMultiPro($request);
        if ($data['status'] == 'error') {
            return response()->json([
                'success' => false,
                'errors' => "Something went wrong",
            ]);
        }
        $id = [];
        if (is_array($data['project_ids'])) {
            $id =    $data['project_ids'];
        } else {
            $id[] =    $data['project_ids'];
        }

        $filters = array();

        if ($request->unit != 0)
            $filters['unit'] = $request->unit;
        if ($request->floor != 0)
            $filters['floor'] = $request->floor;
        if ($request->size != 0)
            $filters['size'] = $request->size;
        if ($request->status != 0)
            $filters['status'] = $request->status;
        if ($request->inventory_type != '')
            $filters['inventory_type'] = $request->inventory_type;


        $data = $this->inventory->updateTable($filters, $id);

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

    public function inventoryStatusSheet(Request $request)
    {
        try {
            $project_id = request()->cookie('current_project_id');
            $user = Auth::user();
            $data['multi_projects'] = [];
            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);
                }
            }



            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'];
                        }

                        return $this->getInventoryStatus($data);
                    } else {
                        $permission = decrypt($request->permission);
                        $project_ids =       $user->roles()
                            // ->where('name', 'NOT like', 'admin')
                            ->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();

                        $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'];
                            }
                        }
                        return $this->getInventoryStatus($data);
                    }
                } else {

                    $roles = $user
                        ->roles()

                        ->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'] = 'other';
                        $data['project_ids'] =  $multi->id;
                        if (isset($data['multipro_id'])) {
                            if ($data['multipro_id'] != 'all') {
                                $data['project_ids'] = $data['multipro_id'];
                            }
                        }


                        return $this->getInventoryStatus($data);
                    }
                }
            }
        } catch (\Exception $e) {
            return redirect()

                ->back()
                ->with([
                    'message' => 'Invalid Inputs!',
                    'alert-type' => 'error',
                ]);
        }
    }
    public function getInventoryStatus($data)
    {

        $id = [];


        if (is_array($data['project_ids'])) {
            $id =    $data['project_ids'];
        } else {
            $id[] =    $data['project_ids'];
        }


        $data['inventories'] = Inventory::where([['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->with('floor')->orderBy('unit_floor_id', 'asc')->get();

        // $data['openInventoryCount'] = Inventory::where([['status', Inventory::open], ['is_deleted', false]])
        // ->orWhere('status', Inventory::package_open_file)
        // ->when($id[0] !== 'all', function ($query) use ($id) {
        //                $query->whereIn('multi_project_id', $id);
        // })

        // ->get();
        $data['openInventoryCount'] = Inventory::where(function ($query) {
            $query->where([
                ['status', Inventory::open],
                ['is_deleted', false]
            ])
                ->orWhere('status', Inventory::package_open_file);
        })
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereIn('multi_project_id', $id);
            })
            ->count();


        $data['openInventoryAmount'] =  Inventory::where(function ($query) {
            $query->where([
                ['status', Inventory::open],
                ['is_deleted', false]
            ])
                ->orWhere('status', Inventory::package_open_file);
        })
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereIn('multi_project_id', $id);
            })

            ->sum('total_price');

        $data['soldInventoryCount'] = Inventory::where([['status', Inventory::sold], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->count();
        $data['soldInventoryAmount'] = Inventory::where([['status', Inventory::sold], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->sum('total_price');

        $data['tokenHoldInventoryCount'] = Inventory::where([['status', Inventory::token_hold], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->count();
        $data['tokenHoldInventoryAmount'] = Inventory::where([['status', Inventory::token_hold], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->sum('total_price');

        $data['tempHoldInventoryCount'] = Inventory::where([['status', Inventory::temp_hold], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->count();
        $data['tempHoldInventoryAmount'] = Inventory::where([['status', Inventory::temp_hold], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->sum('total_price');

        $data['companyHoldInventoryCount'] = Inventory::where([['status', Inventory::hold_company], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->count();
        $data['companyHoldInventoryAmount'] = Inventory::where([['status', Inventory::hold_company], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->sum('total_price');

        $data['categories'] = UnitCategory::where([['is_deleted', false]])->get();

        //categories icon
        $icons = ['fa-btc', 'fa-usd', 'fa-eur', 'fa-krw', 'fa-viacoin'];

        $i = 0;
        $categoryIcon = array();

        foreach ($data['categories'] as $key =>  $c) {
            $categoryIcon[$c->id] = $icons[rand(0, 3)];
        }

        $data['categoryIcon'] = $categoryIcon;

        $floorSqft = array();
        $floorValue = array();
        $floorSoldPer = array();

        $floors = UnitFloor::where('is_deleted', false)->get();

        foreach ($floors as $f) {
            $result = Inventory::where([['unit_floor_id', $f->id], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereIn('multi_project_id', $id);
            })->pluck('unit_size_id')->toArray();

            $floorSqft[$f->id] = 0;

            foreach ($result as $r) {
                $unit_size = UnitSize::where('id', $r)->first();


                $floorSqft[$f->id] += $unit_size ? $unit_size->name : 0;

                $floorValue[$f->id] = Inventory::where([['multi_project_id', $id], ['unit_floor_id', $f->id], ['is_deleted', false]])->sum('total_price');

                if (Inventory::where([['unit_floor_id', $f->id], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
                    $query->whereIn('multi_project_id', $id);
                })->count() > 0)
                    $floorSoldPer[$f->id] = round((Inventory::where([['unit_floor_id', $f->id], ['status', Inventory::sold], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
                        $query->whereIn('multi_project_id', $id);
                    })->count() / Inventory::where([['unit_floor_id', $f->id], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
                        $query->whereIn('multi_project_id', $id);
                    })->count()) * 100);
                else
                    $floorSoldPer[$f->id] = 0;
            }
        }



        $data['floorSqft'] = $floorSqft;
        $data['floorValue'] = $floorValue;
        $data['floorSoldPer'] = $floorSoldPer;

        $data['projecttype'] = request()->cookie('project_type');
        if (!empty( $data['projecttype'])) {
            $data['projecttype'] =  decrypt( $data['projecttype']);
        }

        if (isset($data['multipro_id'])) {
            $multi_pro=    MultiProject::where('id',$data['multipro_id'])->first();
            $data['projecttype'] =  $multi_pro->project_type_id;

            return view('inventory.status-inventory-update', $data);;
        } else {

            return view('inventory.status-inventory', $data);
        }
    }
    public function updateInventoryStatusSheet(Request $request)
    {


        $id = $request->value;
        $inventoryQuery = Inventory::where('is_deleted', false);
        if ($id !== 'all') {
            $inventoryQuery->whereIn('multi_project_id', $id);
        }



        $data['inventories'] = $inventoryQuery->with('floor')->orderBy('unit_floor_id', 'asc')->get();

        $data['openInventoryCount'] = Inventory::where(function ($query) {
            $query->where([
                ['status', Inventory::open],
                ['is_deleted', false]
            ])
                ->orWhere('status', Inventory::package_open_file);
        })
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereIn('multi_project_id', $id);
            })


            ->count();
        $data['openInventoryAmount'] = Inventory::where(function ($query) {
            $query->where([
                ['status', Inventory::open],
                ['is_deleted', false]
            ])
                ->orWhere('status', Inventory::package_open_file);
        })
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereIn('multi_project_id', $id);
            })

            ->sum('total_price');

        $data['soldInventoryCount'] = Inventory::where([['status', Inventory::sold], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->count();
        $data['soldInventoryAmount'] = Inventory::where([['status', Inventory::sold], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->sum('total_price');

        $data['tokenHoldInventoryCount'] = Inventory::where([['status', Inventory::token_hold], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->count();
        $data['tokenHoldInventoryAmount'] = Inventory::where([['status', Inventory::token_hold], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->sum('total_price');

        $data['tempHoldInventoryCount'] = Inventory::where([['status', Inventory::temp_hold], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->count();
        $data['tempHoldInventoryAmount'] = Inventory::where([['status', Inventory::temp_hold], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->sum('total_price');

        $data['companyHoldInventoryCount'] = Inventory::where([['status', Inventory::hold_company], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->count();
        $data['companyHoldInventoryAmount'] = Inventory::where([['status', Inventory::hold_company], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->sum('total_price');

        $data['categories'] = UnitCategory::where([['is_deleted', false]])->get();

        //categories icon
        $icons = ['fa-btc', 'fa-usd', 'fa-eur', 'fa-krw', 'fa-viacoin'];

        $i = 0;
        $categoryIcon = array();

        foreach ($data['categories'] as $key =>  $c) {
            $categoryIcon[$c->id] = $icons[rand(0, 3)];
        }

        $data['categoryIcon'] = $categoryIcon;

        $floorSqft = array();
        $floorValue = array();
        $floorSoldPer = array();

        $floors = UnitFloor::where('is_deleted', false)->get();

        foreach ($floors as $f) {
            $result = Inventory::where([['unit_floor_id', $f->id], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereIn('multi_project_id', $id);
            })->pluck('unit_size_id')->toArray();

            $floorSqft[$f->id] = 0;

            foreach ($result as $r) {
                $unit_size = UnitSize::where('id', $r)->first();


                $floorSqft[$f->id] += $unit_size ? $unit_size->name : 0;

                $floorValue[$f->id] = Inventory::where([['multi_project_id', $id], ['unit_floor_id', $f->id], ['is_deleted', false]])->sum('total_price');

                if (Inventory::where([['unit_floor_id', $f->id], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
                    $query->whereIn('multi_project_id', $id);
                })->count() > 0)
                    $floorSoldPer[$f->id] = round((Inventory::where([['unit_floor_id', $f->id], ['status', Inventory::sold], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
                        $query->whereIn('multi_project_id', $id);
                    })->count() / Inventory::where([['unit_floor_id', $f->id], ['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
                        $query->whereIn('multi_project_id', $id);
                    })->count()) * 100);
                else
                    $floorSoldPer[$f->id] = 0;
            }
        }



        $data['floorSqft'] = $floorSqft;
        $data['floorValue'] = $floorValue;
        $data['floorSoldPer'] = $floorSoldPer;


        return view('inventory.status-inventory-update', $data);
    }
    public function getInventoryInfo(Request $request)
    {

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

        return view('inventory.update-inventory-info-modal', $data);
    }
    public function getSalesDashboard(Request $request)
    {




        // $id = 'all';

        // if ($request->has('multipro_id')) {

        //     $id = $request->multipro_id;
        // }
        $data =
            $this->getCookieInfoAndMultiPro($request);
        if ($data['status'] == 'error') {
            return response()->json([
                'success' => false,
                'errors' => "Something went wrong",
            ]);
        }
        $id = [];
        if (is_array($data['project_ids'])) {
            $id =    $data['project_ids'];
        } else {
            $id[] =    $data['project_ids'];
        }



        $cancel_properties = CustomerProperty::where('status', CustomerProperty::cancel)
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereHas('inventory', function ($q) use ($id) {
                    $q->whereIn('multi_project_id', $id);
                });
            })
            ->pluck('id');

        //Total Unit Count

        $data['total_units_count'] = Inventory::where('is_deleted', false)
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereIn('multi_project_id', $id);
            })
            ->count();
        $data['booked_units_count'] = Inventory::where([['is_deleted', false], ['status', Inventory::sold]])
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereIn('multi_project_id', $id);
            })
            ->count();
        $data['un_booked_units_count'] = Inventory::where([['is_deleted', false], ['status', '!=', Inventory::sold]])
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereIn('multi_project_id', $id);
            })
            ->count();

        //Total Area Sum

        // $result = Inventory::where([['is_deleted', false]])
        //     ->when($id[0] !== 'all', function ($query) use ($id) {
        //         $query->whereIn('multi_project_id', $id);
        //     })
        //     ->pluck('unit_size_id')->toArray();
        // $data['total_units_area'] = 0;
        // foreach ($result as $r) {
        //     $unit_size = UnitSize::where('id', $r)->first();

        //     $data['total_units_area'] += $unit_size ? $unit_size->name : 0;
        // }


        // $result = Inventory::where([['is_deleted', false], ['status', Inventory::sold]])
        //     ->when($id[0] !== 'all', function ($query) use ($id) {
        //         $query->whereIn('multi_project_id', $id);
        //     })
        //     ->pluck('unit_size_id')->toArray();
        // $data['booked_units_area'] = 0;
        // foreach ($result as $r) {
        //     $unit_size = UnitSize::where('id', $r)->first();

        //     $data['booked_units_area'] += $unit_size ? $unit_size->name : 0;
        // }


        // $result = Inventory::where([['is_deleted', false], ['status', '!=', Inventory::sold]])
        //     ->when($id[0] !== 'all', function ($query) use ($id) {
        //         $query->whereIn('multi_project_id', $id);
        //     })
        //     ->pluck('unit_size_id')->toArray();
        // $data['un_booked_units_area'] = 0;
        // foreach ($result as $r) {
        //     $unit_size = UnitSize::where('id', $r)->first();
        //     $data['un_booked_units_area'] += $unit_size ? $unit_size->name : 0;
        // }
        $multi_type= $data['project_ids'];
            
        if( $data['project_ids'] != 'all'){
       $v=     MultiProject::where('id',$data['project_ids'])->first();
       $multi_type=$v->project_type_id;
        }
        $data['multiproject_type'] =  $multi_type;
       


        $data['total_units_area'] = 0;
        $data['booked_units_area'] = 0;
        $data['un_booked_units_area'] = 0;
        $data['total_units_area_2'] = 0;
        $data['booked_units_area_2'] = 0;
        $data['un_booked_units_area_2'] = 0;
        if($data['multiproject_type'] != 'all'){
        //Total Area Sum
         
        $result1 = Inventory::where([['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->pluck('unit_size_id')->toArray();
       
        foreach ($result1 as $r1) {
            $unit_size1 = UnitSize::where('id', $r1)->first();

            $data['total_units_area'] += $unit_size1 ? $unit_size1->name : 0;
        }
        $result2 = Inventory::where([['is_deleted', false], ['status', Inventory::sold]])
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereIn('multi_project_id', $id);
            })->pluck('unit_size_id')->toArray();
       
        foreach ($result2 as $r2) {
            $unit_size2 = UnitSize::where('id', $r2)->first();

            $data['booked_units_area'] += $unit_size2 ? $unit_size2->name : 0;
        }
        $result3 = Inventory::where([
            ['is_deleted', false],
            ['status', '!=', Inventory::sold]
        ])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->pluck('unit_size_id')->toArray();
         
     
        foreach ($result3 as $r3) {
            $unit_size3 = UnitSize::where('id', $r3)->first();
            $data['un_booked_units_area'] += $unit_size3 ? $unit_size3->name : 0;
        }
        }
        else if($data['multiproject_type'] == 'all')
        {

        // marla
        $result4 = Inventory::where([['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })
        ->whereHas('multiProject', function ($query) {
            $query->where('project_type_id',ProjectType::society );
        })
        ->pluck('unit_size_id')->toArray();
       
        foreach ($result4 as $r4) {
            $unit_size4 = UnitSize::where('id', $r4)->first();

            $data['total_units_area'] += $unit_size4 ? $unit_size4->name : 0;
        }
        $result5 = Inventory::where([['is_deleted', false], ['status', Inventory::sold]])
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereIn('multi_project_id', $id);
            })
            ->whereHas('multiProject', function ($query) {
                $query->where('project_type_id',ProjectType::society );
            })
            ->pluck('unit_size_id')->toArray();
       
        foreach ($result5 as $r5) {
            $unit_size5 = UnitSize::where('id', $r5)->first();

            $data['booked_units_area'] += $unit_size5 ? $unit_size5->name : 0;
        }
        $result6 = Inventory::where([
            ['is_deleted', false],
            ['status', '!=', Inventory::sold]
        ])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })
        ->whereHas('multiProject', function ($query) {
            $query->where('project_type_id',ProjectType::society );
        })
        ->pluck('unit_size_id')->toArray();
     
        foreach ($result6 as $r6) {
            $unit_size6 = UnitSize::where('id', $r6)->first();
            $data['un_booked_units_area'] += $unit_size6 ? $unit_size6->name : 0;
        }

        //Sqrft

        $result7 = Inventory::where([['is_deleted', false]])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })
        ->whereHas('multiProject', function ($query) {
            $query->where('project_type_id',ProjectType::high_rise );
        })
        ->pluck('unit_size_id')->toArray();
       
        foreach ($result7 as $r7) {
            $unit_size7 = UnitSize::where('id', $r7)->first();

            $data['total_units_area_2'] += $unit_size7 ? $unit_size7->name : 0;
        }
        $result8 = Inventory::where([['is_deleted', false], ['status', Inventory::sold]])
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereIn('multi_project_id', $id);
            })
            ->whereHas('multiProject', function ($query) {
                $query->where('project_type_id',ProjectType::high_rise );
            })
            ->pluck('unit_size_id')->toArray();
       
        foreach ($result8 as $r8) {
            $unit_size8 = UnitSize::where('id', $r8)->first();

            $data['booked_units_area_2'] += $unit_size8 ? $unit_size8->name : 0;
        }
        $result9 = Inventory::where([
            ['is_deleted', false],
            ['status', '!=', Inventory::sold]
        ])->when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })
        ->whereHas('multiProject', function ($query) {
            $query->where('project_type_id',ProjectType::high_rise );
        })
        ->pluck('unit_size_id')->toArray();
     
        foreach ($result9 as $r9) {
            $unit_size9 = UnitSize::where('id', $r9)->first();
            $data['un_booked_units_area_2'] += $unit_size9 ? $unit_size9->name : 0;
        }

        }
        // end total area sum
        //Total Unit Amount

        $data['total_units_amount'] = Inventory::where('is_deleted', false)
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereIn('multi_project_id', $id);
            })
            ->sum('total_price');
        $data['booked_units_amount'] = Inventory::where([['is_deleted', false], ['status', Inventory::sold]])
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereIn('multi_project_id', $id);
            })
            ->sum('total_price');
        $data['un_booked_units_amount'] = Inventory::where([['is_deleted', false], ['status', '!=', Inventory::sold]])
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereIn('multi_project_id', $id);
            })
            ->sum('total_price');

        $month_stats = array();

        //RECOVERIES & RECEIVABLE STATS

        $data['total_cost_booked_units']  = CustomerProperty::where([['is_deleted', false], ['status', '!=', CustomerProperty::cancel]])
            ->when($id[0] !== 'all', function ($query) use ($id) {
                $query->whereHas('inventory', function ($q) use ($id) {
                    $q->whereIn('multi_project_id', $id);
                });
            })
            ->sum('net_pay');
        $data['total_collection'] =  Receipt::whereNotIn('customer_property_id', $cancel_properties)->where('is_approved', 1)->where('is_deleted', false)->sum('amount');

        $data['overdues'] = CustomerStatement::whereNotIn('customer_property_id', $cancel_properties)->where('due_date', '<', \Carbon\Carbon::now())->sum('balance');

        //Breakup of receivables againts defaulter aged.

        $data['fully_paid_units_count'] = CustomerStatement::when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->havingRaw('sum(balance) = 0')->groupBy('customer_property_id')->count();
        $data['fully_paid_units_amount'] = CustomerStatement::when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->havingRaw('sum(balance) = 0')->groupBy('customer_property_id')->sum('received');

        $data['no_overdue_count'] = CustomerStatement::when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->where('due_date', '<', \Carbon\Carbon::now())->havingRaw('sum(balance) = 0')->groupBy('customer_property_id')->count();
        $data['no_overdue_amount'] = CustomerStatement::when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->where('due_date', '<', \Carbon\Carbon::now())->havingRaw('sum(balance) = 0')->groupBy('customer_property_id')->sum('received');
        $ids = CustomerStatement::when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->where('due_date', '<', \Carbon\Carbon::now())->havingRaw('sum(balance) = 0')->groupBy('customer_property_id')->pluck('customer_property_id')->toArray();
        if (count($ids) > 0) {
            $data['no_overdue_receivable'] = CustomerProperty::whereIn('id', $ids)->sum('net_pay') - $data['no_overdue_amount'];
            $data['no_overdue_receivable_per'] = round(($data['no_overdue_receivable'] / ($data['total_cost_booked_units'] - $data['total_collection'])) * 100);
        } else {
            $data['no_overdue_receivable'] = 0;
            $data['no_overdue_receivable_per'] = 0;
        }



        $data['f_month_overdue_count'] = CustomerStatement::when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->where([['balance', '>', 0]])->whereBetween('due_date', [Carbon::today()->subDay(30), Carbon::today()])->groupBy('customer_property_id')->count();

        $data['f_month_overdue_amount'] = CustomerStatement::when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->where([['balance', '>', 0]])->whereBetween('due_date', [Carbon::today()->subDay(30), Carbon::today()])->groupBy('customer_property_id')->sum('received');

        $data['f_month_overdue_balance'] = CustomerStatement::when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->where([['balance', '>', 0]])->whereBetween('due_date', [Carbon::today()->subDay(30), Carbon::today()])->groupBy('customer_property_id')->sum('balance');

        $ids = CustomerStatement::when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->where([['balance', '>', 0]])->whereBetween('due_date', [Carbon::today()->subDay(30), Carbon::today()])->groupBy('customer_property_id')->pluck('customer_property_id')->toArray();

        if (count($ids) > 0) {
            $data['f_month_overdue_receivable'] = CustomerProperty::whereIn('id', $ids)->sum('net_pay') - $data['f_month_overdue_amount'];
            $data['f_month_overdue_receivable_per'] = round(($data['f_month_overdue_receivable'] / ($data['total_cost_booked_units'] - $data['total_collection'])) * 100);
        } else {
            $data['f_month_overdue_receivable'] = 0;
            $data['f_month_overdue_receivable_per'] = 0;
        }

        $data['s_month_overdue_count'] = CustomerStatement::when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->where([['balance', '>', 0]])->whereBetween('due_date', [Carbon::today()->subDay(60), Carbon::today()])->groupBy('customer_property_id')->count();
        $data['s_month_overdue_amount'] = CustomerStatement::when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->where([['balance', '>', 0]])->whereBetween('due_date', [Carbon::today()->subDay(60), Carbon::today()])->groupBy('customer_property_id')->sum('received');

        $data['s_month_overdue_balance'] = CustomerStatement::when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->where([['balance', '>', 0]])->whereBetween('due_date', [Carbon::today()->subDay(30), Carbon::today()])->groupBy('customer_property_id')->sum('balance');

        $ids = CustomerStatement::when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->where([['balance', '>', 0]])->whereBetween('due_date', [Carbon::today()->subDay(60), Carbon::today()])->groupBy('customer_property_id')->pluck('customer_property_id')->toArray();
        if (count($ids) > 0) {
            $data['s_month_overdue_receivable'] = CustomerProperty::whereIn('id', $ids)->sum('net_pay') - $data['s_month_overdue_amount'];
            $data['s_month_overdue_receivable_per'] = round(($data['s_month_overdue_receivable'] / ($data['total_cost_booked_units'] - $data['total_collection'])) * 100);
        } else {
            $data['s_month_overdue_receivable'] = 0;
            $data['s_month_overdue_receivable_per'] = 0;
        }

        $data['t_month_overdue_count'] = CustomerStatement::when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->where([['balance', '>', 0]])->whereBetween('due_date', [Carbon::today()->subDay(90), Carbon::today()])->groupBy('customer_property_id')->count();
        $data['t_month_overdue_amount'] = CustomerStatement::when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->where([['balance', '>', 0]])->whereBetween('due_date', [Carbon::today()->subDay(90), Carbon::today()])->groupBy('customer_property_id')->sum('received');

        $data['t_month_overdue_balance'] = CustomerStatement::when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->where([['balance', '>', 0]])->whereBetween('due_date', [Carbon::today()->subDay(90), Carbon::today()])->groupBy('customer_property_id')->sum('balance');

        $ids = CustomerStatement::when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->where([['balance', '>', 0]])->whereBetween('due_date', [Carbon::today()->subDay(90), Carbon::today()])->groupBy('customer_property_id')->pluck('customer_property_id')->toArray();
        if (count($ids) > 0) {
            $data['t_month_overdue_receivable'] = CustomerProperty::whereIn('id', $ids)->sum('net_pay') - $data['t_month_overdue_amount'];
            $data['t_month_overdue_receivable_per'] = round(($data['t_month_overdue_receivable'] / ($data['total_cost_booked_units'] - $data['total_collection'])) * 100);
        } else {
            $data['t_month_overdue_receivable'] = 0;
            $data['t_month_overdue_receivable_per'] = 0;
        }

        $data['fo_month_overdue_count'] = CustomerStatement::when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->where([['balance', '>', 0]])->where('due_date', '<', Carbon::today()->subDay(90))->groupBy('customer_property_id')->count();
        $data['fo_month_overdue_amount'] = CustomerStatement::when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->where([['balance', '>', 0]])->where('due_date', '<', Carbon::today()->subDay(90))->groupBy('customer_property_id')->sum('received');

        $data['fo_month_overdue_balance'] = CustomerStatement::when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->where([['balance', '>', 0]])->where('due_date', '<', Carbon::today()->subDay(90))->groupBy('customer_property_id')->sum('balance');

        $ids = CustomerStatement::when($id[0] !== 'all', function ($query) use ($id) {
            $query->whereIn('multi_project_id', $id);
        })->where([['balance', '>', 0]])->where('due_date', '<', Carbon::today()->subDay(90))->groupBy('customer_property_id')->pluck('customer_property_id')->toArray();
        if (count($ids) > 0) {
            $data['fo_month_overdue_receivable'] = CustomerProperty::whereIn('id', $ids)->sum('net_pay') - $data['fo_month_overdue_amount'];
            $data['fo_month_overdue_receivable_per'] = round(($data['fo_month_overdue_receivable'] / ($data['total_cost_booked_units'] - $data['total_collection'])) * 100);
        } else {
            $data['fo_month_overdue_receivable'] = 0;
            $data['fo_month_overdue_receivable_per'] = 0;
        }
        // $data['multi_projects'] = MultiProject::all();

        if ($request->has('multipro_id')) {
            //  dd($data);
            return view('inventory.dashboard-update', $data);
        } else {

            return view('inventory.dashboard', $data);
        }
    }
    public function getSalesDetailDashboard(Request $request)
    {


        // $id = 'all';

        // if ($request->has('multipro_id')) {

        //     $id = $request->multipro_id;
        // }
        $data =
            $this->getCookieInfoAndMultiPro($request);
        if ($data['status'] == 'error') {
            return redirect()

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


        $allFloors = UnitFloor::all();

        $floor_data = array();

        foreach ($allFloors as $f) {
            $temp['name'] = $f->name;
            $temp['project_type'] = $f->project_type_id; 
            $temp['block'] = $f->unitBlock ? $f->unitBlock->name : 'None';

            if (!empty($request->type)) {
                $temp['type'] = json_decode(json_encode($f->unitFloors));
            }

            $temp['total_units'] = Inventory::where([['is_deleted', false], ['unit_floor_id', $f->id]])
                ->when($id[0] !== 'all', function ($query) use ($id) {
                    $query->whereIn('multi_project_id', $id);
                })
                ->count();
            $temp['booked_units'] = Inventory::where([['is_deleted', false], ['unit_floor_id', $f->id], ['status', Inventory::sold]])
                ->when($id[0] !== 'all', function ($query) use ($id) {
                    $query->whereIn('multi_project_id', $id);
                })->count();
            $temp['un_booked_units'] = $temp['total_units'] - $temp['booked_units'];

            $result = Inventory::where([['is_deleted', false], ['unit_floor_id', $f->id]])
                ->when($id[0] !== 'all', function ($query) use ($id) {
                    $query->whereIn('multi_project_id', $id);
                })
                ->pluck('unit_size_id')->toArray();
            $temp['total_units_area'] = 0;
            foreach ($result as $r) {
                $obj = UnitSize::where('id', $r)->first();
                if (!empty($obj)) {

                    $temp['total_units_area'] += $obj->name;
                }
            }


            $result = Inventory::where([['is_deleted', false], ['status', '!=', Inventory::sold], ['unit_floor_id', $f->id]])
                ->when($id[0] !== 'all', function ($query) use ($id) {
                    $query->whereIn('multi_project_id', $id);
                })
                ->pluck('unit_size_id')->toArray();
            $temp['un_booked_units_area'] = 0;
            foreach ($result as $r)
                $temp['un_booked_units_area'] += UnitSize::where('id', $r)->first() ? UnitSize::where('id', $r)->first()->name : 0;

            $floor_id = $f->id;
            $temp['booked_units_area'] = $temp['total_units_area'] - $temp['un_booked_units_area'];

            $temp['total_units_amount'] = Inventory::where([['is_deleted', false], ['unit_floor_id', $f->id], ['status', '=', Inventory::sold]])
                ->when($id[0] !== 'all', function ($query) use ($id) {
                    $query->whereIn('multi_project_id', $id);
                })
                ->sum('total_price');

            $temp['booked_units_amount'] = CustomerProperty::where('is_deleted', false)->where('status', '!=', CustomerProperty::cancel)

                ->whereHas('inventory', function ($query) use ($floor_id, $id) {
                    $query->where('unit_floor_id', $floor_id);
                    $query->where('status', Inventory::sold);
                    if ($id !== 'all') {
                        $query->whereIn('multi_project_id', $id);
                    }
                })->sum('net_pay');

            $temp['un_booked_units_amount'] = Inventory::where([['is_deleted', false], ['unit_floor_id', $f->id], ['status', '!=', Inventory::sold]])
                ->when($id[0] !== 'all', function ($query) use ($id) {
                    $query->whereIn('multi_project_id', $id);
                })
                ->sum('total_price');

            $allProperties = CustomerProperty::where('is_deleted', false)->where('status', '!=', CustomerProperty::cancel)
                ->whereHas('inventory', function ($query) use ($floor_id, $id) {
                    $query->where('unit_floor_id', $floor_id);
                    if ($id !== 'all') {
                        $query->whereIn('multi_project_id', $id);
                    }
                })->pluck('id')->toArray();

            $temp['recovery'] = 0;

            $temp['discount'] = 0;

            $temp['receivable'] = 0;
            $temp['overdue'] = 0;
            $temp['future'] = 0;

            if (count($allProperties) > 0) {
                $temp['recovery'] = $temp['recovery'] = Receipt::where('is_deleted', false)->whereIn('customer_property_id', $allProperties)->where('is_approved', 1)->sum('amount');

                $discount = ($temp['total_units_amount'] - $temp['booked_units_amount']);

                $temp['discount'] = $discount > 0 ? $discount : 0;

                $temp['receivable'] = Customerproperty::whereIn('id', $allProperties)->sum('net_pay') - $temp['recovery'];

                $temp['overdue'] = CustomerStatement::whereIn('customer_property_id', $allProperties)->where('due_date', '<', Carbon::now())->sum('balance');
                $temp['future'] = CustomerStatement::whereIn('customer_property_id', $allProperties)->where('due_date', '>=', Carbon::now())->sum('balance');
            }

            array_push($floor_data, $temp);
        }

        //Type Wise Data

        $type_data = array();


        foreach ($allFloors as $f) {


            if (!empty($request->type)) {
                $types = UnitType::where('id', $request->type)->get();
            } else {
                $types = UnitType::all();
            }


            $temp2['floor_name'] = $f->name;

            $type = array();
            foreach ($types as $t) {
                $temp1['type_name'] = $t->name;
                $temp1['total_units'] = Inventory::where([['is_deleted', false], ['unit_type_id', $t->id], ['unit_floor_id', $f->id]])
                    ->when($id[0] !== 'all', function ($query) use ($id) {
                        $query->whereIn('multi_project_id', $id);
                    })
                    ->count();
                $temp1['booked_units'] = Inventory::where([['is_deleted', false], ['unit_type_id', $t->id], ['unit_floor_id', $f->id], ['status', Inventory::sold]])
                    ->when($id[0] !== 'all', function ($query) use ($id) {
                        $query->whereIn('multi_project_id', $id);
                    })
                    ->count();
                $temp1['un_booked_units'] = $temp1['total_units'] - $temp1['booked_units'];

                $result = Inventory::where([['is_deleted', false], ['unit_type_id', $t->id], ['unit_floor_id', $f->id]])
                    ->when($id[0] !== 'all', function ($query) use ($id) {
                        $query->whereIn('multi_project_id', $id);
                    })
                    ->pluck('unit_size_id')->toArray();
                $temp1['total_units_area'] = 0;
                foreach ($result as $r)
                    $temp1['total_units_area'] += UnitSize::where('id', $r)->first() ? UnitSize::where('id', $r)->first()->name : 0;

                $result = Inventory::where([['is_deleted', false], ['unit_type_id', $t->id], ['status', '!=', Inventory::sold], ['unit_floor_id', $f->id]])
                    ->when($id[0] !== 'all', function ($query) use ($id) {
                        $query->whereIn('multi_project_id', $id);
                    })
                    ->pluck('unit_size_id')->toArray();
                $temp1['un_booked_units_area'] = 0;
                foreach ($result as $r)
                    $temp1['un_booked_units_area'] += UnitSize::where('id', $r)->first() ? UnitSize::where('id', $r)->first()->name : 0;

                $temp1['booked_units_area'] = $temp1['total_units_area'] - $temp1['un_booked_units_area'];

                $temp1['total_units_amount'] = Inventory::where([['is_deleted', false], ['unit_type_id', $t->id], ['unit_floor_id', $f->id]])
                    ->when($id[0] !== 'all', function ($query) use ($id) {
                        $query->whereIn('multi_project_id', $id);
                    })
                    ->sum('total_price');

                $temp1['booked_units_amount'] = Inventory::where([['is_deleted', false], ['unit_type_id', $t->id], ['unit_floor_id', $f->id], ['status', Inventory::sold]])
                    ->when($id[0] !== 'all', function ($query) use ($id) {
                        $query->whereIn('multi_project_id', $id);
                    })
                    ->sum('total_price');

                $temp1['un_booked_units_amount'] = $temp1['total_units_amount'] - $temp1['booked_units_amount'];

                $floor_id = $f->id;
                $type_id = $t->id;

                $allProperties = CustomerProperty::where('is_deleted', false)->where('status', '!=', CustomerProperty::cancel)
                    ->whereHas('inventory', function ($query) use ($floor_id, $type_id, $id) {
                        $query->where('unit_floor_id', $floor_id);
                        $query->where('unit_type_id', $type_id);
                        if ($id !== 'all') {
                            $query->whereIn('multi_project_id', $id);
                        }
                    })->pluck('id')->toArray();


                $temp1['discount'] = 0;

                $temp1['recovery'] = 0;
                $temp1['receivable'] = 0;
                $temp1['overdue'] = 0;
                $temp1['future'] = 0;

                if (count($allProperties) > 0) {

                    $temp1['discount'] = Customerproperty::whereIn('id', $allProperties)->sum('discount');

                    $temp1['recovery'] = $temp['recovery'] = Receipt::where('is_deleted', false)->whereIn('customer_property_id', $allProperties)->where('is_approved', 1)->sum('amount');
                    $temp1['receivable'] = Customerproperty::whereIn('id', $allProperties)->sum('net_pay') - $temp1['recovery'];

                    $temp1['overdue'] = CustomerStatement::whereIn('customer_property_id', $allProperties)->where('due_date', '<', Carbon::now())->sum('balance');
                    $temp1['future'] = CustomerStatement::whereIn('customer_property_id', $allProperties)->where('due_date', '>=', Carbon::now())->sum('balance');
                }

                array_push($type, $temp1);
            }
            $temp2['type'] = $type;

            array_push($type_data, $temp2);
        }


        $data['floor_data'] = $floor_data;
        $data['type_data'] = $type_data;


        $data['unit_blooks'] = UnitBlock::all();

        // echo '<pre>';
        // print_r($data['floor_data']);
        // die;

    

        if (isset($data['multipro_id'])) {
            
            $multi_type= $data['project_ids'];
            
            if( $data['project_ids'] != 'all'){
           $v=     MultiProject::where('id',$data['project_ids'])->first();
           $multi_type=$v->project_type_id;
            }
            $data['multiproject_type'] =  $multi_type;
           

            return view('inventory.sale-detail-dashboard-update', $data);
        } else {

           
             
            $multi_type= $data['project_ids'];
        if( $data['project_ids'] != 'all'){
       $v=     MultiProject::where('id',$data['project_ids'])->first();
       $multi_type=$v->project_type_id;
        }
        $data['multiproject_type'] =  $multi_type;
       
            return view('inventory.sale-detail-dashboard', $data);
        }
    }
    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 {
                        $project_ids = $user->roles()
                            // ->where('name', 'NOT like', 'admin')
                            ->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();
                        //    dd( $data['multi_projects']);
                        $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;
        }
    }
}
