<?php

namespace App\Http\Controllers;

use App\care_of_detail;
use App\City;
use App\Customer;
use App\countries;
use App\CustomerAccount;
use App\TransactionAccount;
use App\Voucher;
use App\VouchersUniqueNumber;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;

class CustomerController extends Controller
{
    protected $role_id;

    protected string $module = 'Customers';

    public function __construct()
    {
        $module = $this->module;

        $this->middleware("permission:$module list")->only(['index']);
        $this->middleware("permission:$module view")->only(['show']);
        $this->middleware("permission:$module add")->only(['create', 'store']);
        $this->middleware("permission:$module edit")->only(['edit', 'update']);
        $this->middleware("permission:$module delete")->only(['destroy']);
    }
    // public function __construct()
    // {
    //     $this->middleware('auth');
    //            $this->middleware(function ($request, $next) {
    //                $this->role_id = Auth::user()->role_id;
    //             //    $slug_filter = preg_replace('/[0-9]+/', '', $request->path());
    //             //    $slug_filter = preg_replace('/[0-9]+/', '', $request->path());
    //             $ex = explode('/',$request->path());
    //             if(count($ex)>=3){
    //                 $sliced = array_slice($ex, 0, -1);

    //             }else{
    //                 $sliced = $ex;
    //             }

    //             $string = implode("/", $sliced);
    //         //                 dd($string);
    //                if (checkConstructor($this->role_id, count($ex)>=3 ? $string.'/': $string) == 1) {
    //                    return $next($request);
    //                }else if(strpos($request->path(), 'store') !== false){
    //                    return $next($request);
    //                }else if(strpos($request->path(), 'update') !== false){
    //                    return $next($request);
    //                } else {
    //                    abort(404);
    //                }
    //            });
    // }
    /**
     * Display a listing of the resource.
     */

    public function customer_search(Request $request, $query = null)
    {
        if ($request->ajax()) {
            $bilal = $request->page;
            $artilces = " ";

            if ($query != null && $query != "") {
                // $artilces = '';
                $customers = Customer::orderBy('id_customers')->where('customer_name', 'LIKE', "%" . $query . "%")->orWhere('customer_cell', '=',  $query)->paginate(20);
                // dd($customers);
            } else {
                $artilces = " ";
            }

            if (isset($customers)) {
                foreach ($customers as $result) {
                    $artilces .= '<div id="get_cus_details" data-id="' . $result->id_customers . '" onClick="CusDetails()" class="az-contact-item mt-3 clickable-data"><div class="az-img-user"><img src="' . asset('img/default_user.png') . '" alt=""></div><div class="az-contact-body"><h6>' . $result->customer_name . '</h6><span class="phone">' . $result->customer_cell . '</span></div></div>';
                }
            }
            return $artilces;
        }
    }

