<?php

namespace App\Http\Controllers;

use App\Classes\EditLogHistory;
use App\Models\CancelReason;
use App\Models\Pop;
use App\Models\SubPackage;
use App\Models\ClientSource;
use App\Models\MarketingDone;
use Illuminate\Http\Request;
use App\Models\NewLineRequest;
use Illuminate\Support\Facades\DB;
use Brian2694\Toastr\Facades\Toastr;
use App\Models\NewLineRequestRemarks;
use App\Models\NewLineRequestSmartDevice;
use App\Models\SmartDivice;
use App\Models\CompanyInformation;
use App\Models\District;
use App\Models\Division;
use App\Models\Employee;
use App\Models\LogHistory;
use App\Models\NewLineRequestSurveyCancelReason;
use App\Models\Packages;
use App\Models\Thana;
use App\Models\Upazila;
use App\Models\User;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Cache;



class NewLineRequestController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if (!auth()->user()->can('confirm-line-request-index')) {
            Toastr::error('You are not authorized to access this page!');
            return redirect()->back();
        }

        $pops = Pop::all();

        $newLineRequests = NewLineRequest::with('marketingEmployee', 'pop', 'package', 'user', 'subPackage.package', 'remarksList.user', 'lineManager', 'client', 'newLineToken')->where('line_status', 'confirm_request')->orderBy('updated_at', 'asc')->get();

        if (request('status') == null && request('pop_id') == null) {
            $newLineRequests = $newLineRequests->where('status', 'pending');
        }

        if (request('pop_id')) {
            $newLineRequests = $newLineRequests->where('pop_id', request('pop_id'));
        }

        if (request('status')) {
            $newLineRequests = $newLineRequests->where('status', request('status'));
        }

        if (request('delivery_date')) {
            $deliveryDate = Carbon::parse(request('delivery_date'))->format('Y-m-d');
            $newLineRequests = $newLineRequests->filter(function ($req) use ($deliveryDate) {
                return $req->delivery_date && Carbon::parse($req->delivery_date)->format('Y-m-d') === $deliveryDate;
            });
        }

        if (request('delivery_date_before')) {
            $today = Carbon::today()->format('Y-m-d');
            $newLineRequests = $newLineRequests->filter(function ($req) use ($today) {
                return $req->delivery_date && Carbon::parse($req->delivery_date)->format('Y-m-d') < $today;
            });
        }


        $companyInfo = \App\Models\CompanyInformation::latest()->first();
        $max_free_day = $companyInfo ? ($companyInfo->max_free_day ?? 0) : 0;
        $lineMen = \App\Models\Employee::where('status', 'active')->orderBy('name')->get();

        return view('clients.newclient.index', [
            'page_title' => 'Confirm Line Request',
            'lists' => $newLineRequests,
            'pops' => $pops,
            'max_free_day' => $max_free_day,
            'lineMen' => $lineMen,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $confday = config('app.billing_cycle');
        $pops = Pop::all();
        return view('clients.newclient.create', [
            'page_title' => 'Create New Line Request',
            'pops' => $pops,
            'confday' => $confday,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'address' => 'required',
            'pop_id' => 'required',
            'package_id' => 'required',
            'otc' => 'required|numeric',
            'phone' => 'required',
            'fiber_meter' => 'required|numeric',
            'notes' => 'nullable',
            'billing_date' => 'required',
            'nid' => 'nullable',
            'alt_phone' => 'nullable',
        ]);
        // dd($request->all());

        $pop = Pop::find($request->pop_id);
        if ($pop->subreseller == 'yes') {
            $subPackageId = SubPackage::where('id', $request->package_id)->first();
            $packageId = $subPackageId->package_id ?? null;
        } else {
            $packageId = $request->package_id;
        }

        try {
            DB::beginTransaction();

            $newLineRequest = new NewLineRequest();
            $newLineRequest->name = $request->name;
            $newLineRequest->father_name = $request->father_name;
            $newLineRequest->mother_name = $request->mother_name;
            $newLineRequest->phone = $request->phone;
            $newLineRequest->alt_phone = $request->alt_phone;
            $newLineRequest->nid = $request->nid;
            $newLineRequest->billing_date = $request->billing_date;
            $newLineRequest->address = $request->address;
            $newLineRequest->pop_id = $request->pop_id;
            $newLineRequest->package_id = $packageId;
            if ($pop->subreseller == 'yes') {
                $newLineRequest->sub_package_id = $request->package_id;
            } else {
                $newLineRequest->sub_package_id = null;
            }
            $newLineRequest->otc = $request->otc;
            $newLineRequest->fiver_miter = $request->fiber_meter;
            $newLineRequest->lat = $request->latitude;
            $newLineRequest->long = $request->longitude;
            $newLineRequest->created_by = auth()->user()->id;
            $newLineRequest->status = 'pending';
            $newLineRequest->line_status = 'confirm_request';
            $newLineRequest->save();

            $newLineRequestRemark = new NewLineRequestRemarks();
            $newLineRequestRemark->new_line_request_id = $newLineRequest->id;
            $newLineRequestRemark->remarks = $request->notes;
            $newLineRequestRemark->created_by = auth()->user()->id;
            $newLineRequestRemark->save();

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Toastr::error('Something went wrong');
            return redirect()->back()->withInput();
        }

        Toastr::success('New Line Request created successfully');
        return redirect()->route('new-line-request.index');
    }

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\NewLineRequest  $newLineRequest
     * @return \Illuminate\Http\Response
     */
    public function edit(NewLineRequest $newLineRequest)
    {
        $confday = config('app.billing_cycle');
        $pops = Pop::all();
        $newLineRequest->load('pop', 'package');
        return view('clients.newclient.edit', [
            'page_title' => 'Edit New Line Request',
            'newLineRequest' => $newLineRequest,
            'pops' => $pops,
            'confday' => $confday,
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\NewLineRequest  $newLineRequest
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, NewLineRequest $newLineRequest)
    {
        $request->validate([
            'name' => 'required',
            'address' => 'required',
            'pop_id' => 'required',
            'package_id' => 'required',
            'otc' => 'required|numeric',
            'phone' => 'required',
            'fiber_meter' => 'required|numeric',
            'notes' => 'nullable',
            'billing_date' => 'required',
            'nid' => 'nullable',
            'alt_phone' => 'nullable',
        ]);

        $pop = Pop::find($request->pop_id);
        if ($pop->subreseller == 'yes') {
            $subPackageId = SubPackage::where('id', $request->package_id)->first();
            $packageId = $subPackageId->package_id ?? null;
        } else {
            $packageId = $request->package_id;
        }

        $newLineRequest->name = $request->name;
        $newLineRequest->father_name = $request->father_name;
        $newLineRequest->mother_name = $request->mother_name;
        $newLineRequest->phone = $request->phone;
        $newLineRequest->alt_phone = $request->alt_phone;
        $newLineRequest->nid = $request->nid;
        $newLineRequest->billing_date = $request->billing_date;
        $newLineRequest->address = $request->address;
        $newLineRequest->pop_id = $request->pop_id;
        $newLineRequest->package_id = $packageId;
        if ($pop->subreseller == 'yes') {
            $newLineRequest->sub_package_id = $request->package_id;
        } else {
            $newLineRequest->sub_package_id = null;
        }
        $newLineRequest->otc = $request->otc;
        $newLineRequest->fiver_miter = $request->fiber_meter;
        $newLineRequest->lat = $request->latitude;
        $newLineRequest->long = $request->longitude;
        $newLineRequest->save();


        Toastr::success('New Line Request updated successfully');
        return redirect()->route('new-line-request.index');
    }

    /**
     * Update only status of the specified resource.
     */
    public function updateStatus(Request $request, NewLineRequest $new_line_request)
    {
        $rules = [
            'status' => 'required',
        ];
        if ($request->status == 'cancelled') {
            $rules['confirm_line_request_cancel_remarks'] = 'required|string|max:2000';
        }
        $request->validate($rules);

        if ($request->status == 'cancelled') {
            $new_line_request->line_status = 'new_request';
            $new_line_request->marketing_done = null;
            $new_line_request->confirm_line_request_cancel_remarks = $request->confirm_line_request_cancel_remarks;
        } else {
            $new_line_request->confirm_line_request_cancel_remarks = null;
        }

        $new_line_request->status = $request->status;
        $new_line_request->save();

        if ($request->wantsJson() || $request->ajax()) {
            return response()->json(['success' => true, 'message' => 'Status updated']);
        }

        Toastr::success('Status updated');
        return redirect()->route('new-line-request.index');
    }

    /**
     * Update delivery date of the specified resource.
     */
    public function updateDeliveryDate(Request $request, NewLineRequest $new_line_request)
    {
        $request->validate([
            'delivery_date' => 'required|date',
        ]);

        $new_line_request->delivery_date = Carbon::parse($request->delivery_date)->startOfDay();
        $new_line_request->save();

        Toastr::success('Delivery date updated');
        return redirect()->route('new-line-request.index');
    }

    /**
     * Update free days of the specified resource.
     */
    public function updateFreeDays(Request $request, NewLineRequest $new_line_request)
    {
        $companyInfo = CompanyInformation::latest()->first();
        $max_day_setting = $companyInfo ? ($companyInfo->max_free_day ?? 0) : 0;
        $request->validate([
            'free_days' => 'required|integer|min:0|max:' . (int) $max_day_setting,
        ], [
            'free_days.max' => 'Free days cannot exceed ' . $max_day_setting . '.',
        ]);

        $new_line_request->free_days = $request->free_days;
        $new_line_request->save();

        Toastr::success('Free day updated');
        return redirect()->route('new-line-request.index');
    }

    /**
     * Update only remarks of the specified resource.
     */
    public function updateRemark(Request $request, NewLineRequest $new_line_request)
    {
        // dd($request->all(), $new_line_request);
        $request->validate([
            'remarks' => 'nullable|string',
        ]);

        $newLineRequestRemark = new NewLineRequestRemarks();
        $newLineRequestRemark->new_line_request_id = $new_line_request->id;
        $newLineRequestRemark->remarks = $request->remarks;
        $newLineRequestRemark->created_by = auth()->user()->id;
        $newLineRequestRemark->save();

        Toastr::success('Remarks updated');
        return redirect()->route('new-line-request.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\NewLineRequest  $newLineRequest
     * @return \Illuminate\Http\Response
     */
    public function destroy(NewLineRequest $newLineRequest)
    {
        //
    }

    public function newLineRequestRemarks($new_line_request)
    {
        // dd($new_line_request);
        $remarks = NewLineRequestRemarks::where('new_line_request_id', $new_line_request)
            ->orderBy('created_at', 'asc')
            ->get();

        return view('clients.newclient.remarks', [
            'page_title' => 'Remarks List For New Line Request',
            'new_line_request' => $new_line_request,
            'remarks' => $remarks,
        ]);
    }

    public function newIndex(Request $request)
    {
        if (!auth()->user()->can('new-line-request-index')) {
            Toastr::error('You are not authorized to access this page!');
            return redirect()->back();
        }

        $pops          = Pop::all();
        $client_source = ClientSource::orderBy('order', 'asc')->orderBy('name', 'asc')->get();

        // --- Build base query ---
        $query = NewLineRequest::with([
            'pop',
            'package',
            'user',
            'subPackage',
            'ClientSource',
            'lockBy',
            'assign',
        ])->where('line_status', 'new_request');

        // --- Apply filters ---
        $query
            ->when($request->filled('id'),                fn($q) => $q->where('id', $request->id))
            ->when($request->filled('name'),              fn($q) => $q->where('name', 'like', '%' . $request->name . '%'))
            ->when($request->filled('father_name'),       fn($q) => $q->where('father_name', 'like', '%' . $request->father_name . '%'))
            ->when($request->filled('mother_name'),       fn($q) => $q->where('mother_name', 'like', '%' . $request->mother_name . '%'))
            ->when($request->filled('address'),           fn($q) => $q->where('address', 'like', '%' . $request->address . '%'))
            ->when($request->filled('pop_id'),            fn($q) => $q->where('pop_id', $request->pop_id))
            ->when($request->filled('package_id'),        fn($q) => $q->where('package_id', $request->package_id))
            ->when($request->filled('otc'),               fn($q) => $q->where('otc', $request->otc))
            ->when($request->filled('fiber_meter'),       fn($q) => $q->where('fiber_meter', $request->fiber_meter))
            ->when($request->filled('mobile_number'),     fn($q) => $q->where('phone', 'like', '%' . $request->mobile_number . '%'))
            ->when($request->filled('alt_mobile_number'), fn($q) => $q->where('alt_phone', 'like', '%' . $request->alt_mobile_number . '%'))
            ->when($request->filled('latitude'),          fn($q) => $q->where('lat', $request->latitude))
            ->when($request->filled('longitude'),         fn($q) => $q->where('long', $request->longitude))
            ->when($request->filled('status'),            fn($q) => $q->where('status', $request->status))
            ->when($request->filled('nid'),               fn($q) => $q->where('nid', 'like', '%' . $request->nid . '%'))
            ->when($request->filled('billing_cycle'),     fn($q) => $q->where('billing_date', $request->billing_cycle))
            ->when($request->filled('division_id'),       fn($q) => $q->where('division_id', $request->division_id))
            ->when($request->filled('district_id'),       fn($q) => $q->where('district_id', $request->district_id))
            ->when($request->filled('upazila_id'),        fn($q) => $q->where('upazila_id', $request->upazila_id))
            ->when($request->filled('thana_id'),          fn($q) => $q->where('thana_id', $request->thana_id))
            ->when($request->filled('customer_status'),   fn($q) => $q->where('customer_status', $request->customer_status))
            ->when($request->filled('email'),             fn($q) => $q->where('email', 'like', '%' . $request->email . '%'))
            ->when($request->filled('free_days'),         fn($q) => $q->where('free_days', $request->free_days))
            ->when($request->filled('divice_uses'),       fn($q) => $q->where('divice_uses', $request->divice_uses))
            ->when($request->filled('client_source_id'),  fn($q) => $q->where('source_id', $request->client_source_id))
            ->when($request->filled('multi_router'),      fn($q) => $q->where('multi_router', $request->multi_router))
            ->when($request->filled('done_by'),           fn($q) => $q->where('marketing_done_by', $request->done_by))
            ->when($request->filled('assigned_to'),       fn($q) => $q->where('assigned_to', $request->assigned_to))
            ->when($request->filled('support_done'),      fn($q) => $q->whereNull('support_done'))
            ->when($request->filled('marketing_done_status'), fn($q) => $q->where('marketing_done', $request->marketing_done_status))
            ->when($request->filled('created_by'), function ($q) use ($request) {
                if ($request->created_by === 'Website') {
                    $q->whereNull('created_by');
                } else {
                    $q->where('created_by', $request->created_by);
                }
            })
            ->when(
                $request->filled('survey_status'),
                fn($q) => $q->where('survey_status', $request->survey_status),
                fn($q) => $q->where(fn($q2) => $q2->where('survey_status', '!=', 'Not Coverage')->orWhereNull('survey_status'))
            )
            ->when($request->filled('created_by_name'), function ($q) use ($request) {
                $q->whereHas('user', fn($u) => $u->where('name', 'like', '%' . $request->created_by_name . '%'));
            })
            ->when($request->filled('follow_up_date'), function ($q) use ($request) {
                $q->whereDate('follow_up_date', Carbon::parse($request->follow_up_date)->format('Y-m-d'));
            })
            ->when($request->filled('confirm_activation_date'), function ($q) use ($request) {
                $q->whereDate('confirm_activation_date', Carbon::parse($request->confirm_activation_date)->format('Y-m-d'));
            })
            ->when($request->filled('from_date') && $request->filled('to_date'), function ($q) use ($request) {
                $q->whereBetween('created_at', [
                    Carbon::parse($request->from_date)->startOfDay(),
                    Carbon::parse($request->to_date)->endOfDay(),
                ]);
            })
            ->when($request->filled('done_status'), function ($q) use ($request) {
                if ($request->done_status === 'Yes') {
                    $q->whereNotNull('marketing_done_by');
                } elseif ($request->done_status === 'Pending') {
                    $q->whereNull('marketing_done_by')->whereHas('latestEditLog');
                } else {
                    $q->whereNull('marketing_done_by');
                }
            }, fn($q) => $q->whereNull('marketing_done_by'))
            ->when($request->filled('assigned_status'), function ($q) use ($request) {
                if ($request->assigned_status === 'Yes') {
                    $q->whereNotNull('assigned_to');
                } else {
                    $q->whereNull('assigned_to');
                }
            })
            ->when($request->filled('lock_status'), function ($q) use ($request) {
                if ($request->lock_status === 'Yes') {
                    $q->whereNotNull('lock_by');
                } else {
                    $q->whereNull('lock_by');
                }
            })
            ->when($request->filled('to_follow_up_pending'), function ($q) use ($request) {
                if ($request->to_follow_up_pending === 'Yes') {
                    $q->whereNotNull('follow_up_date')->where('follow_up_date', '<=', Carbon::today()->format('Y-m-d'));
                } else {
                    $q->whereNull('follow_up_date');
                }
            });

        // --- Detect if any filter is active ---
        $filterKeys = [
            'id',
            'name',
            'father_name',
            'mother_name',
            'address',
            'pop_id',
            'package_id',
            'otc',
            'fiber_meter',
            'mobile_number',
            'alt_mobile_number',
            'latitude',
            'longitude',
            'created_by',
            'status',
            'nid',
            'billing_cycle',
            'division_id',
            'district_id',
            'upazila_id',
            'thana_id',
            'customer_status',
            'email',
            'free_days',
            'divice_uses',
            'client_source_id',
            'multi_router',
            'survey_status',
            'created_by_name',
            'done_status',
            'done_by',
            'support_done',
            'assigned_status',
            'lock_status',
            'assigned_to',
            'follow_up_date',
            'confirm_activation_date',
            'marketing_done_status',
            'to_follow_up_pending',
            'from_date',
            'to_date',
        ];

        $hasFilters = collect($filterKeys)->some(fn($k) => $request->filled($k));

        // --- Execute query based on special filters or regular filters ---
        if ($request->filled('ten_minutes_over') || $request->filled('sixty_minutes_over')) {

            $minutes = $request->filled('sixty_minutes_over') ? 60 : 10;
            $start   = today()->startOfDay();
            $end     = today()->endOfDay();

            $allToday = NewLineRequest::with([
                'pop',
                'package',
                'user',
                'subPackage',
                'ClientSource',
                'lockBy',
                'assign',
                'latestEditLog',
                'remarksList',
            ])
                ->whereBetween('created_at', [$start, $end])
                ->orderBy('id', 'desc')
                ->get();

            $newLineRequests = $allToday->filter(
                fn($item) => $item->latestEditLog === null
                    && $item->remarksList->isEmpty()
                    && $item->created_at->diffInMinutes(now()) > $minutes
            )->values();
        } elseif ($request->filled('fourtyEighthPending') && $request->filled('logged_user_id')) {

            $all_collection = NewLineRequest::with([
                'pop',
                'user',
                'assign',
                'ClientSource',
                'latestEditLog',
            ])
                ->where(function ($q) {
                    $q->where('survey_status', '!=', 'Not Coverage')
                        ->orWhereNull('survey_status');
                })
                ->whereNull('marketing_done_by')
                ->where('line_status', 'new_request')
                ->get();

            $newLineRequests = $all_collection
                ->filter(fn($item) => $item->latestEditLog !== null)
                ->filter(fn($item) => $item->latestEditLog->created_at->diffInHours(now()) > 48)
                ->filter(fn($item) => $item->latestEditLog->edit_by == $request->logged_user_id)
                ->sortByDesc('id')
                ->take(500)
                ->values();
        } elseif ($request->filled('survey_coverage_but_canceled')) {

            $newLineRequests = NewLineRequest::with([
                'pop',
                'package',
                'user',
                'subPackage',
                'ClientSource',
                'lockBy',
                'assign',
            ])
                ->where('marketing_done', 5)
                ->where('survey_status', 'Coverage')
                ->orderBy('id', 'desc')
                ->limit(500)
                ->get();
        } elseif (!$hasFilters) {

            $followUpIds = (clone $query)
                ->whereNotNull('follow_up_date')
                ->where('follow_up_date', '<=', Carbon::today()->format('Y-m-d'))
                ->pluck('id');

            $followLines = (clone $query)
                ->whereIn('id', $followUpIds)
                ->orderBy('follow_up_date', 'asc')
                ->get()
                ->each(fn($item) => $item->is_followup = true);

            $mainResults = (clone $query)
                ->whereNotIn('id', $followUpIds)
                ->orderBy('id', 'desc')
                ->limit(300)
                ->get()
                ->each(fn($item) => $item->is_followup = false);

            $newLineRequests = $followLines->concat($mainResults);
        } else {

            $newLineRequests = $query
                ->orderBy('id', 'desc')
                ->limit(500)
                ->get();
        }

        // --- Excluded system/payment users ---
        $excludedEmails = [
            'admin@billingfix.xyz',
            'soiket@outlook.com',
            'support@yetfix.com',
            'limitedyetfix@gmail.com',
            'Nagad-Online@demo.com',
            'user@nagad.com',
            'Bkash-Online@demo.com',
            'account@bkash.com',
            'user@bkash.com',
            'user@bkashcom',
            'user@nagadcom',
            'SSL-Commerz@demo.com',
            'user@upay.com',
        ];

        return view('clients.newclient.newLineRequestIndex', [
            'page_title'              => 'New Line Request',
            'lists'                   => $newLineRequests,
            'pops'                    => $pops,
            'client_source'           => $client_source,
            'users'                   => User::where('isActive', 'yes')->whereNotIn('email', $excludedEmails)->get(),
            'marketingStatus'         => MarketingDone::where('status', 'Active')->get(),
            'cancelReasons'           => CancelReason::where('status', 'Active')->get(),
            'employees'               => Employee::where('status', 'active')->orderBy('name', 'asc')->get(),
            'packages'                => Packages::get(),
            'divisions'               => Division::get(),
            'devices'                 => SmartDivice::get(),
            'marketing_done_statuses' => MarketingDone::where('status', 'Active')->get(),
        ]);
    }
    public function newCreate()
    {
        $client_source = ClientSource::orderBy('order', 'asc')->orderBy('name', 'asc')->get();

        return view('clients.newclient.newcreate', [
            'page_title' => 'Create New Line Request',
            'client_source' => $client_source,
        ]);
    }

    public function newStore(Request $request)
    {
        $request->validate([
            'mobile' => 'required|digits:11',
            'source_id' => 'required|exists:client_sources,id',
        ], [
            'mobile.required' => 'Mobile number is required.',
            'mobile.digits' => 'Mobile number must be exactly 11 digits.',
            'source_id.required' => 'Please select a source.',
            'source_id.exists' => 'Selected source is invalid.',
        ]);

        $new_line = new NewLineRequest();
        $new_line->phone = $request->mobile;
        $new_line->source_id = $request->source_id;
        $new_line->created_by = auth()->user()->id;
        $new_line->status = 'pending';
        $new_line->line_status = 'new_request';
        $new_line->customer_status = 'Survey';
        $new_line->save();

        Toastr::success('New Line Request created successfully');
        return redirect()->route('newline.newIndex');
    }


    public function newInformation($confirm_line = null, $id)
    {
        $new_line_request = NewLineRequest::with('supportDoneByUser')->find($id);
        $confday = config('app.billing_cycle');
        $pop = Pop::get();
        $smartDevice = SmartDivice::where('status', 'Active')->get();
        $newLineRequestSmartDevices = NewLineRequestSmartDevice::where('new_line_request_id', $id)->get()->pluck('status', 'smart_device_id')->toArray();
        $divisions = DB::table('divisions')->orderBy('name', 'asc')->get();
        $marketingStatus = MarketingDone::where('status', 'Active')->get();
        $companyInfo = CompanyInformation::latest()->first();
        $multirouterYesMessage = $companyInfo ? ($companyInfo->multirouter_yes_message ?? '') : '';

        $max_free_day = $companyInfo ? ($companyInfo->max_free_day ?? 0) : 0;

        $last_note = optional(NewLineRequestRemarks::where('new_line_request_id', $id)->orderBy('id', 'desc')->first())->remarks ?? '';

        $old_division = $new_line_request->division_id;
        $old_district = $new_line_request->district_id;

        $old_package_id = null;
        $packages = [];

        if ($new_line_request->pop_id) {
            $thisPop = Pop::with('reseller')->find($new_line_request->pop_id);
            if ($thisPop->subreseller == 'yes') {
                $subPackageList = explode(',', $thisPop->sub_package_list);
                $packages = SubPackage::select('id', 'name as name')
                    ->whereIn('id', $subPackageList)
                    ->get();
                $old_package_id = $new_line_request->sub_package_id;
            } else {
                $packageList = explode(',', $thisPop->reseller->package_list);
                $packages = Packages::select('id', 'package_name as name')
                    ->whereIn('id', $packageList)
                    ->get();
                $old_package_id = $new_line_request->package_id;
            }
        }


        if ($old_division) {
            $districts = District::where('division_id', $old_division)->get();
        } else {
            $districts = [];
        }

        if ($old_district) {
            $upazilas = Upazila::where('district_id', $old_district)->get();
        } else {
            $upazilas = [];
        }

        $old_upazila = $new_line_request->upazila_id;

        if ($old_upazila) {
            $thanas = Thana::where('upazila_id', $old_upazila)->get();
        } else {
            $thanas = [];
        }

        // dd($thanas);

        $new_line_request->lock_by = auth()->user()->id;

        if ($new_line_request->assigned_to == null) {
            $new_line_request->assigned_to = auth()->user()->id;
        }
        $new_line_request->save();
        $confday = config('app.billing_cycle');
        $employees =  Employee::where('status', 'active')->orderBy('name', 'asc')->get();

        return view('clients.newclient.newinformation', [
            'page_title' => 'Add Information for New Line Request',
            'new_line_request' => $new_line_request,
            'confday' => $confday,
            'pops' => $pop,
            'divisions' => $divisions,
            'smartDevice' => $smartDevice,
            'newLineRequestSmartDevices' => $newLineRequestSmartDevices,
            'marketingStatus' => $marketingStatus,
            'multirouterYesMessage' => $multirouterYesMessage,
            'last_note' => $last_note,
            'districts' => $districts,
            'upazilas' => $upazilas,
            'cancelReasons' => CancelReason::where('status', 'Active')->get(),
            'max_free_day' => $max_free_day,
            'confday' => $confday,
            'thanas' => $thanas,
            'packages' => $packages,
            'old_package_id' => $old_package_id,
            'confirm_line' => $confirm_line,
            'marketingEmployee' => $employees,
        ]);
    }

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


        if (isset($request->free_days)) {
            $max_day_setting = siteinfo()->max_free_day ?? 0;

            if ($request->free_days > $max_day_setting) {
                Toastr::error('Free day is not permitted.', 'error');
                return redirect()->back()->withInput();
            }
        }

        try {
            DB::beginTransaction();




            $new_line = NewLineRequest::with('smartDevices', 'surveyCancelReason')->find($id);

            $old_data = NewLineRequest::with('smartDevices', 'surveyCancelReason')->find($id);

            if ($request->pop_id || $new_line->pop_id) {
                $pop = Pop::find($request->pop_id ?? $new_line->pop_id);
                if ($pop->subreseller == 'yes') {
                    $subPackageId = SubPackage::where('id', $request->package_id ?? $new_line->sub_package_id)->first();
                    $packageId = $subPackageId->package_id ?? null;
                } else {
                    $packageId = $request->package_id ?? $new_line->package_id;
                }
            } else {
                $packageId = null;
            }

            $new_line->name = $request->name;
            $new_line->father_name = $request->father_name;
            $new_line->mother_name = $request->mother_name;
            $new_line->phone = $request->phone;
            $new_line->alt_phone = $request->alt_phone;
            $new_line->billing_date = $request->billing_date;
            $new_line->nid = $request->nid;
            $new_line->division_id = $request->division;
            $new_line->district_id = $request->district;
            $new_line->upazila_id = $request->upazilla;
            $new_line->thana_id = $request->thana_id;
            $new_line->address = $request->address;
            $new_line->pop_id = $request->pop_id ?? null;
            $new_line->package_id = $packageId;
            if ($request->pop_id) {
                if ($pop->subreseller == 'yes') {
                    $new_line->sub_package_id = $subPackageId->id ?? null;
                } else {
                    $new_line->sub_package_id = null;
                }
            }



            $new_line->email = $request->email;
            $new_line->free_days = $request->free_days;
            $new_line->divice_uses = $request->device_uses;
            $new_line->multi_router = $request->multi_router;
            $new_line->multi_router_remarks = $request->multi_router_remarks;

            $new_line->survey_status = $request->survey;
            $new_line->survey_remarks = $request->survey_remarks;

            if ($request->survey) {
                $new_line->surveyed_by = auth()->user()->id;
                if ($request->survey == "Not Coverage") {
                    NewLineRequestSurveyCancelReason::where('new_line_request_id', $id)->delete();
                    // dd($request->survey_cancel_reasons);
                    foreach ($request->survey_cancel_reasons as $key => $cancelReason) {
                        NewLineRequestSurveyCancelReason::create([
                            'new_line_request_id' => $id,
                            'cancel_reason_id' => $key,
                        ]);
                    }
                }
            }

            $new_line->tentative_activation_date = $request->tentative_activation_date;
            $new_line->confirm_activation_date = $request->confirm_activation_date;
            $new_line->follow_up_date = $request->filled('follow_up_date')
                ? Carbon::parse($request->follow_up_date)->format('Y-m-d H:i:s')
                : null;


            $new_line->otc = $request->otc;
            $new_line->fiver_miter = $request->fiber_meter;
            $new_line->lat = $request->latitude;
            $new_line->long = $request->longitude;
            $new_line->long = $request->longitude;
            // $new_line->marketing_done = $request->marketing_status_id;
            // $new_line->marketing_done_by = auth()->user()->id;
            // $new_line->customer_status = 'Marketing';


            if ($request->tentative_activation_date) {
                $new_line->customer_status = 'Tentative activation date';
            }

            if ($request->confirm_activation_date && $request->multi_router != 'Yes') {
                $new_line->customer_status = 'Confirm activation date';
            }

            // if ($request->marketing_status_id == 1) {
            //     $new_line->line_status = 'confirm_request';
            // }

            $new_line->lock_by = null;



            if ($request->marketing_employee && auth()->user()->can('change-marketing-employee')) {
                $new_line->marketing_user_id = $request->marketing_employee;
            }

            $new_line->save();
            if ($request->notes) {
                $newLineRequestRemark = new NewLineRequestRemarks();
                $newLineRequestRemark->new_line_request_id = $new_line->id;
                $newLineRequestRemark->remarks = $request->notes;
                $newLineRequestRemark->created_by = auth()->user()->id;
                $newLineRequestRemark->save();
            }
            NewLineRequestSmartDevice::where('new_line_request_id', $new_line->id)->delete();

            $smartDevices = SmartDivice::where('status', 'Active')->get();
            foreach ($smartDevices as $device) {
                $status = $request->input('smart_devices.' . $device->id, 'No');
                $smartDeviceRow = new NewLineRequestSmartDevice();
                $smartDeviceRow->new_line_request_id = $new_line->id;
                $smartDeviceRow->smart_device_id = $device->id;
                $smartDeviceRow->status = in_array($status, ['Yes', 'No']) ? $status : 'No';
                $smartDeviceRow->save();
            }
            $new_info = NewLineRequest::with('smartDevices', 'surveyCancelReason')->find($id);
            $type = 'new_line_request_update';

            // dd($new_info);
            (new EditLogHistory)->editLogSave($new_line, $type, $old_data, $new_info);

            DB::commit();
            Cache::forget("route_lock_{$id}");


            Toastr::success('New Line Information updated successfully');
            if ($request->confirm_line == "confirm-line") {
                return redirect()->route('new-line-request.index')->with('success', 'New Line Information updated successfully');
            } else {
                return redirect()->route('newline.newIndex');
            }
        } catch (\Exception $e) {
            DB::rollBack();
            Cache::forget("route_lock_{$id}");

            Toastr::error('Something went wrong.' . $e->getMessage());
            return redirect()->back()->withInput();
        }
    }

    public function newSupport(Request $request, $id)
    {
        DB::beginTransaction();
        try {
            // dd($request->all());
            $old_data = NewLineRequest::with('smartDevices', 'surveyCancelReason')->find($id);

            $new_line_request = NewLineRequest::find($id);

            $new_line_request->support_done = 1;

            $new_line_request->support_remarks = $request->support_remarks;
            $new_line_request->support_done_by = auth()->user()->id;


            $new_line_request->customer_status = 'Confirm activation date';
            $new_line_request->support_cancel_status_for_multi_router = $request->support_cancel_status_for_multi_router;

            if ($request->support_cancel_status_for_multi_router == 'Yes') {
                $new_line_request->marketing_done_by = auth()->user()->id;
            }

            $new_line_request->save();

            $new_data = NewLineRequest::with('smartDevices', 'surveyCancelReason')->find($id);
            $type = 'new_line_request_update';
            (new EditLogHistory)->editLogSave($new_line_request, $type, $old_data, $new_data);

            DB::commit();

            Toastr::success('Support Done Successfully');
            return redirect()->back();
        } catch (Exception $e) {
            DB::rollBack();
            Toastr::error('Something went wrong.' . $e->getMessage());
            return redirect()->back()->withInput();
        }
    }

    /**
     * Update survey status and remarks via AJAX.
     */
    public function updateSurvey(Request $request)
    {
        $request->validate([
            'id' => 'required|integer|exists:new_line_requests,id',
            'survey' => 'nullable|string',
            'survey_remarks' => 'nullable|string',
        ]);

        $newLine = NewLineRequest::findOrFail($request->id);
        $newLine->survey_status = $request->survey;
        $newLine->survey_remarks = $request->survey_remarks;
        $newLine->save();

        return response()->json([
            'success' => true,
            'message' => 'Survey updated successfully',
        ]);
    }

    public function updateSurveyFromModal(Request $request)
    {
        DB::beginTransaction();
        try {

            $request->validate([
                'id' => 'required|integer|exists:new_line_requests,id',
                'survey' => 'required|string',
                'survey_remarks' => 'required|string',
            ]);

            $old_data = NewLineRequest::with('surveyCancelReason')->select('id', 'survey_status', 'survey_remarks', 'surveyed_by', 'customer_status')->find($request->id);

            $newLine = NewLineRequest::find($request->id);
            $newLine->survey_status = $request->survey;
            $newLine->survey_remarks = $request->survey_remarks;
            $newLine->surveyed_by = auth()->user()->id;
            $newLine->customer_status = 'Marketing';
            $newLine->save();

            if (isset($request->survey_cancel_reasons)) {
                NewLineRequestSurveyCancelReason::where('new_line_request_id', $request->id)->delete();
                foreach ($request->survey_cancel_reasons as $cancelReason) {
                    NewLineRequestSurveyCancelReason::create([
                        'new_line_request_id' => $request->id,
                        'cancel_reason_id' => $cancelReason,
                    ]);
                }
            }

            $new_data = NewLineRequest::with('surveyCancelReason')->select('id', 'survey_status', 'survey_remarks', 'surveyed_by', 'customer_status')->find($request->id);
            $type = 'new_line_request_update';

            // dd($old_data,$new_info);
            (new EditLogHistory)->editLogSave($newLine, $type, $old_data, $new_data);

            DB::commit();

            return response()->json([
                'error' => false,
                'message' => 'Survey updated successfully',
            ]);
        } catch (Exception $e) {

            DB::rollBack();
            return response()->json([
                'error' => true,
                'message' => 'Survey updated Failed ' . $e->getMessage(),
            ]);
        }
    }
}
