<?php

namespace App\Http\Controllers;

use App\BallotingMapDetail;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Storage;
use App\Rules\ExcelMapFileRule;
use App\Rules\DirectExcelMapFileRule;
use App\BallotingMapFile;
use App\BallotingPreConditionFile;
use App\BallotingPreConditionFileDetail;
use App\Customer;
use App\CustomerStatement;
use DB;
use App\Imports\ImportMapFileData;
use App\Jobs\StartBallotingJob;
use Illuminate\Support\Facades\Bus;
use App\CustomerProperty;
use App\Inventory;
use App\InventoryCategory;
use App\UnitSize;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Validator;
use App\DirectBallotingMapFile;
use App\MultiProject;
use Illuminate\Support\Facades\Auth;
use App\Traits\MultiProjectCookie;
use Illuminate\Support\Facades\Session;

class BallotingController extends Controller
{
    //
    use MultiProjectCookie;
    public function  settingIndex()
    {
        $balloting_files = BallotingMapFile::get();

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

        return view('balloting.setting.index', compact('balloting_files'));
    }

    public function  settingAddFile()
    {
        $data =  $this->getCookieInfoAndMultiPro();
        if ($data['status'] == 'error') {
            return redirect()

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

        activity('Add')->log('Add Balloting File');

        return view('balloting.setting.add', $data);
    }
    public function downloadFileFormate()
    {

        $filename =  'example.xlsx';
        $path = 'excel/' . 'example.xlsx';

        return response()->download(storage_path('app/' . $path), $filename, [
            'Content-Type' => 'application/vnd.ms-excel',
        ]);
    }

    public function downloadFileFormate2($id)
    {
        $file =    BallotingMapFile::where('id', $id)->first();
        $filename =  $file->file_name;
        $path = 'excel/' . $filename;

        return response()->download(storage_path('app/' . $path), $filename, [
            'Content-Type' => 'application/vnd.ms-excel',
        ]);
    }
    public function storeMapFile(Request $request)
    {


        $this->validate($request, [

            'name' => 'required',
            'description' => 'nullable|min:3|max:1000',
            'mapfile' => ['required', 'file', new ExcelMapFileRule],
        ]);

        $dec_pro_id =  $request->cookie('current_project_id');
        if (empty($dec_pro_id)) {
            return redirect()

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

        $pro_id = decrypt($dec_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();
            }
        } else {
            $request->merge(['multipro_id' =>  $dec_pro_id]);
        }

        if ($validator->fails()) {
            return redirect()
                ->back()
                ->withErrors($validator)->withInput();
        }



        $project_id = decrypt($request->multipro_id);



        $file = $request->file('mapfile');

        $filename = time() . '_' . $file->getClientOriginalName();

        // $path = $file->storeAs('excel', $filename, 'public');
        $path = $file->storeAs('excel', $filename, 'local');

        $balloting_file = new BallotingMapFile;
        $balloting_file->name = $request->name;
        $balloting_file->description = $request->description;
        $balloting_file->status = 0;
        $balloting_file->path = $path;
        $balloting_file->file_name = $filename;
        $balloting_file->multi_project_id = $project_id;
        $balloting_file->save();
        return redirect()
            ->route('balloting.setting.files')
            ->with([
                'message' => 'Data Added Successfully!',
                'alert-type' => 'success'
            ]);
    }
    // public function viewMapFile($filename)
    // {
    //     $path = 'excel/' . $filename;
    //     $data = Excel::toArray([], storage_path('app/' . $path))[0];
    //     return view('balloting.setting.view', compact('data'));
    // }
    public function viewMapFile($id)
    {
        $file =    BallotingMapFile::where('id', $id)->first();
        $filename =  $file->file_name;
        $path = 'excel/' . $filename;
        $data = Excel::toArray([], storage_path('app/' . $path))[0];
        activity('View')->log('View Balloting File');
        return view('balloting.setting.view', compact('data'));
    }
    public function viewPublishedMapFile($id)
    {
        $file_data =    BallotingMapDetail::where('balloting_map_file_id', $id)->paginate(25);

        activity('View')->log('View Balloting File');
        return view('balloting.setting.view_published_map', compact('file_data'));
    }
    // public function getCookieInfoAndMultiPro(){
    //     $data =  array();
    //     try{
    //            $request = app(Request::class);
    //                 if($request->has('multipro_id')){

    //             if($request->multipro_id == 'all'){
    //                 $data['multipro_id'] =$request->multipro_id;
    //             }else if(!empty($request->multipro_id)){
    //             $data['multipro_id'] =  decrypt($request->multipro_id);
    //             }
    //         }


    //         $project_id = request()->cookie('current_project_id');

    //         $user = Auth::user();
    //         $data['multi_projects'] = [];
    //         if (!empty($project_id)) {
    //             $p_id = decrypt($project_id);
    //             $multi = MultiProject::where('id', $p_id)->first();
    //             $multiProjectId = $multi->id;
    //             if ($multi->name == "Super Admin") {
    //                 $roles = $user
    //                     ->roles()
    //                     ->where('name', 'like', 'admin')
    //                     ->whereHas('projects', function ($query) use ($multiProjectId) {
    //                         $query->where('multi_project_id', $multiProjectId);
    //                     })
    //                     ->first();
    //                 if (!empty($roles)) {
    //                     $data['multi_projects']  = MultiProject::where('name', 'NOT like', 'Super Admin')->get();
    //                     $data['project'] = $multi->name;
    //                     $data['role'] = 'admin';
    //                     $data['project_ids'] =  'all';
    //                     if(isset( $data['multipro_id'])){
    //                         $data['project_ids'] = $data['multipro_id'];

    //                     }
    //                     $data['status'] = 'success';
    //                     return  $data;


    //                 } else {
    //                     // $request = app(Request::class);

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

    //                 $project_ids=       $user->roles()
    //                ->whereHas('projects', function ($query)   {
    //                $query->where('name', 'NOT like', 'Super Admin');
    //                })
    //                ->get()
    //                ->filter(function ($r) use ($permission) {
    //                return $r->hasPermission($permission);
    //                })
    //                ->pluck('projects.*.id') // Pluck the 'id' column from the remaining 'projects' models
    //                ->flatten() // Flatten the collection of IDs into a single array
    //                ->unique()
    //                ->toArray()
    //                ;

    //                if(sizeof($project_ids) == 0)
    //                {
    //                    $data['status'] = 'error';
    //                    return  $data; 
    //                }

    //                     $data['multi_projects'] = MultiProject::whereIn('id',  $project_ids)->where('name', 'NOT like', 'Super Admin')->get();
    //                     $data['project'] = $multi->name;
    //                     $data['role'] = 'other';
    //                     $data['project_ids'] =  $project_ids;
    //                     if(isset( $data['multipro_id'])){
    //                         if($data['multipro_id'] != 'all'){
    //                         $data['project_ids'] = $data['multipro_id'];
    //                         }

    //                     }
    //                     $data['status'] = 'success';
    //                     return $data;
    //                 }
    //             }
    //             else{
    //                 $roles = $user
    //                     ->roles()

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

    //                     if (!empty($roles)) {
    //                         $data['multi_projects']  = [];
    //                         $data['project'] = $multi->name;
    //                         $data['role'] = 'other';
    //                         $data['project_ids'] =  $multi->id ;
    //                         if(isset( $data['multipro_id'])){
    //                             if($data['multipro_id'] != 'all'){
    //                                 $data['project_ids'] = $data['multipro_id'];
    //                                 }
    //                         }
    //                         $data['status'] = 'success';
    //                         return  $data;


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

    //     }
    // }
    public function ballotingPreConditions()
    {
        $balloting_files = BallotingMapFile::where('publish', 1)->get();

        $unit_size = UnitSize::where('status', 1)->where('is_deleted', 0)->get();
        $data =  $this->getCookieInfoAndMultiPro();

        if ($data['status'] == 'error') {
            return redirect()

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


        activity('View')->log('View Pre Condition List');


        return view('balloting.start.index', $data, compact('balloting_files', 'unit_size'));
    }
    public function getInventoryList(Request $request)
    {
        $dec_pro_id =  $request->cookie('current_project_id');
        if (empty($dec_pro_id)) {
            return redirect()

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

        $pro_id = decrypt($dec_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();
            }
        } else {
            $request->merge(['multipro_id' =>  $dec_pro_id]);
        }

        if ($validator->fails()) {
            return redirect()
                ->back()
                ->withErrors($validator)->withInput();
        }



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

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

        $customer_properties = CustomerProperty::select(
            'customer_properties.*',
            DB::raw('SUM(customer_statements.received) as received_sum'),
            DB::raw('SUM(customer_statements.due) as due_amount_sum'),
        )
            ->join('customer_statements', 'customer_statements.customer_property_id', '=', 'customer_properties.id')
            ->join('inventories', 'inventories.id', '=', 'customer_properties.inventory_id')
            ->when($ids[0] !== 'all', function ($query) use ($ids) {
                $query->whereHas('inventory', function ($q) use ($ids) {
                    $q->whereIn('multi_project_id', $ids);
                });
            })
            ->where('customer_properties.is_deleted', false)
            ->whereNull('customer_properties.block_date')
            ->whereNull('customer_properties.cancel_date')
            ->whereNull('inventories.unit_floor_id')
            ->where('inventories.inventory_type', Inventory::unallocated)
            ->where('inventories.status', Inventory::sold)
            ->where('customer_properties.status', CustomerProperty::approved)
            ->where('inventories.unit_number', 'like', '%' . $request->q . '%')
            ->groupBy('customer_statements.customer_property_id')
            ->take(10)->get();


        $data = [];

        if (!empty($customer_properties)) {
            foreach ($customer_properties as $result) {
                $data[] = [
                    'id' => $result->inventory->id,
                    'text' => $result->customer->name . ' --- ' . $result->inventory->unit_number . ' --- ' . $result->inventory->size->name . ' marla',
                ];
            }
        }
        return response()->json($data);
    }
    public function getInventoryUnitNumberList(Request $request)
    {



        $dec_pro_id =  $request->cookie('current_project_id');
        if (empty($dec_pro_id)) {
            $data = [
                'message' => 'Something went wrong!',
                'alert-type' => 'error',
            ];

            return response()->json(['error' => $data]);
        }

        $pro_id = decrypt($dec_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()) {
                $data = [
                    'message' => 'Invalide Input!',
                    'alert-type' => 'error',
                ];

                return response()->json(['error' => $data]);
            }
        } else {
            $request->merge(['multipro_id' =>  $dec_pro_id]);
        }

        if ($validator->fails()) {
            return redirect()
                ->back()
                ->withErrors($validator)->withInput();
        }



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

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












        $customer_properties = CustomerProperty::select('customer_properties.*')->with('inventory')
            ->join('customer_statements', 'customer_statements.customer_property_id', '=', 'customer_properties.id')
            ->join('inventories', 'inventories.id', '=', 'customer_properties.inventory_id')
            ->when($ids[0] !== 'all', function ($query) use ($ids) {
                $query->whereHas('inventory', function ($q) use ($ids) {
                    $q->whereIn('multi_project_id', $ids);
                });
            })
            ->where('customer_properties.is_deleted', false)
            ->whereNull('customer_properties.block_date')
            ->whereNull('customer_properties.cancel_date')
            ->whereNull('inventories.unit_floor_id')
            ->where('inventories.inventory_type', Inventory::unallocated)
            ->where('customer_properties.status', CustomerProperty::approved)



            ->where('inventories.unit_number', 'like', '%' . $request->q . '%')
            ->groupBy('customer_statements.customer_property_id')
            ->take(10)->get();

        $data = [];

        if (!empty($customer_properties)) {
            foreach ($customer_properties as $result) {
                $data[] = [
                    'id' => $result->id,
                    'text' => $result->inventory->unit_number,
                ];
            }
        }
        return response()->json($data);
    }

    public function getInventoryInfo(Request $request)
    {

        $statement = CustomerProperty::where('id', $request->id)->first();
        $category_id = [];
        $category_name = [];

        if (count($statement->customerPrefferedCategory) > 0) {

            foreach ($statement->customerPrefferedCategory as $c) {
                $category_id[] = $c->category->id;
                $category_name[] = $c->category->name;
            }
        }
        $data = [
            'id' => $statement->inventory->id,
            'size' => $statement->inventory->size->name,
            'name' => $statement->customer ? $statement->customer->name . '---' . $statement->customer->cnic : '',
            'netpay' => number_format($statement->net_pay),
            'data' => date('d-m-Y', strtotime($statement->booking_date)),
            'unit_size_id' => $statement->inventory->unit_size_id,
            'category_id' => $category_id,
            'category_name' => $category_name

        ];

        return $data;
    }

    public function startBalloting(Request $request)
    {


        $dec_pro_id =  $request->cookie('current_project_id');
        if (empty($dec_pro_id)) {
            return redirect()

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

        $pro_id = decrypt($dec_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();
            }
        } else {
            $request->merge(['multipro_id' =>  $dec_pro_id]);
        }

        if ($validator->fails()) {
            return redirect()
                ->back()
                ->withErrors($validator)->withInput();
        }



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

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

        $b = new BallotingMapDetail;
        $allStatements = $b->startCreatedPreconditionInventory($request, $ids);
        if ($request->pre_condition != BallotingMapDetail::random) {
            if ($request->overdue_amount != 'on') {
                $allStatements = collect($allStatements)->filter(function ($statement) {
                    return DB::table('customer_statements')
                        ->where('customer_property_id', $statement->id) // replace 'id' with your statement ID column name
                        ->havingRaw('SUM(CASE WHEN customer_statements.due_date < ? THEN customer_statements.balance ELSE 0 END) = 0', [\Carbon\Carbon::today()])
                        ->exists();
                });
            }
        }

        $unitSizeIds = $allStatements->pluck('inventory.unit_size_id');



        $unit_size = UnitSize::where('status', 1)->where('is_deleted', 0)->get();

        $balloting_files = BallotingMapFile::where('publish', 1)->get();
        $multipro_id = $request->multipro_id;

        return view('balloting.start.selected_inventory', compact('multipro_id', 'unitSizeIds', 'unit_size', 'allStatements', 'balloting_files'));
    }
    public function getCnicList()
    {
        // Session::flush();
        $cnicList = [];
        $nameList = [];
        foreach (Session::all() as $key => $value) {
            if (strpos($key, 'customer_') === 0) {
                $cnicList[] = $value['cnic'];
                $nameList[] = $value['name'];
            }
        }
        $val = [
            'cnic' => $cnicList,
            'name' => $nameList
        ];
        return response()->json($val);
    }
    public function startBallotingMap(Request $request)
    {
        // if ($request->has('unit_category_'.'267')) {

        // }

        // dd($request->all());
        // Session::flush();
        $sessionKeysToRemove = [];

        foreach (Session::all() as $key => $value) {
            if (strpos($key, 'customer_') === 0) {
                $sessionKeysToRemove[] = $key;
            }
        }

        foreach ($sessionKeysToRemove as $key) {
            Session::forget($key);
            // Optionally, you can also remove the flash session data for this key

        }
        $b = new BallotingMapDetail;
        $val = $b->startBallotingInventory($request);
        if ($val['status'] == true) {
            return response()->json([
                'success' => true,
                'message' => 'Data Published Successfully',
                'id' => $val['id']
            ]);
        } else {
            return response()->json([
                'success' => false,
                'message' => 'SomeThing went wrong'
            ]);
        }
    }

    public function storePreConditionFiles(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'inventory_id.*' => 'required|integer',
            'unit_size_id.*' => 'required|integer'
        ]);
        if ($validator->fails()) {
            return redirect()->route('balloting.start.preconditions')
                ->withErrors($validator)
                ->withInput()
                ->with([
                    'message' => 'Invalid Inputs!',
                    'alert-type' => 'error',
                ]);
        }