    public function index()
    {
        $customers = Customer::all();
        return view('customers.index', compact('customers'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function getData(Request $request)
    {

        // Define the number of records to load
        $perPage = 1;

        // Retrieve data based on the scroll position
        $data = Customer::skip($perPage)
            ->take($perPage)
            ->get();
        // Return the data as JSON response
        return response()->json($data);
    }

    public function create(Request $request)
    {
        $cities = City::all();
        $countries = countries::all();
        // $accounts = TransactionAccount::where('transaction_account_name', '=',  'Receivables From Customer', '&&' ,'W. Tax for Customers')->get();
        $accounts = TransactionAccount::whereIn('transaction_account_name', [
            'Receivables From Customer',
            'W. Tax for Customers'
        ])->get();
        $sale_persons = \App\User::select('users.name', 'users.id')->where('role_id', '=', 6)->get()->toArray();
        //        dd($sale_persons);
        return view('customers.create', compact('countries', 'sale_persons', 'accounts', 'cities'));
    }

    public function getCity(Request $request)
    {
        if (is_numeric($request->country_id)) {
            $countries = countries::where('id_countries', $request->country_id)->first();
            $data['cities'] = \App\cities::where("country_id", $countries->id_countries)->get();
        } else {
            $countries = countries::where('name', $request->country_id)->first();
            $data['cities'] = \App\cities::where("country_id", $countries->id_countries)->get();
        }


        return response()->json($data);
        // $cities = "";
        // foreach ($data['cities'] as $key => $value) {
        //     $cities .= "<option " . $value->id . " >" . $value->name . "</option>";
        // }
        // return $cities;
    }

    public function get_customer_details(Request $request)
    {
        $data = Customer::where('id_customers', $request->id)->first();
        echo '<h5>ID: <span style="text-decoration: underline;">' . $data->id_customers . '<input type="hidden" value="' . $data->id_customers . '" name="searched_customer_id"/></span></h5>
            <h5>Customer: <span style="text-decoration: underline;">' . $data->customer_name . '</span></h5>
            <p>Contact# <span style="text-decoration: underline;">' . $data->customer_cell . '</span></p>
                                <p>Email: <span style="text-decoration: underline;">' . $data->customer_email . '</span></p>

                                <p>Last Inquiry# <span style="text-decoration: underline;"></span></p>';
    }
    /**
     * Store a newly created resource in storage.
     */

    public function store(Request $request)
    {
        // Validate incoming request data

        $validatedData = $request->validate([
            'customer_name' => 'required|string|max:255|unique:customers,customer_name',
            'customer_name_urdu' => 'nullable|string|max:255|unique:customers,customer_name_urdu',
            'customer_email' => 'nullable|email|max:255',
            'customer_cell' => 'nullable|string|max:255',
            'whatsapp_number' => 'nullable|string|max:255',
            'customer_ope_bal_dr' => 'nullable|string|max:255',
            'customer_ope_bal_cr' => 'nullable|string|max:15',
            'customer_address' => 'nullable|string|max:255',
            'city' => 'nullable',
            'customer_address_urdu' => 'nullable|url|max:255',
            'customer_status' => 'nullable|in:0,1',
            'customer_reference' => 'nullable|numeric|between:0,9999999999999.99',
            'customer_remarks' => 'nullable|string',
            'blance_cr' => 'nullable|string|max:255',
            'customer_ope_date' => 'nullable|string|max:255',
        ]);
        // Create new Supplier
        $Customer = new Customer();
        $Customer->business_id = 1;
        $Customer->customer_name = $validatedData['customer_name'];
        $Customer->customer_name_urdu = $validatedData['customer_name_urdu'] ?? null;
        $Customer->customer_email = $validatedData['customer_email'] ?? null;
        $Customer->customer_cell = $validatedData['customer_cell'] ?? null;
        $Customer->whatsapp_number = $validatedData['whatsapp_number'] ?? null;
        $Customer->customer_ope_bal_dr = $validatedData['customer_ope_bal_dr'] ?? null;
        $Customer->customer_ope_bal_cr = $validatedData['customer_ope_bal_cr'] ?? null;
        $Customer->customer_ope_date = $validatedData['customer_ope_date'] ?? null;
        $Customer->customer_address = $validatedData['customer_address'] ?? null;
        $Customer->customer_address_urdu = $validatedData['customer_address_urdu'] ?? null;
        $Customer->customer_city = $validatedData['city'] ?? null;
        $Customer->customer_reference = $validatedData['customer_reference'] ?? null;
        $Customer->customer_remarks = $validatedData['customer_remarks'] ?? null;
        $Customer->customer_remarks_urdu = $validatedData['customer_remarks_urdu'] ?? null;
        $Customer->status = $request->customer_status ?? 0;
        $Customer->created_by = auth()->user()->id;

        if (!empty($request->customer_image)) {
            $file = $request->file('customer_image');
            $extension = $file->getClientOriginalExtension();
            $filename = time() . '.' . $extension;
            $file->move(public_path('uploads/customer_images/'), $filename);
            $data['image'] = $filename;
            $Customer->customer_image = $data['image'];
        }

        $cus_id = Customer::max('id_customers');
        $Customer->save();

        if (!empty($validatedData['customer_ope_bal_dr']) || !empty($validatedData['customer_ope_bal_cr'])) {

            $customerAccount = CustomerAccount::where('customers_id', $Customer->id_customers)->first();

            if ($customerAccount) {
                // Update existing customer account
                if (!empty($validatedData['customer_ope_bal_dr']) || !empty($validatedData['customer_ope_bal_cr'])) {
                    $customerAccount->debit += $validatedData['customer_ope_bal_dr'] ?? 0; // Add debit if present
                    $customerAccount->credit += $validatedData['customer_ope_bal_cr'] ?? 0; // Add credit if present
                    $customerAccount->balance = $customerAccount->debit - $customerAccount->credit; // Calculate balance
                    $customerAccount->save(); // Save changes
                }
            } else {
                // Create a new customer account record
                CustomerAccount::create([
                    'customers_id' => $Customer->id_customers,
                    'account_name' => 'Receivables From Customer',
                    'account_no' => '22',
                    'debit' => $validatedData['customer_ope_bal_dr'] ?? 0, // Set debit or 0 if not present
                    'credit' => $validatedData['customer_ope_bal_cr'] ?? 0, // Set credit or 0 if not present
                    'balance' => (float)str_replace(',', '', $validatedData['customer_ope_bal_dr'] ?? 0) - (float)str_replace(',', '', $validatedData['customer_ope_bal_cr'] ?? 0),

                ]);
            }

            // Generate unique voucher number

            $uniqueVoucherNumber = 'JV-' . str_pad(rand(0, 99999), 5, '0', STR_PAD_LEFT);

            // Create a new VouchersUniqueNumber record
            $voucherUniqueNumber = new VouchersUniqueNumber();
            $voucherUniqueNumber->voucher_type = 'Journal Voucher';
            $voucherUniqueNumber->voucher_number = $uniqueVoucherNumber;
            $voucherUniqueNumber->save();
            // Create vouchers based on the presence of debit and credit values

            // Voucher for Debit
            if (!empty($validatedData['customer_ope_bal_dr'])) {

                $voucherDebit = new Voucher();
                $voucherDebit->vouchers_unique_number_id = $voucherUniqueNumber->id_vouchers_unique_number;
                $voucherDebit->date = $validatedData['customer_ope_date'];
                $voucherDebit->transaction_acc_no = '22';
                $voucherDebit->transaction_acc_name = 'Receivables From Customer';
                $voucherDebit->business_partner_type = 'Customer';
                $voucherDebit->partner_name = $validatedData['customer_name'];
                $voucherDebit->debit = $validatedData['customer_ope_bal_dr'];
                $voucherDebit->credit = 0;
                // dd($voucherDebit);
                $voucherDebit->save();
            }

            // Voucher for Credit
            if (!empty($validatedData['customer_ope_bal_cr'])) {
                $uniqueVoucherNumber = 'JV-' . str_pad(rand(0, 99999), 5, '0', STR_PAD_LEFT);

                // Create a new VouchersUniqueNumber record

                $voucherCredit = new Voucher();
                $voucherCredit->vouchers_unique_number_id = $voucherUniqueNumber->id_vouchers_unique_number;
                $voucherCredit->date = $validatedData['customer_ope_date'];
                $voucherCredit->transaction_acc_no = '22';
                $voucherCredit->transaction_acc_name = 'Receivables From Customer';
                $voucherCredit->business_partner_type = 'Customer';
                $voucherCredit->partner_name = $validatedData['customer_name'];
                $voucherCredit->debit = 0;
                $voucherCredit->credit = $validatedData['customer_ope_bal_cr'];
                $voucherCredit->save();
            }

            // Redirect to the voucher print route, passing the id of VouchersUniqueNumber
        }

        if ($request->ajax()) {
            $getCustomer = Customer::all()->toArray();
            return response()->json([
                'success' => true,
                'message' => 'New Customer Added Successfully!',
                'customers' =>  $getCustomer,
            ]);
        }

        session()->flash('success', "New Supplier Added Successfully");
        return redirect('customers');
    }

    public function print($id)
    {
        dd($id); // Check if `transaction_acc_name` is present in this collection
        $id = Crypt::decrypt($id);

        // Fetch voucher details with related vouchers
        $voucherDetails = VouchersUniqueNumber::with('vouchers')
            ->where('voucher_type', 'Journal Voucher')
            ->where('id_vouchers_unique_number', $id)
            ->first();

        if (!$voucherDetails) {
            abort(404, 'Voucher not found.');
        }

        $accountVouchers = $voucherDetails->vouchers->where('business_partner_type', 'Customer');
        $vou_other_detail = $accountVouchers->first(); // Get the first voucher for the other detail

        // Debugging to check if transaction_acc_name is present

        return view('voucher.view', compact('voucherDetails', 'accountVouchers', 'vou_other_detail'));
    }

    /**
     * Display the specified resource.
     */
    public function show(service_vendor $service_vendor) {}

    public function check_customer_number($cell)
    {
        $get_customer = Customer::where('customer_cell', $cell)->first();

        // dd($cell);

        if ($get_customer) {
            return response()->json([
                'getCell' => true
            ]);
        } else {
            return response()->json([
                'getCell' => false
            ]);
        }
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        $cities = City::all();
        $dec_id = \Crypt::decrypt($id);
        $customers = customer::where('id_customers', $dec_id)->first();
        // dd($customers);
        $countries = countries::all();
        return view('customers.edit', compact('customers', 'countries', 'cities'));
    }

    public function update(Request $request, $id)
    {
        // Decrypt the ID
        $customerId = Crypt::decrypt($id);

        // Validate the incoming request data
        $validatedData = $request->validate([
            'customer_ope_date' => 'nullable|date',
            'customer_name' => 'required|string|max:255',
            'customer_name_urdu' => 'nullable|string|max:255',
            'customer_email' => 'nullable|email|max:255',
            'customer_phone' => 'nullable|string|max:20',
            'customer_whatsapp' => 'nullable|string|max:20',
            'customer_ope_bal_dr' => 'nullable|numeric',
            'customer_ope_bal_cr' => 'nullable|numeric',
            'customer_address' => 'nullable|string|max:255',
            'customer_address_urdu' => 'nullable|string|max:255',
            'city' => 'nullable|string|max:110',
            'customer_reference' => 'nullable|string|max:255',
            'customer_remarks' => 'nullable|string|max:255',
            'customer_remarks_urdu' => 'nullable|string|max:255',
            'customer_status' => 'nullable|in:0,1',
            'customer_image' => 'nullable|mimes:jpeg,png,jpg,gif,svg|max:2048', // You can adjust the image validation
        ]);

        // Find the customer by ID
        $customer = Customer::findOrFail($customerId);

        // Update the customer data with the validated request data
        $customer->customer_ope_date = $validatedData['customer_ope_date'];
        $customer->customer_name = $validatedData['customer_name'];
        $customer->customer_name_urdu = $validatedData['customer_name_urdu'];
        $customer->customer_email = $validatedData['customer_email'];
        $customer->customer_cell = $validatedData['customer_phone'];
        $customer->whatsapp_number = $validatedData['customer_whatsapp'];
        $customer->customer_ope_bal_dr = $validatedData['customer_ope_bal_dr'] ?? null;
        $customer->customer_ope_bal_cr = $validatedData['customer_ope_bal_cr'] ?? null;
        $customer->customer_address = $validatedData['customer_address'];
        $customer->customer_address_urdu = $validatedData['customer_address_urdu'];
        $customer->customer_city = $validatedData['city'];
        $customer->customer_reference = $validatedData['customer_reference'];
        $customer->customer_remarks = $validatedData['customer_remarks'];
        $customer->customer_remarks_urdu = $validatedData['customer_remarks_urdu'];
        $customer->status = $validatedData['customer_status'];

        // Handle image upload
        if ($request->hasFile('customer_image')) {
            $image = $request->file('customer_image');
            $imageName = time() . '.' . $image->getClientOriginalExtension();
            $image->move(public_path('uploads/customer_images'), $imageName);

            // Optionally, delete the old image if needed
            // if ($customer->customer_image) {
            //     File::delete(public_path('uploads/customer_images/' . $customer->customer_image));
            // }

            $customer->customer_image = $imageName;
        }

        // Save the updated customer information
        $customer->save();

        // Redirect back with a success message
        return redirect()->back()->with('success', 'Customer information updated successfully.');
    }





    public function destroy($id)
    {
        $dec_id = Crypt::decrypt($id);
        $edit_vendor = Customer::where('id_customers', $dec_id)->delete();
        // dd($edit_vendor);
        session()->flash('success', "Deleted Successfully");
        return redirect()->back();
    }

    public function view($id)
    {
        $customers = Customer::all();
        $dec_id = Crypt::decrypt($id);
        $view = Customer::where('id_customers', $dec_id)->first();
        // $inquiry1 = inquiry::where('customer_id', $view->id_customers)->get();
        // $quotations = [];
        // $inquiry = inquiry::select('inquiry.*', 'inquirytypes.type_id', 'inquirytypes.type_name')
        //     ->join('inquirytypes', 'inquirytypes.type_id', 'inquiry.id_inquiry')
        //     // ->join('users' ,'users.id' , 'inquiry.saleperson' )
        //     ->where('customer_id', $view->id_customers)->get();

        //     foreach ($inquiry as $in) {
        //         $quotation = quotation::where('inquiry_id', $in->id_inquiry)->get();
        //     if ($quotation) {
        //         $quotations[] = $quotation;
        //     }
        //         }

        // dd($quotations);
        return view('customers.view', compact('customers', 'view'));
    }
}