        $dec_pro_id =  $request->cookie('current_project_id');
        if (empty($dec_pro_id)) {
            return redirect()

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

        $pro_id = decrypt($dec_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()->route('balloting.start.preconditions')
                    ->withErrors($validator)
                    ->withInput()
                    ->with([
                        'message' => 'Invalid Inputs!',
                        'alert-type' => 'error',
                    ]);
            }
        } else {
            $request->merge(['multipro_id' =>  $dec_pro_id]);
        }

        if ($validator->fails()) {
            return redirect()
                ->back()
                ->withErrors($validator)->withInput();
        }



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

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

        if ($ids[0] == 'all') {
            $ids =    MultiProject::where('name', 'NOT LIKE', 'Super Admin')->get()->pluck('id')->toArray();
        }


        // if ($validator->fails()) {
        //     return redirect()->route('balloting.start.preconditions')
        //         ->withErrors($validator)
        //         ->withInput()
        //         ->with([
        //             'message' => 'Invalid Inputs!',
        //             'alert-type' => 'error',
        //         ]);
        // }
        // dd($request->all());
        $val = 1;
        DB::beginTransaction();
        try {
            $listnumber = BallotingPreConditionFile::select('name')->where('name', 'like', 'PCL-%')->latest('id')->first();
            if (!empty($listnumber)) {
                $number = str_replace('PCL-', "", $listnumber ? $listnumber->name : 1);

                $val = $number + 1;
            }


            $balloting_pre = new BallotingPreConditionFile;

            $balloting_pre->name = 'PCL-' . $val;
            $balloting_pre->save();
            foreach ($request->inventory_id as $index => $inv) {
                $detail = new BallotingPreConditionFileDetail;
                $detail->balloting_pre_cond_file_id = $balloting_pre->id;
                $detail->inventory_id = $inv;
                $request->unit_size_id[$index];
                $detail->unit_size_id = $request->unit_size_id[$index];

                $detail->save();
            }

            foreach ($ids as $id) {

                DB::insert('insert into preconditionfile_with_multiproject (multi_project_id, balloting_precondition_file_id) values (?, ?)', [$id, $balloting_pre->id]);
            }

            DB::commit();

            return redirect()
                ->route('balloting.start.balloting.index', $balloting_pre->id)
                ->with([
                    'message' => 'Inventories are ready to ballot!',
                    'alert-type' => 'success'
                ]);
        } catch (\Exception $e) {
            DB::rollback();
            return redirect()->route('balloting.start.preconditions')
                ->with([
                    'message' => 'Something went wrong!',
                    'alert-type' => 'error'
                ]);
        }
    }

    public function preConditionBallotingListForBalloting($id)
    {

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

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




        $pre_cond =    BallotingPreConditionFile::where('id', $id)->first();
        $allStatements = new Collection();

        foreach ($pre_cond->detail as $detail) {

            $cust_pro =  CustomerProperty::select(
                'customer_properties.*'
            )
                ->where('inventory_id', $detail->inventory_id)
                ->join('inventories', 'inventories.id', '=', 'customer_properties.inventory_id')

                ->where('customer_properties.is_deleted', false)
                ->whereNull('customer_properties.block_date')
                ->whereNull('customer_properties.cancel_date')
                ->whereNull('inventories.unit_floor_id')
                ->where('inventories.inventory_type', Inventory::unallocated)
                ->where('customer_properties.status', CustomerProperty::approved)
                ->groupBy('customer_properties.id')
                ->first();
            if (!empty($cust_pro)) {
                $allStatements->push($cust_pro);
            }
        }

        $balloting_files = BallotingMapFile::where('publish', 1)
            ->when($ids[0] !== 'all', function ($query) use ($ids) {
                $query->whereIn('multi_project_id', $ids);
            })
            ->get();

        $multipro_id = 'all';
        if ($ids[0] != 'all' && sizeof($ids) == 0) {

            $multipro_id =   decrypt($ids[0]);
        }

        activity('View')->log('Pre Condition Start Balloting List');



        return view('balloting.precoditionlist.start_balloting', compact('multipro_id', 'balloting_files', 'allStatements', 'pre_cond'));
    }


    public function viewPreConditionBallotingListForBalloting($id)
    {

        $pre_cond =    BallotingPreConditionFile::where('id', $id)->first();
        $allStatements = new Collection();

        foreach ($pre_cond->detail as $detail) {

            $cust_pro =        CustomerProperty::where('inventory_id', $detail->inventory_id)
                ->join('inventories', 'inventories.id', '=', 'customer_properties.inventory_id')

                ->where('customer_properties.is_deleted', false)
                ->whereNull('customer_properties.block_date')
                ->whereNull('customer_properties.cancel_date')


                ->where('customer_properties.status', CustomerProperty::approved)
                ->first();
            if (!empty($cust_pro)) {
                $allStatements->push($cust_pro);
            }
        }
        $balloting_files = BallotingMapFile::where('publish', 1)->get();

        activity('View')->log('View Pre Condition Balloting');


        return view('balloting.precoditionlist.view', compact('balloting_files', 'allStatements', 'pre_cond'));
    }



    public function importBallotingMapFileData(Request $request)
    {
        try {
            $balloting_file = BallotingMapFile::where('id', $request->map_id)->first();


            $data = Excel::toArray([], storage_path('app/' . $balloting_file->path))[0];
            $total_row = sizeof($data);
            $path = storage_path('app/' . $balloting_file->path);
            $import = new ImportMapFileData($balloting_file->id, $total_row, $balloting_file->multi_project_id);

            Excel::import($import, storage_path('app/' . $balloting_file->path));

            $errorMessages = $import->getErrorMessages();



            session(['progress' => 100]);
            $balloting_file->publish = 1;
            $balloting_file->save();
            if (!empty($errorMessages)) {
                return response()->json(['success' => true, 'pub_message' => $errorMessages]);
            }
            return response()->json([
                'success' => true,
                'message' => 'Data Published Successfully',
                'pub_message' => []
            ]);
        } catch (\Exception $e) {

            return response()->json([
                'error' => true,
                'message' => 'Something went wrong'
            ], 500);
        }
    }

    public function publishMap($id)
    {
        $balloting_file = BallotingMapFile::where('id', $id)->first();

        activity('Publish')->log('Import Pre Condition Balloting File Map');


        return view('balloting.setting.publish', compact('balloting_file'));
    }
    public function  publishMapInventory($id)
    {
        $data =  $this->getCookieInfoAndMultiPro();
        if ($data['status'] == 'error') {
            return redirect()

                ->back()
                ->with([
                    'message' => 'Invalid Inputs!',
                    'alert-type' => 'error',
                ]);
        }
        $ids = [];
        if (is_array($data['project_ids'])) {
            $ids =    $data['project_ids'];
        } else {
            $ids[] =    $data['project_ids'];
        }
        $balloting_file = BallotingMapFile::where('id', $id)
            ->when($ids[0] !== 'all', function ($query) use ($ids) {
                $query->whereIn('multi_project_id', $ids);
            })
            ->first();

        if (empty($balloting_file)) {

            return redirect()

                ->route('home')
                ->with([
                    'message' => 'UnAuthorized Action!',
                    'alert-type' => 'error',
                ]);
        }

        activity('View')->log('Pre Condition Start Balloting List after Import');

        return view('balloting.start.view', compact('balloting_file'));
    }

    public function  mapListIndex()
    {
        $data =  $this->getCookieInfoAndMultiPro();
        if ($data['status'] == 'error') {
            return redirect()

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

        $balloting_files = BallotingMapFile::where('status', 1)
            ->when($ids[0] !== 'all', function ($query) use ($ids) {
                $query->whereIn('multi_project_id', $ids);
            })
            ->get();

        activity('View')->log('Pre Condition Balloting List');

        return view('balloting.list.index', compact('balloting_files'));
    }
    public function editMapInventory($id)
    {



        $ball_detail = BallotingMapDetail::where('id', $id)->first();
        $request = app(Request::class);
        $request->merge([
            'multipro_id' => encrypt($ball_detail->map->multi_project_id),

        ]);


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

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

        if ($ids[0] == $ball_detail->map->multi_project_id || $ids[0] == 'all') {
            if ($ids[0] != 'all') {
                $multipro_id = $ball_detail->map->multi_project_id;
            } else {
                $multipro_id = 'all';
            }
            // $customer_properties = CustomerProperty::select('customer_properties.*')
            // ->join('customer_statements', 'customer_statements.customer_property_id', '=', 'customer_properties.id')
            // ->join('inventories', 'inventories.id', '=', 'customer_properties.inventory_id')
            // ->select('customer_properties.*', DB::raw('SUM(customer_statements.received) as received_sum'), DB::raw('SUM(customer_statements.due) as due_amount_sum'))
            // ->where('customer_properties.plot_no', null)
            // ->where('customer_properties.is_deleted', false)
            // ->groupBy('customer_statements.customer_property_id')
            // ->get();

            activity('Edit')->log('Pre Condition Balloting File');


            return view('balloting.list.edit', compact('ball_detail', 'multipro_id'));
        } else {
            return redirect()

                ->route('home')
                ->with([
                    'message' => 'UnAuthorized Action!',
                    'alert-type' => 'error',
                ]);
        }

        // $customer_properties = CustomerProperty::select('customer_properties.*')
        //     ->join('customer_statements', 'customer_statements.customer_property_id', '=', 'customer_properties.id')
        //     ->join('inventories', 'inventories.id', '=', 'customer_properties.inventory_id')
        //     ->select('customer_properties.*', DB::raw('SUM(customer_statements.received) as received_sum'), DB::raw('SUM(customer_statements.due) as due_amount_sum'))
        //     ->where('customer_properties.plot_no', null)
        //     ->where('customer_properties.is_deleted', false)
        //     ->groupBy('customer_statements.customer_property_id')
        //     ->get();


    }
    public function updateMapInventory(Request $request)
    {


        $this->validate($request, [

            'id' => 'required',
            'customer_property' => 'required',

        ]);
        $ball_map_detail =  BallotingMapDetail::where('id', $request->id)->first();
        $inventory =  Inventory::where('id', $request->customer_property)->first();
        if ($ball_map_detail->unit_size_id == $inventory->unit_size_id) {
            $ball_map_detail->inventory_id = $inventory->id;
            $ball_map_detail->balloting_status = BallotingMapDetail::balloting_pending;
            $ball_map_detail->save();
            $inventory = Inventory::where('id', $inventory->id)->first();

            $old_unit_number = $inventory->unit_number;
            $inventory->unit_number = $ball_map_detail->plot_no;
            $inventory->unit_floor_id = $ball_map_detail->unit_floor_id;
            $inventory->old_unit_number = $old_unit_number;
            $inventory->inventory_type = Inventory::allocated;
            $inventory->save();
            $ballondetail =  BallotingPreConditionFileDetail::where('inventory_id', $inventory->id)->get();
            foreach ($ballondetail as $detail) {
                $detail->balloting_map_detail_id = $ball_map_detail->id;
                $detail->save();
            }

            if (!empty($ball_map_detail->category)) {
                foreach ($ball_map_detail->category as $r) {

                    InventoryCategory::create(['inventory_id' => $inventory->id, 'unit_category_id' => $r->category_id]);
                }
            }

            return redirect()
                ->route('balloting.map.inventory', $ball_map_detail->balloting_map_file_id)
                ->with([
                    'message' => 'Data Updated Successfully!',
                    'alert-type' => 'success'
                ]);
        }
        return redirect()
            ->back()
            ->with([
                'message' => 'Sizes Mismatch!',
                'alert-type' => 'error'
            ]);
    }
    public function getMapFileInformation(Request $request)
    {
        // dd($request->all());
        // $map = BallotingMapFile::where('id', $id)->first();
        // $unitSizeIds = $map->mapDetail()->distinct('unit_size_id')->pluck('unit_size_id');
        $map = BallotingMapFile::where('id', $request->id)->first();

        $sector = $map->mapDetail()->select('unit_block_id', 'sector')->distinct('unit_size_id')->get();
        $counts = $map->mapDetail()->select('unit_size_id', 'area', DB::raw('COUNT(*) as count'))->groupBy('unit_size_id')->get();

        $pf =   BallotingPreConditionFile::where('id', $request->pc_id)->first();
        $count2 = BallotingPreConditionFileDetail::where('balloting_pre_cond_file_id', $pf->id)->select('unit_size_id', DB::raw('COUNT(*) as count'))->groupBy('unit_size_id')->get();


        $unitSizes = $counts->pluck('unit_size_id')->merge($count2->pluck('unit_size_id'))->unique();
        // dd($unitSizes);
        $differences = [];
        foreach ($unitSizes as $unitSize) {
            $c1 = $counts->where('unit_size_id', $unitSize)->pluck('count')->first() ?? 0;
            $c2 = $count2->where('unit_size_id', $unitSize)->pluck('count')->first() ?? 0;
            $diff = abs($c1 - $c2);

            $differences[$unitSize] = $diff;
        }
        $msg = [];

        foreach ($differences as $index => $val) {

            $size = UnitSize::where('id', $index)->first();
            $name = $size->name;
            $diff = $val;
            $msg[] = [
                'size' => $name,
                'diff' => $val,

            ];
        }

        // dd($differences);
        // dd($counts,$count2);
        $data = [
            'msg' => $msg,
            'map' => $map->mapDetail,
            'sector' => $sector
        ];
        if (!empty($map)) {

            return  $data;
        } else {
            return response()->json([
                'success' => false,
                'message' => 'SomeThing went wrong'
            ]);
        }
    }
    public function removeMapFileInventory(Request $request)
    {

        try {
            $ball_map_detail = BallotingMapDetail::where('id', $request->id)->first();


            $inventory =  Inventory::where('id', $ball_map_detail->inventory_id)->first();

            $inventory->unit_number =   $inventory->old_unit_number;

            $ball_map_detail->inventory_id = null;
            $ball_map_detail->balloting_status = BallotingMapDetail::not_ballot_yet;
            $ball_map_detail->save();

            // $inventory = Inventory::where('id', $customer_pro->inventory_id)->first();
            $inventory->unit_floor_id = null;
            $inventory->inventory_type = Inventory::unallocated;
            $inventory->save();

            $ballondetail =  BallotingPreConditionFileDetail::where('inventory_id', $inventory->id)->get();
            foreach ($ballondetail as $detail) {
                $detail->balloting_map_detail_id = '';
                $detail->save();
            }

            if (!empty($ball_map_detail->category)) {
                foreach ($ball_map_detail->category as $r) {

                    $inventory_cat = InventoryCategory::where('inventory_id', $inventory->id)->where('unit_category_id', $r->category_id)->first();
                    if ($inventory_cat->percent == 0 && $inventory_cat->is_percent == 0) {
                        $inventory_cat->delete();
                    }
                }
            }

            return response()->json([
                'success' => true,
                'message' => 'Data Removed Successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'error' => true,
                'message' => 'Something went wrong'
            ], 500);
        }
    }

    public function preConditionList()
    {
        $data =  $this->getCookieInfoAndMultiPro();
        if ($data['status'] == 'error') {
            return redirect()

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

        $ballonpre_condition =  BallotingPreConditionFile::when($ids[0] !== 'all', function ($query) use ($ids) {
            $query->whereHas('projects', function ($q) use ($ids) {
                $q->whereIn('multi_project_id', $ids);
            });
            // ->has('projects', '=', 1);
        })->get();

        activity('View')->log('Pre Condition List');

        return view('balloting.precoditionlist.index', compact('ballonpre_condition'));
    }

    public function approveBalloting($id)
    {
        $balloting_detail =     BallotingMapDetail::where('id', $id)->where('balloting_status', BallotingMapDetail::balloting_pending)->first();
        if (!empty($balloting_detail)) {
            if ($balloting_detail->inventory_id) {
                $inventory = Inventory::with('categories', 'size', 'floor', 'type')->where('id', $balloting_detail->inventory_id)->first();
                $sum = 0;
                if (sizeof($inventory->categories) > 0) {
                    foreach ($inventory->categories as $c) {

                        if ($c->is_percent) {
                            $sum += ($inventory->total_price * $c->percent) / 100;
                        } else {
                            $sum +=  $c->percent;
                        }
                    }
                }

                activity('View')->log('Pre Condition Approve Balloting List');


                return view('balloting.approve.index', compact('sum', 'inventory', 'balloting_detail'));
            }
        } else {
            return redirect()->back()
                ->with([
                    'message' => 'SomeThing went wrong!',
                    'alert-type' => 'error'
                ]);
        }
    }

    public function storeApproveBalloting(Request $request)
    {


        $this->validate($request, [

            'add_charges' => 'required|numeric',
            'balloting_id' => 'required|numeric',

        ]);

        if ($request->add_charges == 1) {
            $this->validate($request, [

                'custom_date.*' => 'required',
                'custom_amount.*' => 'required',
            ]);
        }
        // dd($request->all());
        DB::beginTransaction();
        try {

            $balloting_detail =     BallotingMapDetail::where('id', $request->balloting_id)->where('balloting_status', BallotingMapDetail::balloting_pending)->first();

            if (!empty($balloting_detail)) {
                $balloting_detail->balloting_status = BallotingMapDetail::balloting_complete;
                $balloting_detail->save();
                $sum = 0;
                if ($request->add_charges == 1) {
                    $customer_property =    $balloting_detail->Inventory->customer_property;
                    $last_balloting_amount   =  CustomerStatement::where('customer_id', $customer_property->customer_id)->where('customer_property_id', $customer_property->id)->where('payment_head', CustomerStatement::balloting)->latest('id')
                        ->first();
                    $last_balloting_amount_inst_no = 0;
                    if (!empty($last_balloting_amount)) {
                        $cleanString = preg_replace('/[^0-9]/', '', $last_balloting_amount->inst_no);
                        $last_balloting_amount_inst_no = (int) $cleanString;
                    }

                    for ($i = 0; $i < sizeof($request->custom_date); $i++) {

                        $last_balloting_amount_inst_no =   $last_balloting_amount_inst_no + 1;
                        $sum = $sum + $request->custom_amount[$i];

                        CustomerStatement::create(['customer_id' => $customer_property->customer_id, 'customer_property_id' => $customer_property->id, 'payment_head' => CustomerStatement::balloting, 'inst_no' =>   $last_balloting_amount_inst_no, 'due_date' => $request->custom_date[$i], 'due' => $request->custom_amount[$i], 'balance' => $request->custom_amount[$i], 'received' => 0]);
                    }
                    $property = CustomerProperty::where('id', $customer_property->id)->first();
                    $property->net_pay =  $property->net_pay + $sum;
                    $property->save();
                    $inventory =  Inventory::where('id', $balloting_detail->inventory_id)->first();
                    $inventory->extra_amount = $inventory->extra_amount + $sum;
                    $inventory->total_price =  $inventory->total_price +  $sum;
                    $inventory->save();
                    //  dd($balloting_detail,$balloting_detail->Inventory->customer_property);
                    // 
                    //  $property = CustomerProperty::where()
                    //Make Bulleting payment entry
                    //  
                }
            }
        } catch (\Exception $e) {


            DB::rollback();
            return redirect()->route('balloting.map.inventory', $balloting_detail->balloting_map_file_id)
                ->with([
                    'message' => 'SomeThing went wrong!',
                    'alert-type' => 'error'
                ]);
        }
        DB::commit();

        return redirect()
            ->route('balloting.map.inventory', $balloting_detail->balloting_map_file_id)
            ->with([
                'message' => 'Property Approved Sucessfully!',
                'alert-type' => 'success'
            ]);
    }
    public function getBallotResultAgainstCnic(Request $request)
    {
        $this->validate($request, [
            'cnic' => 'required|string|size:13', // Add validation rules
        ]);
        $cnic = $request->input('cnic');

       
        $ballot_detail = [];
        $customer = Customer::where('cnic', $cnic)->first();
       
        if (!empty($customer)) {
            
            foreach ($customer->properties as $property) {


                $ballot_inventory =  BallotingMapDetail::where('inventory_id', $property->inventory_id)->first();
                if (!empty($ballot_inventory)) {

                    $detail = [
                        'plot_no' => $ballot_inventory->plot_no,
                        'area' => $ballot_inventory->area.' Marla',
                        'feature' => $ballot_inventory->feature,
                        'sector' => $ballot_inventory->sector,
                        'road_category' => $ballot_inventory->road_category,
                    ];
                    $ballot_detail[] =   $detail;
                }
            }
        } else {
            $response = [
                'cnic' => $cnic,
                'error' => "Customer Not Exists",
            ];
            return response()->json($response);
        }
        $response = [
            'cnic' => $cnic,
            'ballot_detail' =>   $ballot_detail,
        ];
        

        return response()->json($response);
    }
    public function getResultForm(){

        return view('balloting.resultform');
    }
}
