<?php

namespace App\Http\Controllers\Apis;

use App\Models\AccessoryType;
use App\Models\Categories;
use App\Models\EmailTemplate;
use App\Models\LogisticsServicePincodes;
use App\Models\NegotiationWalletRepeat;
use App\Models\Products;
use App\Models\ProductsCapacity;
use App\Models\ProductsColor;
use DateTime;
use App\Http\Controllers\Controller;
use App\Models\Accessory;
use App\Models\Aeb;
use App\Models\AlphaSchemeSettings;
use App\Models\ApBranchConfiguration;
use App\Models\ApChainsSettings;
use App\Models\User;
use App\Models\ApiAuth;
use App\Models\ApiWebItemDetails;
use App\Models\Branchs;
use App\Models\Category;
use App\Models\City;
use App\Models\ConditionCategories;
use App\Models\ConditionOptions;
use App\Models\FinalCondition;
use App\Models\FunctionalResult;
use App\Models\ItemDetails;
use App\Models\ItemImages;
use App\Models\ItemsLog;
use App\Models\Location;
use App\Models\MobilePricing;
use App\Models\NegotiationWallet;
use App\Models\PramotionalDiscounts;
use App\Models\PricingConditions;
use App\Models\ProductBrands;
use App\Models\ProductModels;
use App\Models\ProductCapacity;
use App\Models\ProductColor;
use App\Models\ProductModelCapacity;
use App\Models\ProductModelColor;
use App\Models\ProductNegotiation;
use App\Models\PurchaseDetails;
use App\Models\SpeacialOffers;
use App\Models\StoreNegConditions;
use App\Models\Stores;
use App\Models\StoresRepeat;
use App\Models\StorewiseOnlinePricingPercentage;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use Illuminate\Support\Facades\Auth;
use App\Models\AppLogDetails;
use App\Models\ApSchemePricing;
use App\Models\ApSchemePricingRepeat;
use App\Models\Coupons;
use App\Models\LfrCoupons;
use App\Models\PartnersSettings;
use App\Models\PartnerstoStores;
use App\Models\Smshistory;
use Illuminate\Support\Facades\Http;
use Carbon\Carbon;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Validator;


class XchangeApiWebController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    // use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    // public function __construct()
    // {
    //     $this->middleware('guest')->except('logout');
    // }

    //For validation IMEI with imei format and validation
    public function validateimei($imei)
    {

        if (!preg_match('/^[0-9]{15}$/', $imei)) return 0;
        $sum = 0;
        for ($i = 0; $i < 14; $i++) {
            $num = $imei[$i];
            if (($i % 2) != 0) {
                $num = $imei[$i] * 2;
                if ($num > 9) {
                    $num = (string) $num;
                    $num = $num[0] + $num[1];
                }
            }
            $sum += $num;
        }
        if ((($sum + $imei[14]) % 10) != 0) return 0;
        return 1;
    }
    //Random number generator
    public function getRandom($n)
    {
        // $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
        $randomString = '';

        for ($i = 0; $i < $n; $i++) {
            $index = rand(0, strlen($characters) - 1);
            $randomString .= $characters[$index];
        }

        return $randomString;
    }

    //for category generator
    public function getBearerToken(Request $request)
    {

        $validator = Validator::make($request->all(), [
            
            'AccessToken' => ['required', 'regex:/^[a-zA-Z0-9\s]+$/', 'min:3', 'max:150'],
            'username' => ['required'],
        ], [
            'AccessToken.required' => 'AccessToken is required.',
            'AccessToken.regex' => 'AccessToken must only contain letters and spaces.',
            'AccessToken.min' => 'AccessToken must be at least 3 characters long.',
            'AccessToken.max' => 'AccessToken must not exceed 50 characters.',
            'username.required' => 'Username is required.',
            
        ]);

        if ($validator->fails()) {
            $errors = $validator->errors()->toArray();
            $firstError = collect($errors)->flatten()->first(); // Get the first error

            $response["status"] = 0;
            $response["statusCode"] = 400;
            $response["message"] = $firstError;
            $response["data"] = [];
            return response($response, 200);
        }

        $accessToken = "$2y$10$".$request->AccessToken;

        $authDatacount = DB::table('api_auth')->where('auth_token', $accessToken)->where('status', 'active')->count();
        if($authDatacount < 1)
        {
            $response["status"] = 0;
            $response["statusCode"] = 400;
            $response["message"] = "Invalid AccessToken";
            $response["data"] = [];
            return response($response, 200);
        }
        $authData = DB::table('api_auth')->where('auth_token', $accessToken)->where('status', 'active')->first();

        $store_id = $authData->store_id;

        // $user = DB::table('users')->where('store_id', $store_id)->where('username', $request->username)->where('status', 'active')->first();
        $user = User::where('username', $request->username)->where('store_id', $store_id)->where('status','active')->first();
//  return response($user, 200);
        if(!$user) {
            $response =["status" => 0, "statuscode" => 401, "message" => "Invalid credentials. Please check your username and password and try again.", "data" => []];
            return response($response, 401);
        }

        $token = $user->createToken('myapptoken')->plainTextToken;

        $latestToken = $user->tokens()->latest()->first();
                    
                    // Check if the token entry exists and update the columns
        if ($latestToken) {

        $latestToken->push_id = $request->push_id;
        $latestToken->device_type = $request->device_type;
        $latestToken->status = "active";
        $latestToken->device_code = $request->device_code;
        $latestToken->save(); // Use save() instead of update()
        }

         DB::table('login_history')->insert([
            'user_id' => $user->id,
            // 'user_mac' => $request->latitude .','.$request->longitude,
            'log_time' => date('Y-m-d H:i:s'),
            'log_type' => 'login',
            'latitude' => $request->latitude,
            'longitude' => $request->longitude,
            'device_code' =>  "web",
            'device_type' => "web",
            'app_version' =>  "web",
        ]);


        $response = [
            "status" => 1,
            "message" => "Successfully logged in",
            'token' => $token
        ];
        return response($response, 200);

        
    }
    public function getXchangeCategory(Request $request)
    {


        $userdta = Auth::user();
        // $token = $userdta->createToken('token-name')->plainTextToken;
        $token = $request->bearerToken();
        [$id, $plainTextToken] = explode('|', $token, 2);
        $validToken = DB::table('personal_access_tokens')->where('token', hash('sha256', $plainTextToken))->get();
        
        // $response["status"] = 0;
        // $response["statuscode"] = 401;
        // $response["messagetype"] = "User Inactive";
        // $response["message"] = "Your account appears to be inactive. Access to this app is restricted";
        // $response["data"] = [];
        // return response($response, 401);
    
        // return response($userdta, 200);
        //getting the information from the api service
        $headers = apache_request_headers();
        $body = file_get_contents('php://input');

        $date = date("Y-m-d H:i:s");

     

        $response = ["status" => 0, "message" => "No data found for the specified request", "description" => "", "data" => []];

        if (!empty($userdta)) {
            $branch_id = $userdta->branch_id;
            $store_id = $userdta->store_id;
            $storedata = Stores::where('status', 'active')->where('id', $store_id)->get();
            if (sizeof($storedata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 404;
                $response["messagetype"] = "Unauthorised request";
                $response["message"] = "You do not have permission to access this resource, as the LFR is not enabled for using this resource";
                $response["data"] = [];
                return response($response, 404);
            }

            $storebranchdata = StoresRepeat::where('status', 'active')->where('parent_id', $store_id)->where('store_branch', $branch_id)->get();
            if (sizeof($storebranchdata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 404;
                $response["messagetype"] = "Unauthorized request";
                $response["message"] = "You do not have permission to access this resource, as the branch is not enabled for using this resource";
                $response["data"] = [];
                return response($response, 404);
            }

            // query to retrieve store mobile_pricing data from mobile_pricing table with product details
            $distinctModelIds = DB::table('mobile_pricing')
                        ->where('status', 'active')
                        ->where('partner_id', 0)
                        ->distinct()
                        ->pluck('model_id');
            $distinctModelIdsArray = $distinctModelIds->toArray();      

            // dd($request->all());
            $categorydata = Products::query();
            if ($request->has('category_name')) {
                $categorydata->where('category_name', 'like', '%' . $request->input('category_name') . '%');
            }
            $categorydata = $categorydata->select('cat.id as category_id', 'category_name', 'category_image','input_type')->whereIn('products.id',$distinctModelIdsArray)->leftJoin(DB::connection("mysql2")->getDatabaseName().'.categories as cat','cat.id','products.category')->groupBy('cat.id')->orderBy('category_name','ASC')->get();
            // return response($categorydata, 200);
            if (sizeof($categorydata) > 0) {

                //For transaction reference number
                $storeCode = str_pad($store_id, 2, '0', STR_PAD_LEFT);
                $branchCode = str_pad($branch_id, 4, '0', STR_PAD_LEFT);
                $dtCode = date("YmdHis");
                $getRandom = $this->getRandom("8");
                $transaction_ref_no = "LS" . $storeCode . $branchCode . $dtCode . $getRandom;

                //For Brands data 
                // $brandsdata = ProductBrands::select('id as brand_id', 'brand_name', 'category_id','brand_image')->orderBy('brand_name','ASC')->get();
                // $brandsdata2[] = $brandsdata;

                // $modeldata = ProductModels::select('id as model_id', 'model_name', 'brand_id', 'category_id')->orderBy('model_name','ASC')->where('status', 'active')->get();

                $host = $_SERVER['HTTP_HOST'];
                $https = $_SERVER['HTTPS'];
                if($https == 'on')
                {
                    $siteurl = "https://$host/";
                }else{
                    $siteurl = "http://$host/";
                }

                $brandsimgpath = $siteurl."brand_logos/";
                $categoryimgpath = $siteurl."category_logos/";
                // $brandsdata1['brandsdata'] = $brandsdata2;
                $data['TransactionRefNo'] = $transaction_ref_no;
                $data['categoryimgpath'] = $categoryimgpath;
                $data['categorydata'] = $categorydata;
                // $data['brandsimgpath'] = $brandsimgpath;
                // $data['brandsdata'] = $brandsdata;
                // $data['modeldata'] = $modeldata;

                $insert["transaction_ref_no"] = $transaction_ref_no;
                $insert["latLong"] = $request->latitude.','.$request->longitude;
                $insert["store_id"] = $store_id;
                $insert["branch_id"] = $branch_id;
                $insert["created_at"] = date('Y-m-d H:i:s');
                $insert["status"] = "created";
                ApiWebItemDetails::create($insert);


                //For successful fetch data
                $response["status"] = 1;
                $response["statuscode"] = 200;
                $response["messagetype"] = "";
                $response["message"] = "";
                $response["data"] = $data;
                return response($response, 200);
            } else {
                //Response for invalid authentication
                $response["status"] = 0;
                $response["statuscode"] = 401;
                $response["messagetype"] = "No data found for the specified request";
                $response["message"] = "";
                $response["data"] = [];
                return response($response, 401);
            }
        } else {
            //Response for invalid authentication
            $response["status"] = 0;
            $response["statuscode"] = 404;
            $response["messagetype"] = "Unauthorized request";
            $response["message"] = "You do not have permission to access this resource";
            $response["data"] = [];
            return response($response, 404);
        }
    }
    public function getXchangeBrands(Request $request)
    {


        $userdta = Auth::user();
        // $token = $userdta->createToken('token-name')->plainTextToken;

    
        // return response($userdta, 200);
        //getting the information from the api service
        $headers = apache_request_headers();
        $body = file_get_contents('php://input');

        $date = date("Y-m-d H:i:s");

        $transaction_ref_no = $request->TransactionRefNo;
        $category_id = $request->category_id;
        // return response($request->all(), 404);

        $response = ["status" => 0, "message" => "No data found for the specified request", "description" => "", "data" => []];

        if (!empty($userdta)) {
            $branch_id = $userdta->branch_id;
            $store_id = $userdta->store_id;
            $storedata = Stores::where('status', 'active')->where('id', $store_id)->get();
            if (sizeof($storedata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 404;
                $response["messagetype"] = "Unauthorised request";
                $response["message"] = "You do not have permission to access this resource, as the LFR is not enabled for using this resource";
                $response["data"] = [];
                return response($response, 404);
            }

            $storebranchdata = StoresRepeat::where('status', 'active')->where('parent_id', $store_id)->where('store_branch', $branch_id)->get();
            if (sizeof($storebranchdata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 404;
                $response["messagetype"] = "Unauthorized request";
                $response["message"] = "You do not have permission to access this resource, as the branch is not enabled for using this resource";
                $response["data"] = [];
                return response($response, 404);
            }


            if (empty($transaction_ref_no) || empty($category_id)) {
                //Response for invalid input details
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "All required parameters are missing - category_id,TransactionRefNo";
                $response["data"] = [];
                return response($response, 200);
            }

            $refdata = ApiWebItemDetails::where('transaction_ref_no', $transaction_ref_no)->get();
            if (sizeof($refdata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "No data found for the specified request. Please check the TransactionRefNo";
                $response["data"] = [];
                return response($response, 200);
            }

            // query to retrieve store mobile_pricing data from mobile_pricing table with product details
            // $categorydata = Category::select('id as category_id', 'category_name', 'category_image')->orderBy('category_name','ASC')->get();
            // dd($request->all());


            $distinctModelIds = DB::table('mobile_pricing')
                        ->where('status', 'active')
                        ->where('partner_id', 0)
                        ->distinct()
                        ->pluck('model_id');
            $distinctModelIdsArray = $distinctModelIds->toArray();


            
            $brandsdata = Products::query();
            // if ($request->has('brand_name')) {
            //     $brandsdata->where('brand_name', 'like', '%' . $request->input('brand_name') . '%');
            // }
            $brandsdata = $brandsdata->select('pb.id as brand_id', 'brand_name', 'products.category as category_id', 'brand_image','priority')->leftJoin('brands as pb','pb.id','products.brand')->where('products.category',$category_id)->where('pb.status','active')->whereIn('products.id',$distinctModelIdsArray)->groupBy('pb.id')->orderByRaw("FIELD(priority, 1,2,3,4,5,6,7,8,9,10,11,12,0)")->orderBy('brand_name','ASC')->get();

            // $sql = Str::replaceArray('?', $brandsdata->getBindings(), $brandsdata->toSql());
            // dd($sql);

            // return response($categorydata, 200);
            if (sizeof($brandsdata) > 0) {

                //For transaction reference number
               
                //For Brands data 
                // $brandsdata = ProductBrands::select('id as brand_id', 'brand_name', 'category_id','brand_image')->orderBy('brand_name','ASC')->get();
                // $brandsdata2[] = $brandsdata;

                // $modeldata = ProductModels::select('id as model_id', 'model_name', 'brand_id', 'category_id')->orderBy('model_name','ASC')->where('status', 'active')->get();

                $host = $_SERVER['HTTP_HOST'];
                $https = $_SERVER['HTTPS'];
                if($https == 'on')
                {
                    $siteurl = "https://$host/";
                }else{
                    $siteurl = "http://$host/";
                }

                $brandsimgpath = $siteurl."brand_logos/";
                $categoryimgpath = $siteurl."category_logos/";
                // $brandsdata1['brandsdata'] = $brandsdata2;
                $data['TransactionRefNo'] = $transaction_ref_no;
                // $data['categoryimgpath'] = $categoryimgpath;
                $data['brandsimgpath'] = $brandsimgpath;
                // $data['categorydata'] = $categorydata;
                $data['brandsdata'] = $brandsdata;
                // $data['modeldata'] = $modeldata;

                $insert["transaction_ref_no"] = $transaction_ref_no;
                $insert["store_id"] = $store_id;
                $insert["branch_id"] = $branch_id;
                $insert["created_at"] = date('Y-m-d H:i:s');
                $insert["status"] = "created";
                // ApiWebItemDetails::create($insert);

                $update['category_id'] = $category_id;
                $update = ApiWebItemDetails::where('transaction_ref_no', $transaction_ref_no)->update($update);

                //For successful fetch data
                $response["status"] = 1;
                $response["statuscode"] = 200;
                $response["messagetype"] = "";
                $response["message"] = "";
                $response["data"] = $data;
                return response($response, 200);
            } else {
                //Response for invalid authentication
                $response["status"] = 0;
                $response["statuscode"] = 401;
                $response["messagetype"] = "No data found for the specified request";
                $response["message"] = "";
                $response["data"] = [];
                return response($response, 401);
            }
        } else {
            //Response for invalid authentication
            $response["status"] = 0;
            $response["statuscode"] = 404;
            $response["messagetype"] = "Unauthorized request";
            $response["message"] = "You do not have permission to access this resource";
            $response["data"] = [];
            return response($response, 404);
        }
    }
    
    public function getXchangeProducts(Request $request)
    {


        $userdta = Auth::user();
        // $token = $userdta->createToken('token-name')->plainTextToken;

    
        // return response($userdta, 200);
        //getting the information from the api service
        $headers = apache_request_headers();
        $body = file_get_contents('php://input');

        $date = date("Y-m-d H:i:s");

        $transaction_ref_no = $request->TransactionRefNo;
        $category_id = $request->category_id;
        $brand_id = $request->brand_id;
        // return response($request->all(), 404);

        $response = ["status" => 0, "message" => "No data found for the specified request", "description" => "", "data" => []];

        if (!empty($userdta)) {
            $branch_id = $userdta->branch_id;
            $store_id = $userdta->store_id;
            $storedata = Stores::where('status', 'active')->where('id', $store_id)->get();
            if (sizeof($storedata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 404;
                $response["messagetype"] = "Unauthorised request";
                $response["message"] = "You do not have permission to access this resource, as the LFR is not enabled for using this resource";
                $response["data"] = [];
                return response($response, 404);
            }

            $storebranchdata = StoresRepeat::where('status', 'active')->where('parent_id', $store_id)->where('store_branch', $branch_id)->get();
            if (sizeof($storebranchdata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 404;
                $response["messagetype"] = "Unauthorized request";
                $response["message"] = "You do not have permission to access this resource, as the branch is not enabled for using this resource";
                $response["data"] = [];
                return response($response, 404);
            }


            if (empty($transaction_ref_no) || empty($category_id)  || empty($brand_id)) {
                //Response for invalid input details
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "All required parameters are missing - category_id,brand_id,TransactionRefNo";
                $response["data"] = [];
                return response($response, 200);
            }

            $refdata = ApiWebItemDetails::where('transaction_ref_no', $transaction_ref_no)->get();
            if (sizeof($refdata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "No data found for the specified request. Please check the TransactionRefNo";
                $response["data"] = [];
                return response($response, 200);
            }

            // query to retrieve store mobile_pricing data from mobile_pricing table with product details
            // $categorydata = Category::select('id as category_id', 'category_name', 'category_image')->orderBy('category_name','ASC')->get();
            // dd($request->all());

            $distinctModelIds = DB::table('mobile_pricing')
                        ->where('status', 'active')
                        ->where('partner_id', 0)
                        ->where('brand_id', $brand_id)
                        ->distinct()
                        ->pluck('model_id');
            $distinctModelIdsArray = $distinctModelIds->toArray();

            
            $modeldata = Products::query();
            // if ($request->has('model_name')) {
            //     $modeldata->where('model_name', 'like', '%' . $request->input('model_name') . '%');
            // }
            $modeldata = $modeldata->select('id as model_id', 'model_name', 'brand as brand_id', 'category as category_id')->where('category',$category_id)->where('status','active')->where('brand',$brand_id)->whereIn('products.id',$distinctModelIdsArray)->groupBy('id')->orderBy('model_name','ASC')->get();
            

           
            // return response($categorydata, 200);
            if (sizeof($modeldata) > 0) {

                //For transaction reference number
               
                //For Brands data 
                // $brandsdata = ProductBrands::select('id as brand_id', 'brand_name', 'category_id','brand_image')->orderBy('brand_name','ASC')->get();
                // $brandsdata2[] = $brandsdata;

                // $modeldata = ProductModels::select('id as model_id', 'model_name', 'brand_id', 'category_id')->orderBy('model_name','ASC')->where('status', 'active')->get();

                $host = $_SERVER['HTTP_HOST'];
                $https = $_SERVER['HTTPS'];
                if($https == 'on')
                {
                    $siteurl = "https://$host/";
                }else{
                    $siteurl = "http://$host/";
                }

                $brandsimgpath = $siteurl."brand_logos/";
                $categoryimgpath = $siteurl."category_logos/";
                // $brandsdata1['brandsdata'] = $brandsdata2;
                $data['TransactionRefNo'] = $transaction_ref_no;
                // $data['categoryimgpath'] = $categoryimgpath;
                // $data['brandsimgpath'] = $brandsimgpath;
                // $data['categorydata'] = $categorydata;
                // $data['brandsdata'] = $brandsdata;
                $data['modeldata'] = $modeldata;

                $insert["transaction_ref_no"] = $transaction_ref_no;
                $insert["store_id"] = $store_id;
                $insert["branch_id"] = $branch_id;
                $insert["created_at"] = date('Y-m-d H:i:s');
                $insert["status"] = "created";
                // ApiWebItemDetails::create($insert);

                
                $update['brand_id'] = $brand_id;
                $update = ApiWebItemDetails::where('transaction_ref_no', $transaction_ref_no)->update($update);


                //For successful fetch data
                $response["status"] = 1;
                $response["statuscode"] = 200;
                $response["messagetype"] = "";
                $response["message"] = "";
                $response["data"] = $data;
                return response($response, 200);
            } else {
                //Response for invalid authentication
                $response["status"] = 0;
                $response["statuscode"] = 401;
                $response["messagetype"] = "No data found for the specified request";
                $response["message"] = "";
                $response["data"] = [];
                return response($response, 401);
            }
        } else {
            //Response for invalid authentication
            $response["status"] = 0;
            $response["statuscode"] = 404;
            $response["messagetype"] = "Unauthorized request";
            $response["message"] = "You do not have permission to access this resource";
            $response["data"] = [];
            return response($response, 404);
        }
    }
    public function getExchangeClrCapacity(Request $request)
    {


        // return response($_SERVER, 200);

        //getting the information from the api service
        $headers = apache_request_headers();

        $userdta = Auth::user();
        // $token = $userdta->createToken('token-name')->plainTextToken;
        $transaction_ref_no = isset($_SERVER['HTTP_TRANSACTIONREFNO']) ? $_SERVER['HTTP_TRANSACTIONREFNO'] : '';
        // $acctoken=$_SERVER['HTTP_ACCESSTOKEN'];
        //For getting body data from api service
        $category_id = $request->category_id;
        $brand_id = $request->brand_id;
        $model_id = $request->model_id;
        $transaction_ref_no = $request->TransactionRefNo;
        // return response($request, 200);
      
        $date = date("Y-m-d H:i:s");

        
        $response = ["status" => 0, "message" => "No data found for the specified request1", "description" => "", "data" => []];

        if (!empty($userdta)) {
            $branch_id = $userdta->branch_id;
            $store_id = $userdta->store_id;
            $storedata = Stores::where('status', 'active')->where('id', $store_id)->get();
            if (sizeof($storedata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 404;
                $response["messagetype"] = "Unauthorised request";
                $response["message"] = "You do not have permission to access this resource, as the LFR is not enabled for using this resource";
                $response["data"] = [];
                return response($response, 404);
            }

            $storebranchdata = StoresRepeat::where('status', 'active')->where('parent_id', $store_id)->where('store_branch', $branch_id)->get();
            if (sizeof($storebranchdata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 404;
                $response["messagetype"] = "Unauthorized request";
                $response["message"] = "You do not have permission to access this resource, as the branch is not enabled for using this resource";
                $response["data"] = [];
                return response($response, 404);
            }
            // return response($brand_id.'-'.$model_id.'-'.$transaction_ref_no, 400);
            if (empty($brand_id) || empty($model_id) || empty($transaction_ref_no)) {
                //Response for invalid Voucher Number
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "All required parameters are missing - category_id, brand_id,model_id,TransactionRefNo123";
                $response["data"] = [];
                return response($response, 200);
            }

            //Checking for valid teansaction_ref_no with branch and status
            // $refdata = ApiWebItemDetails::where('transaction_ref_no',$transaction_ref_no)->where('status','created')->where('store_id',$store_id)->where('branch_id',$branch_id)->get();
            $refdata = ApiWebItemDetails::where('transaction_ref_no', $transaction_ref_no)->get();
            if (sizeof($refdata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "No data found for the specified request. Please check the TransactionRefNo";
                $response["data"] = [];
                return response($response, 200);
            }
            // return response($store_id, 200);
            if ($store_id != $refdata[0]["store_id"]) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "TransactionRefNo does not belong to your account or request.";
                $response["data"] = [];
                return response($response, 200);
            }
            if ($branch_id != $refdata[0]["branch_id"]) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "TransactionRefNo does not belong to your branch or request.";
                $response["data"] = [];
                return response($response, 200);
            }
            if ($refdata[0]["status"] != 'created') {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "The requested TransactionRefNo has already been applied for an exchange.";
                $response["data"] = [];
                return response($response, 200);
            }

            $productModls = Products::where('category', $category_id)->where('id', $model_id)->where('brand', $brand_id)->where('status', 'active')->get();

            if (sizeof($productModls) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "No data found for the specified request";
                $response["data"] = [];
                return response($response, 200);
            }

            $distinctModelIds = DB::table('mobile_pricing')
                        ->where('status', 'active')
                        ->where('partner_id', 0)
                        ->where('model_id', $model_id)
                        ->distinct()
                        ->pluck('capacity_id');
            $distinctCapIdsArray = $distinctModelIds->toArray();

            // query to retrieve store capacity data 
            $capacitydata = ProductsCapacity::select('pc.id as capacity_id', 'pc.capacity')
                ->leftJoin('mobile_capacity as pc', 'pc.id', '=', 'product_capacity.mobile_capacity_id')
                ->where('pc.status', 'active')->where('product_id', $model_id)->whereIn('pc.id',$distinctCapIdsArray)->where('pc.capacity', '!=', 'N/A')->groupBy('pc.id')->orderBy('pc.capacity','ASC')->get();

            //For assigning partner id for the transaction
            $branchsDetails = Branchs::where('id', $branch_id)->get();

            $state_id = $branchsDetails['0']->location_id;
            $city_id = $branchsDetails['0']->city_id;

            
           

            if (sizeof($capacitydata) > 0) {
                $colordata = ProductsColor::select('pc.id as color_id', 'pc.color')
                    ->leftJoin('mobile_color as pc', 'pc.id', '=', 'product_color.mobile_color_id')->where('product_id', $model_id)->where('pc.color', '!=', 'N/A')->groupBy('pc.id')->orderBy('pc.color','ASC')->get();
                
                
                $physical_condition = ConditionCategories::where('status', 'active')->where('condition_type_id', '1')->select('id', 'category_name', 'remarks as description')->get();
                $accessorydata = Accessory::where('category_id',$category_id)->where('brand_id',$brand_id)->where('model_id',$model_id)->where('status','active')->select('id','accessory_name')->get();
                
               
                $partner_id = 0;
                //For inserting brand model data into api_item_details table
                $update['partner_id'] = $partner_id;
                $update['category_id'] = $category_id;
                $update['brand_id'] = $brand_id;
                $update['model_id'] = $model_id;
                $update = ApiWebItemDetails::where('transaction_ref_no', $transaction_ref_no)->update($update);

                $data['capacitydata'] = $capacitydata;
                $data['colordata'] = $colordata;
                $data['alertmsg'] = "Is the device powering on and not dead?";
                $data['applealert'] = "Is the iCloud account locked?";
                // $data['physical_condition'] = $physical_condition;    
                // $data['accessorydata'] = $accessorydata;
                $data['fake_mobile'] = array("Note" => "To get price information, please send whether the device OS / is fake / iCloud Lock(based on brand) or not with a response as yes or no within your request.");

                //For successful fetch data
                $response["status"] = 1;
                $response["statuscode"] = 200;
                $response["messagetype"] = "";
                $response["message"] = "";
                $response["data"] = $data;
                return response($response, 200);
            } else {
                //Response for invalid authentication
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "No data found for the specified request";
                $response["data"] = [];
                return response($response, 401);
            }
        } else {
            //Response for invalid authentication
            $response["status"] = 0;
            $response["statuscode"] = 404;
            $response["messagetype"] = "Unauthorized request";
            $response["message"] = "You do not have permission to access this resource";
            $response["data"] = [];
            return response($response, 404);
        }
    }

    public function getExchangeBasePrice(Request $request)
    {

       
        
        //getting the information from the api service
        $userdta = Auth::user();
        

        $transaction_ref_no = isset($_SERVER['HTTP_TRANSACTIONREFNO']) ? $_SERVER['HTTP_TRANSACTIONREFNO'] : '';

        // $acctoken=$_SERVER['HTTP_ACCESSTOKEN'];
        //For getting body data from api service
        $category_id = $request->category_id;
        $brand_id = $request->brand_id;
        $model_id = $request->model_id;
        $capacity_id = $request->capacity_id;
        $color_id = $request->color_id;
        $is_fake = $request->is_fake;
        $is_icloud_locked = $request->is_icloud_locked;
        $is_deviceon = $request->is_deviceon;
        $imei = $request->imei;
        $purchase_date = $request->purchase_date;
        $physical_condition_id = $request->physical_condition_id;
        $transaction_ref_no = $request->TransactionRefNo;
        




        
        // return response($userdata, 200);

        $response = ["status" => 0, "message" => "No data found for the specified request", "description" => "", "data" => []];

        if (!empty($userdta) > 0) {
            $branch_id = $userdta->branch_id;
            $store_id = $userdta->store_id;
            $storedata = Stores::where('status', 'active')->where('id', $store_id)->get();
            if (sizeof($storedata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 404;
                $response["messagetype"] = "Unauthorised request";
                $response["message"] = "You do not have permission to access this resource, as the LFR is not enabled for using this resource";
                $response["data"] = [];
                return response($response, 404);
            }

            $storebranchdata = StoresRepeat::where('status', 'active')->where('parent_id', $store_id)->where('store_branch', $branch_id)->get();
            if (sizeof($storebranchdata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 404;
                $response["messagetype"] = "Unauthorized request";
                $response["message"] = "You do not have permission to access this resource, as the branch is not enabled for using this resource";
                $response["data"] = [];
                return response($response, 404);
            }
            if (empty($brand_id) || empty($category_id) || empty($model_id) || empty($capacity_id) || empty($color_id) || empty($is_fake) || empty($is_icloud_locked) || empty($transaction_ref_no)) {
                //Response for invalid input details
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "All required parameters are missing - category_id, brand_id,model_id,capacity_id,color_id,is_fake,is_icloud_locked,TransactionRefNo";
                $response["data"] = [];
                return response($response, 200);
            }

            if (empty($imei)) {
                //Response for invalid input details
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "error";
                $response["message"] = "It is mandatory to fill in the IMEI number and cannot be left blank";
                $response["data"] = [];
                return response($response, 200);
            }

            if (strlen($imei) < 6) {
                //Response for invalid input details
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "error";
                $response["message"] = "Ensure that the IMEI/Seriel No entered has minimum 6 characters in length";
                $response["data"] = [];
                return response($response, 200);
            }

            $categorydata = Category::select('id as category_id', 'category_name', 'category_image','input_type')->where('id',$category_id)->orderBy('category_name','ASC')->get();
            // return response($categorydata, 200);
            if(empty($categorydata))
            {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "Invalid Category Id. Please check and correct it";
                $response["data"] = [];
                return response($response, 200);

            }
            if($categorydata[0]->input_type == 'imei')
            {

                // $imeival = $this->validateimei($imei);
                $imeival = $this->validateimei($imei);
                if ($imeival == 0) {
                    $response["status"] = 0;
                    $response["statuscode"] = 400;
                    $response["messagetype"] = "Bad Request";
                    $response["message"] = "Invalid IMEI format. Please check and correct it.";
                    $response["data"] = [];
                    return response($response, 200);
                }
            }

            if (empty($purchase_date)) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "To get the price information, include the 'purchase date' in the request.";
                $response["data"] = [];
                return response($response, 200);
            }

            $interval = 0;
            $test_arr  = explode('-', $purchase_date);
            if (count($test_arr) == 3) {
                if (!checkdate($test_arr[1], $test_arr[0], $test_arr[2])) {

                    $response["status"] = 0;
                    $response["statuscode"] = 400;
                    $response["messagetype"] = "Bad Request";
                    $response["message"] = "Invalid date format. Please provide the purchase_date in the dd-mm-yyyy format.";
                    $response["data"] = [];
                    return response($response, 200);
                } else {

                    if ($test_arr[2] < 1990) {
                        $response["status"] = 0;
                        $response["statuscode"] = 400;
                        $response["messagetype"] = "Bad Request";
                        $response["message"] = "Invalid format. The year of purchase_date must be 1990 or later.";
                        $response["data"] = [];
                        return response($response, 200);
                    }

                    $today = date("d-m-Y");

                    if (strtotime($purchase_date) > strtotime($today)) {
                        $response["status"] = 0;
                        $response["statuscode"] = 400;
                        $response["messagetype"] = "Bad Request";
                        $response["message"] = "Invalid date. The purchase_date cannot be a future date.";
                        $response["data"] = [];
                        return response($response, 200);
                    }

                    $diff = strtotime($purchase_date) - strtotime($today);
                    $interval = abs(round($diff / 86400));
                }
            } else {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "Invalid date format. Please provide the purchase_date in the dd-mm-yyyy format.";
                $response["data"] = [];
                return response($response, 200);
            }


            
            
            //Checking for IMEI duplicate
            $itmcount = ItemDetails::where('imei', $imei)->where("status", "active")
                ->where(DB::raw('DATE_FORMAT(created_at, "%Y-%m-%d")'), '>', DB::raw('DATE_SUB(curdate(), INTERVAL 5 DAY)'))->count();

            $itmcount1 = ApiWebItemDetails::where('imei', $imei)->where("status", "generated")->where("final_status","!=", "cancelled")
                ->where(DB::raw('DATE_FORMAT(created_at, "%Y-%m-%d")'), '>', DB::raw('DATE_SUB(curdate(), INTERVAL 5 DAY)'))->count();    
            if ($itmcount > 0 || $itmcount1 > 0) {
                //Response for invalid iCloud mobile data
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "Oops! An exchange voucher has already been generated for this IMEI.";
                $response["data"] = [];
                return response($response, 200);
            }
            //Checking for valid teansaction_ref_no with branch and status
            //  $refdata = ApiWebItemDetails::where('transaction_ref_no',$transaction_ref_no)->where('status','created')->where('store_id',$store_id)->where('branch_id',$branch_id)->get();
            $refdata = ApiWebItemDetails::where('transaction_ref_no', $transaction_ref_no)->get();
            if (sizeof($refdata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "No data found for the specified request. Please check the TransactionRefNo";
                $response["data"] = [];
                return response($response, 200);
            }
            if ($store_id != $refdata[0]["store_id"]) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "TransactionRefNo does not belong to your account or request.";
                $response["data"] = [];
                return response($response, 200);
            }
            if ($branch_id != $refdata[0]["branch_id"]) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "TransactionRefNo does not belong to your branch or request.";
                $response["data"] = [];
                return response($response, 200);
            }
            if ($refdata[0]["status"] != 'created') {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "The requested TransactionRefNo has already been applied for an exchange.";
                $response["data"] = [];
                return response($response, 200);
            }
            if ($is_fake != 'yes' && $is_fake != 'no') {
                //Response for invalid fake information
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "Invalid value for 'Is Device Fake'. Please check the values to be passed in this request.";
                $response["data"] = [];

                // $itemLog = 
                return response($response, 200);
            }
            //  return response($request, 200);
            if(!isset($request->is_deviceon))
            {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "Invalid value for 'Device Power On'. Please check the values to be passed in this request.";
                $response["data"] = [];

                // $itemLog = 
                return response($response, 200);
            }

            if ($is_deviceon != 'yes' && $is_deviceon != 'no') {
                //Response for invalid fake information
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "Invalid value for 'Device Power On'. Please check the values to be passed in this request.";
                $response["data"] = [];

                // $itemLog = 
                return response($response, 200);
            }

            
            if (strtolower($is_fake) == 'yes' || strtolower($is_deviceon) == 'no') {
                //Response for invalid fake mobile data
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "Oops! This device is not currently accepted under the Loop Sustainability exchange scheme.";
                $response["data"] = [];
                return response($response, 200);
            }
            // checking valid icloud lock options for apple devices
            if ($brand_id == '1' && ($is_icloud_locked != 'yes' && $is_icloud_locked != 'no')) {
                //Response for invalid iCloud lock options
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "Invalid parameter values, please check the values to be passed in this request ";
                $response["data"] = [];

                // $itemLog = 
                return response($response, 200);
            }
            // checking icloud lock for apple devices
            if ($brand_id == '1' && strtolower($is_icloud_locked) == 'yes') {
                //Response for invalid iCloud mobile data
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "Oops! This device is not currently accepted under the Loop Sustainability exchange scheme.";
                $response["data"] = [];
                return response($response, 200);
            }

            $user_id = $userdta->id;
            $branch_id = $userdta->branch_id;
            $partner_id = $refdata[0]["partner_id"];

            


            $productModls = ProductModels::where('category_id', $category_id)->where('id', $model_id)->where('brand_id', $brand_id)->where('status', 'active')->get();

            if (sizeof($productModls) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "No data found for the specified request";
                $response["data"] = [];
                return response($response, 200);
            }

            
            // query to retrieve store capacity data 
            $pricedata = MobilePricing::select('*')
                ->where('status', 'active')->where('model_id', $model_id)->where('brand_id', $brand_id)->where('capacity_id', $capacity_id)->where('partner_id', 0)->get();
            
            

            if (sizeof($pricedata) > 0) {
                //To get the product wise pricing percentage data with branch id
                $pstr_percentage = StorewiseOnlinePricingPercentage::where('store_id', $store_id)->where('status', 'active')->where('branch_id', $branch_id)->where('category_id', $category_id)->where('brand_id', $brand_id)->where('model_id', $model_id)->where('type', 'product')->get();
                if (sizeof($pstr_percentage) > 0) {
                    $percentage = $pstr_percentage[0]->percentage;
                } else {
                    //To get the product wise pricing percentage data without branch id
                    $pbstr_percentage = StorewiseOnlinePricingPercentage::where('store_id', $store_id)->where('status', 'active')->where('branch_id', '0')->where('category_id', $category_id)->where('brand_id', $brand_id)->where('model_id', $model_id)->where('type', 'product')->get();
                    if (sizeof($pbstr_percentage) > 0) {
                        $percentage = $pbstr_percentage[0]->percentage;
                    } else {
                        //To get the branch wise pricing percentage data 
                        $bstr_percentage = StorewiseOnlinePricingPercentage::where('store_id', $store_id)->where('branch_id', $branch_id)->where('status', 'active')->where('type', 'branch')->get();
                        if (sizeof($bstr_percentage) > 0) {
                            $percentage = $bstr_percentage[0]->percentage;
                        } else {
                            //To get the store wise pricing percentage data 
                            $ststr_percentage = StorewiseOnlinePricingPercentage::where('store_id', $store_id)->where('status', 'active')->where('type', 'LFR')->get();
                            if (sizeof($ststr_percentage) > 0) {
                                $percentage = $ststr_percentage[0]->percentage;
                            } else {
                                //if above percentages are not available then we consider percentage as 0
                                $percentage = 0;
                            }
                        }
                    }
                }

               

                $fp="exc_price";

                //For mobile Final value based on the current conditions
                $mprice = MobilePricing::where('brand_id',$brand_id)->where('model_id',$model_id)->where('capacity_id',$capacity_id)->select("$fp as price")->where('partner_id', 0)->first();
                $finalvalue1 = $mprice->price;
                $finalvalue=$finalvalue1 + ($finalvalue1*$percentage/100);
                // return response($finalvalue1, 200);
                //For accessory value based on the current options selected
                $accessorydata = $request->accessoryids;
                $tot_accessory_price = 0;
                $is_validbill = "no";
                

               //For mobile Final value based on the current conditions
               $wdmprice = MobilePricing::where('brand_id',$brand_id)->where('model_id',$model_id)->where('capacity_id',$capacity_id)->select("broken_price as price")->where('partner_id', 0)->first();
               $wdfinalvalue1 = $wdmprice->price;
               $wdfinalvalue=$wdfinalvalue1 + ($wdfinalvalue1*$percentage/100);

                // return response($accessorydata, 200);
                $storeexcprice=$pricedata[0]->exc_price + ($pricedata[0]->exc_price*$percentage/100);

                $final_price=sprintf('%0.2f',($finalvalue + $tot_accessory_price));
                $wdfinal_price=sprintf('%0.2f',($wdfinalvalue + $tot_accessory_price));

                $accessoryprice1 = Accessory::where('brand_id',$brand_id)->where('model_id',$model_id)->where('status','active')->sum('value');

                $accessoryprice = StorewiseOnlinePricingPercentage::where('store_id', $store_id)
                        ->where('status', 'active')
                        ->where('type', 'LFR')
                        ->selectRaw('
                            valid_bill +
                            original_box +
                            original_charging_cable +
                            original_charging_dock +
                            original_earphones +
                            original_strap as total_sum
                        ')
                        ->value('total_sum');

                $accessoryPricingDetails = DB::table('accessory')
                    ->select('id', 'value','accessory_name')
                    ->where('brand_id', $brand_id)
                    ->where('model_id', $model_id)
                    ->where('status', 'active')
                    ->get();

                $accData = '';

                

                if ($accessoryPricingDetails->isNotEmpty()) {
                    $accData1 = $accessoryPricingDetails->map(function ($item) use ($store_id) {
                        
                        $col_name = strtolower(str_replace(" ","_",$item->accessory_name));
                        $accprice = StorewiseOnlinePricingPercentage::where('store_id', $store_id)
                                ->where('status', 'active')
                                ->where('type', 'LFR')
                                ->value($col_name) ?? 0;

                        return $item->id . '::' . $accprice;
                    })->toArray();

                    $accData = implode(":,", $accData1);
                }

                $partner_id = 1;
                //For available selling options for partner to current store start
                $xchangeotps = array();
                
                    $xchangeotps = array(1,2,3);
                    $data['deviceprice'] = number_format(floor($final_price));
                    if($final_price > 0)
                    {
                        $data['devicepricedata'] = "* Get Upto ".number_format(floor($final_price)) ." *";
                        $data['accessoryprice'] = number_format(floor($accessoryprice));
                        if($accessoryprice > 0)
                        {
                            // $data['accessorypricedata'] = "*Additional value of ₹".number_format(floor($accessoryprice))." (For Accessories & Valid Invoice with warranty)";
                            $data['accessorypricedata'] = "* Get an additional value of ₹".number_format(floor($accessoryprice)).", if the device comes with genuine accessories and a valid purchase invoice with warranty.";
                        }else{
                            $data['accessorypricedata'] = "";
                        }
                        // $data['without_diag_deviceprice'] = number_format(floor($wdfinal_price));
                        // $data['Note'] = "**Conditions Apply: The price of the selected device is subject to change based on its final functional conditions.";
                        $data['Note'] = "**The price of the selected device is subject to change based on its final functional and physical evaluation.";
                    
                        // $data['allowed_exchange_optionsmsg'] = "No options are available to proceed with the device exchange.";

                        // $data['allowed_exchange_options']['mobileapp'] = "Proceed with Diagnostic App";
                        // $data['allowed_exchange_options']['manual'] = "Proceed with manual process";
                        // $data['allowed_exchange_options']['withoutqc'] = 'Skip diagnostics and get flat Rs.' . number_format($wdfinal_price);
                                           
                        // $data['allowed_exchange_options1'] = implode(",",$xchangeotps);


                    }else{
                        $data['devicepricedata'] = "Currently, we are unable to accept this device.";
                    }
                    
                
                // $data['accessoryprice'] = number_format(floor($accessoryprice));
                // $data['devicevaluedesc'] = "Get Upto Rs. " . number_format(floor($storeexcprice)) . "/- and Rs. " . number_format(floor($accessoryprice)) . "/- more on submitting valid bill(under/with warranty) and Accessories";
                // $data['accessorypricedata'] = "Extra ".number_format(floor($accessoryprice))." (For Accessories & Valid bill)";

                $productModls1 = ProductModels::where('category_id', $category_id)->where('id', $model_id)->where('brand_id', $brand_id)->where('status', 'active')->get();
                $BrandData = ProductBrands::find($brand_id);
                $CapdData = ProductCapacity::find($capacity_id);
                $ColData = ProductColor::find($color_id);
                $CapDetails = explode("/", $CapdData['capacity']);
                $qrdata1 = [
                    // 'Brand' => $BrandData['brand_name'],
                    // 'Model' => $productModls1[0]['model_name'],
                    // 'RAM' => trim($CapDetails['0']),
                    // 'ROM' => trim($CapDetails['1']),
                    // // 'Color' => $ColData['color'],
                    // 'IMEI' => $imei,
                    'RefNo' => $transaction_ref_no,

                ];


                $qrdata = $transaction_ref_no;
                $jsonData = $transaction_ref_no;
		        $qrfilename1 = 'qrcodeimgs/qrcode-'.time().'.png';
                $host = $_SERVER['HTTP_HOST'];
                $https = $_SERVER['HTTPS'];
                if($https == 'on')
                {
                    $siteurl = "https://$host/";
                }else{
                    $siteurl = "http://$host/";
                }
                $qrcode = $siteurl.$qrfilename1;


                // $path = 'qrcodes/example.png';
                QrCode::format('png')->size(300)->backgroundColor(255, 255, 255)->color(0, 0, 0)->generate($transaction_ref_no, $qrfilename1);

                             
                // $data['qrcode'] = $qrcode;
                

             

                //For inserting brand model data into api_item_details table
                // $update['brand_id'] = $brand_id;
                // $update['category_id'] = $category_id;
                // $update['model_id'] = $model_id;
                $update['base_price'] = $final_price;
                $update['accessory_price'] = $tot_accessory_price;
                $update['str_percentage'] = $percentage;
                $update['color_id'] = $color_id;
                $update['capacity_id'] = $capacity_id;
                $update['imei'] = $imei;
                $update['is_fake'] = $is_fake;
                $update['is_icloud_lock'] = $is_icloud_locked;
                $update['accessory_data'] = $accData;
                $update['purchase_date'] = date("Y-m-d",strtotime($purchase_date));
                
                // $update['cust_mobile'] = $request->customer_mobile;
                // $update['exe_physical_condition_id'] = $request->physical_condition_id;
                // return response($update, 200);
                $update = ApiWebItemDetails::where('transaction_ref_no', $transaction_ref_no)->update($update);

                //For successful fetch data
                $response["status"] = 1;
                $response["statuscode"] = 200;
                $response["messagetype"] = "";
                $response["message"] = "";
                $response["data"] = $data;
                return response($response, 200);
            } else {
                //when prices are not available
                $response["status"] = 0;
                $response["statuscode"] = 401;
                $response["messagetype"] = "No data found for the specified request";
                $response["message"] = "We are currently not accepting the selected device.";
                $response["data"] = [];
                return response($response, 401);
            }
        } else {
            //Response for invalid authentication
            $response["status"] = 0;
            $response["statuscode"] = 404;
            $response["messagetype"] = "Unauthorized request";
            $response["message"] = "You do not have permission to access this resource";
            $response["data"] = [];
            return response($response, 404);
        }
    }

   
    public function getExchangeConditions(Request $request)
    {



        //getting the information from the api service
        $headers = apache_request_headers();

      
        // $transaction_ref_no = isset($_SERVER['HTTP_TRANSACTIONREFNO']) ? $_SERVER['HTTP_TRANSACTIONREFNO'] : '';

        // $acctoken=$_SERVER['HTTP_ACCESSTOKEN'];
        //For getting body data from api service
        $transaction_ref_no = $request->TransactionRefNo;
        $date = date("Y-m-d H:i:s");
        // return response($category_id.'=>'.$brand_id.'=>'.$model_id.'=>'.$capacity_id.'=>'.$color_id.'=>'.$is_fake.'=>'.$is_icloud_locked.'=>>'.$transaction_ref_no , 404);
 
        $userdata = $userdata = Auth::user();
       

        $response = ["status" => 0, "message" => "No data found for the specified request", "description" => "", "data" => []];

        if (!empty($userdata) > 0) {
            $branch_id = $userdata->branch_id;
            $store_id = $userdata->store_id;
            $storedata = Stores::where('status', 'active')->where('id', $store_id)->get();
            if (sizeof($storedata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 404;
                $response["messagetype"] = "Unauthorised request";
                $response["message"] = "You do not have permission to access this resource, as the LFR is not enabled for using this resource";
                $response["data"] = [];
                return response($response, 404);
            }

            $storebranchdata = StoresRepeat::where('status', 'active')->where('parent_id', $store_id)->where('store_branch', $branch_id)->get();
            if (sizeof($storebranchdata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 404;
                $response["messagetype"] = "Unauthorized request";
                $response["message"] = "You do not have permission to access this resource, as the branch is not enabled for using this resource";
                $response["data"] = [];
                return response($response, 404);
            }
            
            if (empty($transaction_ref_no)) {
                //Response for invalid input details
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "All required parameters are missing - TransactionRefNo";
                $response["data"] = [];
                return response($response, 200);
            }

            
          
            //Checking for valid teansaction_ref_no with branch and status
            $refdata = ApiWebItemDetails::where('transaction_ref_no', $transaction_ref_no)->get();
            if (sizeof($refdata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "No data found for the specified request. Please check the TransactionRefNo";
                $response["data"] = [];
                return response($response, 200);
            }
            if ($store_id != $refdata[0]["store_id"]) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "TransactionRefNo does not belong to your account or request.";
                $response["data"] = [];
                return response($response, 200);
            }
            if ($branch_id != $refdata[0]["branch_id"]) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "TransactionRefNo does not belong to your branch or request.";
                $response["data"] = [];
                return response($response, 200);
            }
            if ($refdata[0]["status"] != 'created') {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "The requested TransactionRefNo has already been applied for an exchange.";
                $response["data"] = [];
                return response($response, 200);
            }
            

            $user_id = $userdata->id;
            $branch_id = $userdata->branch_id;

            $category_id = $refdata[0]->category_id;
            $brand_id = $refdata[0]->brand_id;
            $model_id = $refdata[0]->model_id;
            $capacity_id = $refdata[0]->capacity_id;
            // query to retrieve store capacity data 
            $pricedata = MobilePricing::select('*')
                ->where('status', 'active')->where('model_id', $model_id)->where('capacity_id', $capacity_id)->where('partner_id', 0)->get();
            //|| date("Y-m-d",strtotime($request->purchase_date)) != $refdata[0]->purchase_date
            //  return response($pricedata, 200);
            

            if (sizeof($pricedata) > 0) {
                //To get the product wise pricing percentage data with branch id
                $pstr_percentage = StorewiseOnlinePricingPercentage::where('store_id', $store_id)->where('status', 'active')->where('branch_id', $branch_id)->where('category_id', $category_id)->where('brand_id', $brand_id)->where('model_id', $model_id)->where('type', 'product')->get();
                if (sizeof($pstr_percentage) > 0) {
                    $percentage = $pstr_percentage[0]->percentage;
                } else {
                    //To get the product wise pricing percentage data without branch id
                    $pbstr_percentage = StorewiseOnlinePricingPercentage::where('store_id', $store_id)->where('status', 'active')->where('branch_id', '0')->where('category_id', $category_id)->where('brand_id', $brand_id)->where('model_id', $model_id)->where('type', 'product')->get();
                    if (sizeof($pbstr_percentage) > 0) {
                        $percentage = $pbstr_percentage[0]->percentage;
                    } else {
                        //To get the branch wise pricing percentage data 
                        $bstr_percentage = StorewiseOnlinePricingPercentage::where('store_id', $store_id)->where('branch_id', $branch_id)->where('status', 'active')->where('type', 'branch')->get();
                        if (sizeof($bstr_percentage) > 0) {
                            $percentage = $bstr_percentage[0]->percentage;
                        } else {
                            //To get the store wise pricing percentage data 
                            $ststr_percentage = StorewiseOnlinePricingPercentage::where('store_id', $store_id)->where('status', 'active')->where('type', 'LFR')->get();
                            if (sizeof($ststr_percentage) > 0) {
                                $percentage = $ststr_percentage[0]->percentage;
                            } else {
                                //if above percentages are not available then we consider percentage as 0
                                $percentage = 0;
                            }
                        }
                    }
                }

                //Calculating the excellent price basedon the percentage
                $storeexcprice = $pricedata[0]->exc_price + ($pricedata[0]->exc_price * $percentage / 100);

                //getting the accessory price for selected products
                // $accessoryprice = Accessory::where('brand_id', $brand_id)->where('model_id', $model_id)->where('status', 'active')->sum('value');

                $accessoryprice = StorewiseOnlinePricingPercentage::where('store_id', $store_id)
                        ->where('status', 'active')
                        ->where('type', 'LFR')
                        ->selectRaw('
                            valid_bill +
                            original_box +
                            original_charging_cable +
                            original_charging_dock +
                            original_earphones +
                            original_strap as total_sum
                        ')
                        ->value('total_sum');

                // $data['baseprice'] = number_format(floor($storeexcprice));
                // $data['basepricedata'] = "Get Upto ".number_format(floor($storeexcprice));
                // $data['accessoryprice'] = number_format(floor($accessoryprice));
                // $data['accessorypricedata'] = "Extra ".number_format(floor($accessoryprice))." (For Accessories & Valid bill)";

                //getting the condition categories based on category
                $modelDetails = ProductModels::where('id', $model_id)->get();
                $facelock = $modelDetails['0']->face_lock;
                $fingerprint = $modelDetails['0']->finger_print;
                if ($facelock == 'yes' && $fingerprint == 'yes') {
                    $condition_categories = ConditionCategories::where('status', 'active')->where('condition_type_id', '2')->where('category_id', $category_id)->select('id', 'category_name','cat_img','description','image1','image2','image3')->orderBy('priority', 'DESC')->orderBy('category_name', 'ASC')->get();
                } elseif ($facelock == 'yes' && $fingerprint == 'no') {
                    $condition_categories = ConditionCategories::where('status', 'active')->where('condition_type_id', '2')->where('category_id', $category_id)->where('category_name', '!=', 'finger print')->select('id', 'category_name','cat_img','description','image1','image2','image3')->orderBy('priority', 'DESC')->orderBy('category_name', 'ASC')->get();
                } elseif ($facelock == 'no' && $fingerprint == 'yes') {
                    $condition_categories = ConditionCategories::where('status', 'active')->where('condition_type_id', '2')->where('category_id', $category_id)->where('category_name', '!=', 'face lock')->select('id', 'category_name','cat_img','description','image1','image2','image3')->orderBy('priority', 'DESC')->orderBy('category_name', 'ASC')->get();
                } else {
                    $condition_categories = ConditionCategories::where('status', 'active')->where('condition_type_id', '2')->where('category_id', $category_id)->where('category_name', '!=', 'face lock')->where('category_name', '!=', 'finger print')->select('id', 'category_name','cat_img','description','image1','image2','image3')->orderBy('priority', 'DESC')->orderBy('category_name', 'ASC')->get();
                }

                $host = $_SERVER['HTTP_HOST'];
                $https = $_SERVER['HTTPS'];
                if($https == 'on')
                {
                    $siteurl = "https://$host/";
                }else{
                    $siteurl = "http://$host/";
                }

                $functionalpath = $siteurl."functional_logos/";

                // return response($condition_categories, 401);
                // $condition_categories = ConditionCategories::where('status','active')->where('condition_type_id','2')->where('category_id',$category_id)->select('id','category_name')->get();
                // $data['condition_categories'] = $condition_categories;

                //For getting the condition options based on condition category
                $conditionOptions = [];
                foreach ($condition_categories as $condition_category) {
                    $condition_categories_id = $condition_category->id;
                    $condition_category_name = $condition_category->category_name;
                    $cat_img = $condition_category->cat_img;
                    $description = $condition_category->description;
                    $image1 = $condition_category->image1;
                    $image2 = $condition_category->image2;
                    $image3 = $condition_category->image3;
                    // $condition_sub_categories = ConditionOptions::where('status', 'active')->where('condition_categories_id', $condition_categories_id)->select('id', 'con_option')->get();
                    
                    //Based on condition score sending is_correct
                    $condition_sub_categories = ConditionOptions::where('status', 'active')->where('condition_categories_id', $condition_categories_id)->select('id', 'con_option','con_score')->get()->map(function ($item) {
                        $item->is_correct = ($item->con_score == 0) ? 1 : 0;
                        unset($item->con_score);
                        return $item;
                    });
                    
                    // $data['condition_categories_id'] = $condition_categories_id;
                    // $data['condition_category_name'] = $condition_category_name;
                    // $data['condition_options'][$condition_category_name] = $condition_sub_categories;

                    $data['condition_options_label'] = "Please choose or select the options that are functionally operational and applicable.";

                    $conditionOptions[$condition_categories_id] = [
                        "condition_categories_id" => $condition_categories_id,
                        "condition_category_name" => $condition_category_name,
                        "condition_category_img" => $functionalpath.$cat_img,
                        "description" => $description,
                        "image1" => !empty($image1) ? $functionalpath.$image1: "",
                        "image2" => !empty($image2) ? $functionalpath.$image2: "",
                        "image3" => !empty($image3) ? $functionalpath.$image3: "",
                        "options" => []
                    ];

                    $conditionOptions[$condition_categories_id]["options"] = $condition_sub_categories;


                }
                $conditionOptions = array_values($conditionOptions);

                $data['condition_options'] = $conditionOptions;
                //For list of physical conditions and description
                // return response($interval, 401);
                $purchase_date = $refdata[0]->purchase_date;
                $today = date("Y-m-d");
                $test_arr  = explode('-', $purchase_date);
                $diff = strtotime($purchase_date) - strtotime($today);
                $interval = abs(round($diff / 86400));

                // $interval = "100";
                if ($interval > "330") {
                    $physical_condition = ConditionCategories::where('status', 'active')->where('condition_type_id', '1')->where('category_name', '!=', 'excellent')->select('id', 'category_name', 'remarks as description')->get()->map(function($item) {
                        $item->category_name = ucwords($item->category_name);
                        $item->description = ucwords($item->description);
                        return $item;
                    });
                } else {
                    $physical_condition = ConditionCategories::where('status', 'active')->where('condition_type_id', '1')->select('id', 'category_name', 'remarks as description')->get()->map(function($item) {
                        $item->category_name = ucwords($item->category_name);
                        $item->description = ucwords($item->description);
                        return $item;
                    });
                }
                $data['physical_condition'] = $physical_condition;

                //For list of accessories
                $accessoryimgpath = $siteurl."accessory_logos/";
                $accessorydata = Accessory::leftJoin('accessory_type', 'accessory_type.name', '=', 'accessory.accessory_name')->where('category_id', $category_id)->where('brand_id', $brand_id)->where('model_id', $model_id)->where('partner_id', 0)->where('accessory.status', 'active')->select('accessory.id', 'accessory_name',DB::raw("CONCAT('" . $accessoryimgpath . "', acc_image) as accimage"),DB::raw("CASE WHEN accessory_name IS NOT NULL AND accessory_name = 'valid bill' THEN 1 ELSE 0 END as isbill"))->get()->map(function($item) {
                    $item->accessory_name = ucwords($item->accessory_name);
                    
                    return $item;
                });


                // $data['accessoryimgpath'] = $accessoryimgpath;
                $data['accessorydata'] = $accessorydata;


                $smartupgradecount = Aeb::where('store_id', $store_id)->where('selling_model_id', $model_id)->where('status', 'active')->where('selling_capacity_id', $capacity_id)->count();

             



                //For inserting brand model data into api_item_details table 
                // $update['brand_id'] = $brand_id;
                // $update['model_id'] = $model_id;
                $update['base_price'] = $storeexcprice;
                $update['accessory_price'] = $accessoryprice;
                $update['str_percentage'] = $percentage;
                // $update['color_id'] = $color_id;
                // $update['capacity_id'] = $capacity_id;
                // $update['imei'] = $imei;
                // $update['is_fake'] = $is_fake;
                // $update['is_icloud_lock'] = $is_icloud_locked;
                // $update['purchase_date'] = $purchase_date;
                $update = ApiWebItemDetails::where('transaction_ref_no', $transaction_ref_no)->update($update);

                //For successful fetch data
                $response["status"] = 1;
                $response["statuscode"] = 200;
                $response["messagetype"] = "";
                $response["message"] = "";
                $response["data"] = $data;
                return response($response, 200);
            } else {
                //when prices are not available
                $response["status"] = 0;
                $response["statuscode"] = 401;
                $response["messagetype"] = "No data found for the specified request";
                $response["message"] = "We are currently not accepting the selected device.";
                $response["data"] = [];
                return response($response, 401);
            }
        } else {
            //Response for invalid authentication
            $response["status"] = 0;
            $response["statuscode"] = 404;
            $response["messagetype"] = "Unauthorized request";
            $response["message"] = "You do not have permission to access this resource";
            $response["data"] = [];
            return response($response, 404);
        }
    }
       
    public function getExchangeFinalPrice(Request $request)
    {

        $userdata = Auth::user();
        // return response($userdata, 200);

     
        //For getting body data from api service
        
        $transaction_ref_no = $request->TransactionRefNo;

        
       
        $date = date("Y-m-d H:i:s");
       
        $response = ["status" => 0, "message" => "No data found for the specified request", "description" => "", "data" => []];

        if (!empty($userdata) > 0) {
            $branch_id = $userdata->branch_id;
            $city_id = $userdata->city_id;
            $state_id = $userdata->location_id;
            $store_id = $userdata->store_id;


            $storedata = Stores::where('status', 'active')->where('id', $store_id)->get();
            if (sizeof($storedata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 404;
                $response["messagetype"] = "Unauthorised request";
                $response["message"] = "You do not have permission to access this resource, as the LFR is not enabled for using this resource";
                $response["data"] = [];
                return response($response, 404);
            }

            $storebranchdata = StoresRepeat::where('status', 'active')->where('parent_id', $store_id)->where('store_branch', $branch_id)->get();
            if (sizeof($storebranchdata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 404;
                $response["messagetype"] = "Unauthorized request";
                $response["message"] = "You do not have permission to access this resource, as the branch is not enabled for using this resource";
                $response["data"] = [];
                return response($response, 404);
            }
            if (empty($transaction_ref_no)) {
                //Response for invalid input details
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "All required parameters are missing - TransactionRefNo";
                $response["data"] = [];
                return response($response, 200);
            }
            //Checking for valid teansaction_ref_no with branch and status
            // $refdata = ApiWebItemDetails::where('transaction_ref_no',$transaction_ref_no)->where('status','created')->where('store_id',$store_id)->where('branch_id',$branch_id)->get();
            $refdata = ApiWebItemDetails::where('transaction_ref_no', $transaction_ref_no)->get();
            if (sizeof($refdata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "No data found for the specified request. Please check the TransactionRefNo";
                $response["data"] = [];
                return response($response, 200);
            }
            // return response($transaction_ref_no ,200);
            if ($store_id != $refdata[0]["store_id"]) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "TransactionRefNo does not belong to your account or request.";
                $response["data"] = [];
                return response($response, 200);
            }
            if ($branch_id != $refdata[0]["branch_id"]) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "TransactionRefNo does not belong to your branch or request.";
                $response["data"] = [];
                return response($response, 200);
            }
            if ($refdata[0]["status"] != 'created') {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "The requested TransactionRefNo has already been applied for an exchange.";
                $response["data"] = [];
                return response($response, 200);
            }

            

            $interval = 0;
            
            $user_id = $userdata->id;
            $branch_id = $userdata->branch_id;

            $partner_id = $refdata[0]["partner_id"];
            $model_id = $refdata[0]["model_id"];
            $capacity_id = $refdata[0]["capacity_id"];
            $color_id = $refdata[0]["color_id"];
            $category_id = $refdata[0]["category_id"];
            $brand_id = $refdata[0]["brand_id"];
            // $partner_id = $refdata[0]["partner_id"];
            // $partner_id = $refdata[0]["partner_id"];

            // query to retrieve store capacity data 
            $pricedata = MobilePricing::select('*')->where('status', 'active')->where('model_id', $model_id)->where('capacity_id', $capacity_id)->where('partner_id', 0)->get();



            if (sizeof($pricedata) > 0) {
                //To get the product wise pricing percentage data with branch id
                $pstr_percentage = StorewiseOnlinePricingPercentage::where('store_id', $store_id)->where('status', 'active')->where('branch_id', $branch_id)->where('category_id', $category_id)->where('brand_id', $brand_id)->where('model_id', $model_id)->where('type', 'product')->get();
                if (sizeof($pstr_percentage) > 0) {
                    $percentage = $pstr_percentage[0]->percentage;
                } else {
                    //To get the product wise pricing percentage data without branch id
                    $pbstr_percentage = StorewiseOnlinePricingPercentage::where('store_id', $store_id)->where('status', 'active')->where('branch_id', '0')->where('category_id', $category_id)->where('brand_id', $brand_id)->where('model_id', $model_id)->where('type', 'product')->get();
                    if (sizeof($pbstr_percentage) > 0) {
                        $percentage = $pbstr_percentage[0]->percentage;
                    } else {
                        //To get the branch wise pricing percentage data 
                        $bstr_percentage = StorewiseOnlinePricingPercentage::where('store_id', $store_id)->where('branch_id', $branch_id)->where('status', 'active')->where('type', 'branch')->get();
                        if (sizeof($bstr_percentage) > 0) {
                            $percentage = $bstr_percentage[0]->percentage;
                        } else {
                            //To get the store wise pricing percentage data 
                            $ststr_percentage = StorewiseOnlinePricingPercentage::where('store_id', $store_id)->where('status', 'active')->where('type', 'LFR')->get();
                            if (sizeof($ststr_percentage) > 0) {
                                $percentage = $ststr_percentage[0]->percentage;
                            } else {
                                //if above percentages are not available then we consider percentage as 0
                                $percentage = 0;
                            }
                        }
                    }
                }

                // $percentage = 0;

                //Calculating the excellent price basedon the percentage
                $storeexcprice = $pricedata[0]->exc_price + ($pricedata[0]->exc_price * $percentage / 100);

                //getting the accessory price for selected products
                // $accessoryprice = Accessory::where('brand_id', $brand_id)->where('model_id', $model_id)->where('status', 'active')->sum('value');
                $accessoryprice = StorewiseOnlinePricingPercentage::where('store_id', $store_id)
                        ->where('status', 'active')
                        ->where('type', 'LFR')
                        ->selectRaw('
                            valid_bill +
                            original_box +
                            original_charging_cable +
                            original_charging_dock +
                            original_earphones +
                            original_strap as total_sum
                        ')
                        ->value('total_sum');

                // $data['baseprice'] = number_format(floor($storeexcprice));
                // $data['basepricedata'] = "Get Upto ".number_format(floor($storeexcprice));
                // $data['accessoryprice'] = number_format(floor($accessoryprice));
                // $data['accessorypricedata'] = "Extra ".number_format(floor($accessoryprice))." (For Accessories & Valid bill)";

                //getting the condition categories based on category
                // $condition_categories = ConditionCategories::where('status','active')->where('condition_type_id','2')->where('category_id',$category_id)->select('id','category_name')->get();
                $modelDetails = ProductModels::where('id', $model_id)->get();
                $facelock = $modelDetails['0']->face_lock;
                $fingerprint = $modelDetails['0']->finger_print;
                if ($facelock == 'yes' && $fingerprint == 'yes') {
                    $condition_categories = ConditionCategories::where('status', 'active')->where('condition_type_id', '2')->where('category_id', $category_id)->select('id', 'category_name')->orderBy('priority', 'DESC')->orderBy('category_name', 'ASC')->get();
                } elseif ($facelock == 'yes' && $fingerprint == 'no') {
                    $condition_categories = ConditionCategories::where('status', 'active')->where('condition_type_id', '2')->where('category_id', $category_id)->where('category_name', '!=', 'finger print')->select('id', 'category_name')->orderBy('priority', 'DESC')->orderBy('category_name', 'ASC')->get();
                } elseif ($facelock == 'no' && $fingerprint == 'yes') {
                    $condition_categories = ConditionCategories::where('status', 'active')->where('condition_type_id', '2')->where('category_id', $category_id)->where('category_name', '!=', 'face lock')->select('id', 'category_name')->orderBy('priority', 'DESC')->orderBy('category_name', 'ASC')->get();
                } else {
                    $condition_categories = ConditionCategories::where('status', 'active')->where('condition_type_id', '2')->where('category_id', $category_id)->where('category_name', '!=', 'face lock')->where('category_name', '!=', 'finger print')->select('id', 'category_name')->orderBy('priority', 'DESC')->orderBy('category_name', 'ASC')->get();
                }
                // return response($condition_categories, 200);
                // $data['condition_categories'] = $condition_categories;
                $FunctionalData = array();
                $conoptdata = array();
                $invconoptdata = array();
                $total_score = 0;
                $exe_functional_options = array();
                //For getting the condition options based on condition category
                $con_cat_percent = array();
                foreach ($condition_categories as $condition_category) {
                    $condition_categories_id = $condition_category->id;
                    $condition_category_name = $condition_category->category_name;
                    // $FunctionalData[]['key'] = ucwords($condition_categories_id);
                    // $FunctionalData[]['title'] = ucwords($condition_category_name);
                    $con_cat = isset($request->condition_options[$condition_categories_id]) ? $request->condition_options[$condition_categories_id] : 0;

                    if ($con_cat == 0) {
                        $conoptdata[] = $condition_category_name;
                    } else {
                        // $scoreopt = ConditionOptions::find($con_cat);
                        $scoreopt = ConditionOptions::leftJoin('condition_categories as cc', 'cc.id', '=', 'condition_options.condition_categories_id')->where('condition_options.id', $con_cat)->where('cc.category_name', $condition_category_name)->get();
                        // return response($scoreopt, 200);
                        if (sizeof($scoreopt) > 0) {
                            if($scoreopt[0]->con_option == 'working' || $scoreopt[0]->con_option == 'yes' || $scoreopt[0]->con_option == 'pass' || $scoreopt[0]->con_option == 'true')
                            {
                                $funopt = 1;
                            }else{
                                $funopt = 0;
                            }
                            $FunctionalData[] = [
                                'key' => ucwords($condition_categories_id),
                                'title' => ucwords($condition_category_name),
                                'value' => $funopt
                            ];
                            // $FunctionalData[]['value'] = ucwords($funopt);
                            if ($condition_category_name != 'finger print' && $condition_category_name != 'face lock') {
                                $total_score = $total_score + $scoreopt[0]->con_score;
                            } else {
                                $con_cat_percent[] = $con_cat;
                            }
                        } else {
                            $invconoptdata[] = $condition_category_name;
                        }
                        $exe_functional_options[] = $con_cat;
                        // $total_score = $total_score + $scoreopt->con_score;
                    }

                    // $condition_sub_categories = ConditionOptions::where('status','active')->where('condition_categories_id',$condition_categories_id)->select('id','con_option')->get();
                    // $data['condition_options'][$condition_category_name] = $condition_sub_categories;
                }
                // return response($FunctionalData, 200);
                $exe_functional_option = implode(",", $exe_functional_options);
                //For missed condition options data
                if (sizeof($conoptdata) > 0) {
                    //Response for missed condition options
                    $response["status"] = 0;
                    $response["statuscode"] = 400;
                    $response["messagetype"] = "Bad Request";
                    $response["message"] = "All required parameters are missing for " . implode(', ', $conoptdata);
                    $response["data"] = [];
                    return response($response, 200);
                }
                //For invalid condition options data
                if (sizeof($invconoptdata) > 0) {
                    //Response for invalid condition options
                    $response["status"] = 0;
                    $response["statuscode"] = 400;
                    $response["messagetype"] = "Bad Request";
                    $response["message"] = "Invalid parameter values, please check the values to be passed in this request for Condition options " . implode(', ', $invconoptdata);
                    $response["data"] = [];
                    return response($response, 200);
                }

                //For physical condition options data
                $condition_categories = ConditionCategories::where('id', $request->physical_condition_id)->where('condition_type_id', '1')->get();
                if (sizeof($condition_categories) > 0) {
                    //physical condition name
                    $phy_catname = $condition_categories[0]->category_name;
                    $priphyresultdata = PricingConditions::where('condition_name', $phy_catname)->get();
                } else {
                    //Response for invalid physical condition options
                    $response["status"] = 0;
                    $response["statuscode"] = 400;
                    $response["messagetype"] = "Bad Request";
                    $response["message"] = "Invalid parameter values, please check the values being passed in this request for Physical conditions, not a valid parameter value";
                    $response["data"] = [];
                    return response($response, 200);
                }

                //For getting functional condition information
                // $total_score = 2;
                $fresultdatacount = FunctionalResult::where('score', $total_score)->count();
                if ($fresultdatacount < 1) {
                    $priresultdata = PricingConditions::where('condition_name', 'broken')->get();
                    $functional_condition = $priresultdata[0]->id;
                    $fun_cond_name = "broken";
                } else {
                    $priresultdata = FunctionalResult::leftJoin('pricing_conditions as pc', 'pc.id', '=', 'functional_result.pricing_condition_id')->where('functional_result.score', $total_score)->select('pc.id as id', 'pc.condition_name')->get();
                    $functional_condition = $priresultdata[0]->id;
                    $fun_cond_name = $priresultdata[0]->condition_name;
                }

                //For final condition of the device based on physical and functional conditions
                $finalData = FinalCondition::leftJoin('pricing_conditions as pc', 'pc.id', '=', 'final_condition.final_condition')->where('final_condition.functional_condition', $functional_condition)->where('final_condition.physical_condition', $priphyresultdata[0]->id)->select('pc.id as pri_condition_id', 'pc.condition_name')->get();


                $final_condition = $finalData['0']->condition_name;
                $pri_condition_id = $finalData['0']->pri_condition_id;
                if ($final_condition == 'excellent') {
                    $fp = "exc_price";
                } elseif ($final_condition == 'good') {
                    $fp = "good_price";
                } elseif ($final_condition == 'fair') {
                    $fp = "fair_price";
                } elseif ($final_condition == 'broken') {
                    $fp = "broken_price";
                } else {
                    $fp = "broken_price";
                }

                //For mobile Final value based on the current conditions
                $mprice = MobilePricing::where('brand_id', $brand_id)->where('model_id', $model_id)->where('capacity_id', $capacity_id)->select("$fp as price")->where('partner_id', 0)->first();
                $finalvalue1 = $mprice->price;
                $finalvalue = $finalvalue1 + ($finalvalue1 * $percentage / 100);
                // return response($finalvalue1, 200);
                //For accessory value based on the current options selected
                $accessorydata = $request->accessoryids;
                $tot_accessory_price = 0;
                $is_validbill = "no";
                if (!empty($accessorydata)) {
                    $accessorieaData = explode(",", $accessorydata);
                    foreach ($accessorieaData as $accessory_id) {
                        // $accData=mysqli_query($conn,"select * from accessory where id='$accessory_id'");
                        $accData = Accessory::where('id', $accessory_id)->get();
                        $AccessoryDetails = $accData[0];
                        $accvalue = $AccessoryDetails->value;
                        $accname = $AccessoryDetails->accessory_name;
                        // return response($accessorydata, 200);

                        if (strtolower($accname) == "valid bill") {
                            $is_validbill = "yes";
                        }
                        // if ($accvalue == '0.00' || empty($accvalue)) {
                        //     $accpercentage = $AccessoryDetails->percentage;
                        //     $percentage1 = $accpercentage / 100;
                        //     $accprice1 = $finalvalue * $percentage1;
                        //     $accprice = sprintf('%0.2f', $accprice1);
                        // } else {
                        //     $accprice = $accvalue;
                        // }

                        $col_name = strtolower(str_replace(" ","_",$accname));
                        $accprice = StorewiseOnlinePricingPercentage::where('store_id', $store_id)
                                ->where('status', 'active')
                                ->where('type', 'LFR')
                                ->value($col_name) ?? 0;

                        $tot_accessory_price += $accprice;
                    }
                }
                $bill_date = null;
                if ($is_validbill == "yes") {
                    // return response($request, 200);
                    $bill_date = $request->bill_date;
                    if (!isset($bill_date)) {
                        $response["status"] = 0;
                        $response["statuscode"] = 400;
                        $response["messagetype"] = "Bad Request";
                        $response["message"] = "Date of Invoice is mandatory, if an accessory ID for a valid bill is provided.";
                        $response["data"] = [];
                        return response($response, 200);
                    }
                    $test_arr1  = explode('-', $bill_date);
                    if (count($test_arr1) == 3) {
                        if (!checkdate($test_arr1[1], $test_arr1[0], $test_arr1[2])) {

                            $response["status"] = 0;
                            $response["statuscode"] = 400;
                            $response["messagetype"] = "Bad Request";
                            $response["message"] = "Invalid date format. Please provide the bill_date in the dd-mm-yyyy format.";
                            $response["data"] = [];
                            return response($response, 200);
                        } else {
                            if ($test_arr1[2] < 1990) {
                                $response["status"] = 0;
                                $response["statuscode"] = 400;
                                $response["messagetype"] = "Bad Request";
                                $response["message"] = "Invalid format. The year of bill_date must be 1990 or later.";
                                $response["data"] = [];
                                return response($response, 200);
                            }
                            $today = date("d-m-Y");

                            if (strtotime($bill_date) > strtotime($today)) {
                                $response["status"] = 0;
                                $response["statuscode"] = 400;
                                $response["messagetype"] = "Bad Request";
                                $response["message"] = "Invalid date. The bill_date cannot be a future date.";
                                $response["data"] = [];
                                return response($response, 200);
                            }

                            $diff = strtotime($bill_date) - strtotime($today);
                            $interval = abs(round($diff / 86400));
                        }
                    } else {
                        $response["status"] = 0;
                        $response["statuscode"] = 400;
                        $response["messagetype"] = "Bad Request";
                        $response["message"] = "Invalid date format. Please provide the bill_date in the dd-mm-yyyy format.";
                        $response["data"] = [];
                        return response($response, 200);
                    }
                }

                // return response($accessorydata, 200);


                $final_price = sprintf('%0.2f', ($finalvalue + $tot_accessory_price));
                // return response($final_price, 200);


                // //For list of physical conditions and description
                // $physical_condition = ConditionCategories::where('status','active')->where('condition_type_id','1')->select('id','category_name','remarks as description')->get();
                // $data['physical_condition'] = $physical_condition;

                // //For list of accessories
                // $accessorydata = Accessory::where('category_id',$category_id)->where('brand_id',$brand_id)->where('model_id',$model_id)->where('status','active')->select('id','accessory_name')->get();
                // $data['accessorydata'] = $accessorydata;

                //For face lock and finger pring options are not working calculating the diduction amount 
                $deduct_accessory_price = 0;
                if (sizeof($con_cat_percent) > 0) {

                    $fprintoptdata = ProductModels::where('id', $model_id)->first();

                    $codcatdatacount = ConditionOptions::whereIn('condition_options.id', $con_cat_percent)->where('con_option','not working')->count();

                    if($fprintoptdata->finger_print == 'yes' && $fprintoptdata->finger_print == 'yes' && $codcatdatacount > 1 )
                    {
                        $FunAccessoryDetails = Accessory::where('type', "functional")->orderBy('percentage','DESC')->limit(1)->get();
                        $Faccvalue = $FunAccessoryDetails[0]->value;

                        if ($Faccvalue == '0.00' || empty($Faccvalue)) {
                            $accpercentage = $FunAccessoryDetails[0]->percentage;
                            // return response($FunAccessoryDetails, 200); 
                            $percentage2 = $accpercentage / 100;
                            //$accprice1=$final_price * $percentage;
                            $accprice1 = $finalvalue * $percentage2;
                            $Faccprice = sprintf('%0.2f', $accprice1);
                        } else {
                            $Faccprice = $Faccvalue;
                        }
                        $deduct_accessory_price += $Faccprice;
                        // return response($deduct_accessory_price, 200); 
                    }else{
                        $codcatdata = ConditionOptions::leftJoin('condition_categories as cc', 'cc.id', '=', 'condition_options.condition_categories_id')->whereIn('condition_options.id', $con_cat_percent)->select('category_name', 'con_option')->get();
                        $deduct_accessory_price = 0;
                        foreach ($codcatdata as $codcatdetails) {
                            if ($codcatdetails->con_option != 'working') {
                                $categ_name = $codcatdetails->category_name;
                                $categ_name1 = str_replace(' ', '_', $categ_name);
                                $fprintopt = ProductModels::where($categ_name1, 'yes')->where('id', $model_id)->count();
                                if ($fprintopt > 0) {
                                    $FunAccessoryDetails = Accessory::where('accessory_name', $categ_name)->get();
                                    if (sizeof($FunAccessoryDetails) > 0) {
                                        $Faccvalue = $FunAccessoryDetails[0]->value;

                                        if ($Faccvalue == '0.00' || empty($Faccvalue)) {
                                            $accpercentage = $FunAccessoryDetails[0]->percentage;
                                            // return response($FunAccessoryDetails, 200); 
                                            $percentage2 = $accpercentage / 100;
                                            //$accprice1=$final_price * $percentage;
                                            $accprice1 = $finalvalue * $percentage2;
                                            $Faccprice = sprintf('%0.2f', $accprice1);
                                        } else {
                                            $Faccprice = $Faccvalue;
                                        }
                                    } else {
                                        $Faccprice = 0;
                                    }
                                } else {
                                    $Faccprice = 0;
                                }
                                $deduct_accessory_price += $Faccprice;
                            }
                        }
                    }
                    // return response($deduct_accessory_price, 200); 

                    
                    // return response($deduct_accessory_price, 200);
                }

               
                $discountprice = 0;
                $promodiscountprice = 0;
                $promotional_discount_id = 0;
                //For negotiationcalculation lfr wise,lfrbranch wise, product wise....
                $neg_applicable = "No";
                $neg_negitive = "No";
                $pro_neg_percentage = 0;
                $wallet_balance = 0;

                //calculating grand total (deducting finger_print and face_lock from final price)
                $grandfinal_price = floor($final_price - $deduct_accessory_price);
                $negotiation_value = 0;

                //For smart upgrade prices calculation
                $buyingprice = 0;
                $lfrval = 0;
                $minteval = 0;
                $smart_model_data = "";
                // return response("Here", 401);
                $buyingprice1 = 0;

                // return response("Here1", 401);

                $MobilePricingDetails = MobilePricing::where('brand_id', $brand_id)->where('model_id', $model_id)->where('capacity_id', $capacity_id)->where('partner_id', 0)->first();

                $exc_price1 = $MobilePricingDetails->exc_price;
                $storeexcpercentage1 = $MobilePricingDetails->exc_price * $percentage / 100;
                $cur_exc_price = $exc_price1 + $storeexcpercentage1;

                $good_price1 = $MobilePricingDetails->good_price;
                $storegdpercentage1 = $MobilePricingDetails["good_price"] * $percentage / 100;
                $cur_good_price = $good_price1 + $storegdpercentage1;

                $fair_price1 = $MobilePricingDetails->fair_price;
                $storefrpercentage1 = $MobilePricingDetails->fair_price * $percentage / 100;
                $cur_fair_price = $fair_price1 + $storefrpercentage1;

                $broken_price1 = $MobilePricingDetails->broken_price;
                $storebrpercentage1 = $MobilePricingDetails->broken_price * $percentage / 100;
                $cur_broken_price = $broken_price1 + $storebrpercentage1;

                $cur_all_prices = $cur_exc_price . '::CUR::' . $cur_good_price . '::CUR::' . $cur_fair_price . '::CUR::' . $cur_broken_price;

                $partner_id = 1;
                //For coupon avalibility check start
               $coupon_avalibility ="no";
                    // return response($offersAvail, 200);
                   
                 //for Schemes check end





                //For inserting brand model data into api_item_details table
                $update['coupon_avalibility'] = $coupon_avalibility;
                $update['exe_functional_option'] = $exe_functional_option;
                $update['exe_physical_option'] = $phy_catname;
                $update['exe_physical_condition_id'] = $request->physical_condition_id;
                $update['exe_final_condition'] = $final_condition;
                $update['exe_accessory'] = $accessorydata;
                $update['is_neg_app'] = $neg_applicable;
                $update['org_neg_val'] = $negotiation_value;
                $update['buying_values'] = $buyingprice;
                $update['minte_buy_val'] = $minteval;
                $update['lfr_buy_val'] = $lfrval;
                $update['exc_price'] = $cur_exc_price;
                $update['good_price'] = $cur_good_price;
                $update['fair_price'] = $cur_fair_price;
                $update['broken_price'] = $cur_broken_price;
                $update['discount_price'] = $discountprice;
                $update['special_discount'] = $promodiscountprice;
                $update['cust_name'] = $request->customer_name;
                $update['cust_mobile'] = $request->customer_mobile;
                $update['exe_price'] = $grandfinal_price;
                $update['smartupgrade_models'] = $smart_model_data;
                $update['fun_cond_name'] = $fun_cond_name;
                $update['valid_bill'] = $is_validbill;
                $update['bill_date'] = isset($bill_date) ? date("Y-m-d",strtotime($bill_date)) :"";
                // $update['offers_data'] = $offersAvail;
                
                
                $modeldata = Products::query();
                $modeldata = $modeldata->select('brand_name', 'model_name')->leftJoin('brands as pb','pb.id','products.brand')->where('products.id',$model_id)->where('brand',$brand_id)->first();
                
                

                $capacitydata = ProductsCapacity::select('pc.id as capacity_id', 'pc.capacity')
                ->leftJoin('mobile_capacity as pc', 'pc.id', '=', 'product_capacity.mobile_capacity_id')
                ->where('pc.status', 'active')->where('pc.id',$capacity_id)->where('pc.capacity', '!=', 'N/A')->first();

                // $modelDetails = ucwords($modeldata->brand_name).' - '.ucwords($modeldata->model_name). \n .ucwords($capacitydata->capacity);
                $modelDetails = ucwords($modeldata->brand_name) . ' - ' . ucwords($modeldata->model_name) . "\n" . ucwords($capacitydata->capacity);


                // return response($modelDetails, 200);

                $update = ApiWebItemDetails::where('transaction_ref_no', $transaction_ref_no)->update($update);

                $data['grandfinal_price'] = $grandfinal_price + $lfrval + $minteval + $discountprice + $promodiscountprice;
                $data['final_condition'] = ucwords($final_condition);
                // $data['discountprice'] = $discountprice;
                // $data['promodiscountprice'] = $promodiscountprice;
                // $data['promotional_discount_id'] = $promotional_discount_id;
                $data['modelDetails'] = $modelDetails;
                $data['ConditionOptions'] = $FunctionalData;
                


                // $data['lfrval'] = $lfrval;

                // return response($data, 200); 
                //For successful fetch data
                $response["status"] = 1;
                $response["statuscode"] = 200;
                $response["messagetype"] = "";
                $response["message"] = "";
                $response["data"] = $data;
                return response($response, 200);
            } else {
                //Response for invalid authentication
                $response["status"] = 0;
                $response["statuscode"] = 401;
                $response["messagetype"] = "No data found for the specified request";
                $response["message"] = "";
                $response["data"] = [];
                return response($response, 401);
            }
        } else {
            //Response for invalid authentication
            $response["status"] = 0;
            $response["statuscode"] = 404;
            $response["messagetype"] = "Unauthorized request";
            $response["message"] = "You do not have permission to access this resource";
            $response["data"] = [];
            return response($response, 404);
        }
    }


    public function calculateRFC2104HMACForString($secretKey, $requestString) {
        if ($secretKey) {
            return base64_encode(hash_hmac('sha256', $requestString, $secretKey, true));
        }
    }
    
    public function detectDevice1(){
        $userAgent = $_SERVER["HTTP_USER_AGENT"];
        $devicesTypes = array(
            "computer" => array("msie 10", "msie 9", "msie 8", "windows.*firefox", "windows.*chrome", "x11.*chrome", "x11.*firefox", "macintosh.*chrome", "macintosh.*firefox", "opera"),
            "tablet"   => array("tablet", "android", "ipad", "tablet.*firefox"),
            "mobile"   => array("mobile ", "android.*mobile", "iphone", "ipod", "opera mobi", "opera mini"),
            "bot"      => array("googlebot", "mediapartners-google", "adsbot-google", "duckduckbot", "msnbot", "bingbot", "ask", "facebook", "yahoo", "addthis")
        );
         foreach($devicesTypes as $deviceType => $devices) {           
            foreach($devices as $device) {
                if(preg_match("/" . $device . "/i", $userAgent)) {
                    $deviceName = $deviceType;
                }
            }
        }
        return ucfirst($deviceName);
     }

    public function numberToWords($number)
    {
         $f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
         return ucfirst($f->format($number));
    } 
    function extractPincode($address) {
        // Regex to find a 6-digit Indian PIN
        if (preg_match('/\b\d{6}\b/', $address, $matches)) {
            return $matches[0]; // return the PIN
        }
        return null; // If no PIN found
    }
    public function generateExchange(Request $request)
    {


        $recData = $request->all();
        $jsonData = json_encode($recData, JSON_PRETTY_PRINT);
        // $fileData = json_encode($_FILES, JSON_PRETTY_PRINT);

        $filePath = public_path('example.txt'); // Path in public folder

        file_put_contents($filePath, "\n".date("Y-m-d H:i:s")."\nAPI Name:GenerateExchange\n----------------------------------\n", FILE_APPEND);
        
        file_put_contents($filePath, $jsonData, FILE_APPEND);
        file_put_contents($filePath, "\n\n=================FILES\n", FILE_APPEND);
        // file_put_contents($filePath, $fileData, FILE_APPEND);
        
        $year = date('Y');
        $month = date('M');
        $day = date('d');
       

        $destination = "./uploads/" . $year . "/" . $month . "/" . $day . "/";
        // if (!file_exists($destination)) {
        //     mkdir($destination, 0777, true);
        // }

        $validator = Validator::make($request->all(), [

            'TransactionRefNo'     => ['required', 'string', 'max:255'],
            'self_pickup'          => ['required', 'in:yes,no'],
            'customer_name'        => ['required', 'string', 'max:100'],
            'customer_mobile'      => ['required', 'digits:10'],
            'customer_email'       => ['required', 'email', 'max:255'],
            'customer_address'     => ['required', 'string', 'max:500'],

        ], [
            'TransactionRefNo.required'    => 'Transaction reference number is required.',
            'TransactionRefNo.max'         => 'Transaction reference number must not exceed 255 characters.',

            'self_pickup.required'         => 'Self pickup selection is required.',
            'self_pickup.in'               => 'Self pickup must be either "yes" or "no".',

            'customer_name.required'       => 'Customer name is required.',
            'customer_name.max'            => 'Customer name must not exceed 100 characters.',

            'customer_mobile.required'     => 'Customer mobile number is required.',
            'customer_mobile.digits'       => 'Customer mobile number must be exactly 10 digits.',

            'customer_email.required'      => 'Customer email is required.',
            'customer_email.email'         => 'Customer email must be a valid email address.',
            'customer_email.max'           => 'Customer email must not exceed 255 characters.',

            'customer_address.required'    => 'Customer address is required.',
            'customer_address.max'         => 'Customer address must not exceed 500 characters.',
        ]);

        if ($validator->fails()) {
            $errors = $validator->errors()->toArray();
            $firstError = collect($errors)->flatten()->first(); // Get the first error

            $response["status"] = 0;
            $response["statusCode"] = 400;
            $response["message"] = $firstError;
            $response["data"] = [];
            return response($response, 200);
        }

        $transaction_ref_no = $request->TransactionRefNo;

        
        $userdata = Auth::user();

        $token = $request->bearerToken();
        [$id, $plainTextToken] = explode('|', $token, 2);
        $validToken = DB::table('personal_access_tokens')->where('token', hash('sha256', $plainTextToken))->get();
        
        if ($validToken->isNotEmpty()) 
        {
            // dd($validToken);
            $validToken = $validToken->first();
            $createdAt = $validToken->created_at;
            $currentTime = now();

            $createdAt = Carbon::parse($createdAt);

            $expiryTime = $createdAt->addDays(365);

            if ($currentTime->greaterThan($expiryTime)) {
                // Token is invalid
                // return response()->json(['message' => 'Token is expired'], 401);
                $response["status"] = 0;
                $response["statuscode"] = 401;
                $response["messagetype"] = "Unauthorised Access";
                $response["message"] = "Token is expired.Please Login again";
                $response["data"] = [];
                return response($response, 401);
            } else {
                // Token is still valid
                $user_id = $validToken->tokenable_id;
                $user = User::where('id', $user_id)->first();
                
                if($user->user_type == 2)
                {
                    $role_id = $user->role_id;
                    $store_id = $user->store_id;
                    $Stores = Stores::where('id', $store_id)->where('status', 'active')->count();
                    if($role_id == 4)
                    {
                        $branch_id = $user->branch_id;
                        $StoresRep = StoresRepeat::where('parent_id', $store_id)->where('store_branch', $branch_id)->where('status', 'active')->count();
                        if($StoresRep > 0)
                        {
                            $brCount = 1;
                        }else{
                            $brCount = 0;
                        }


                    }else{
                        $brCount = 0;
                    }
                    if($Stores > 0 && $brCount > 0)
                    {
                        $strStatus = "active";
                    }else{
                        $strStatus = "inactive";
                    }
                }else{
                    $strStatus = "active";
                }
                // return response($user->status, 200);
                if($user->status == 'inactive' || $strStatus == 'inactive')
                {
                    $response["status"] = 0;
                    $response["statuscode"] = 401;
                    $response["messagetype"] = "Unauthorised Access";
                    $response["message"] = "Your account appears to be inactive. Access to this page is restricted.";
                    $response["data"] = [];
                    return response($response, 401);
                }

            }
           
        }else{
            $response["status"] = 0;
            $response["statuscode"] = 401;
            $response["messagetype"] = "Unauthorised Access";
            $response["message"] = "Your account appears to be inactive. Access to this page is restricted.";
            $response["data"] = [];
            return response($response, 401);
        }
        
        $response = ["status" => 0, "message" => "No data found for the specified request", "description" => "", "data" => []];
        if (!empty($userdata) > 0) {
            $branch_id = $userdata->branch_id;
            $store_id = $userdata->store_id;
            $storedata = Stores::where('status', 'active')->where('id', $store_id)->get();
            if (sizeof($storedata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 404;
                $response["messagetype"] = "Unauthorised request";
                $response["message"] = "You do not have permission to access this resource, as the LFR is not enabled for using this resource";
                $response["data"] = [];
                return response($response, 404);
            }

            $storebranchdata = StoresRepeat::where('status', 'active')->where('parent_id', $store_id)->where('store_branch', $branch_id)->get();
            if (sizeof($storebranchdata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 404;
                $response["messagetype"] = "Unauthorized request";
                $response["message"] = "You do not have permission to access this resource, as the branch is not enabled for using this resource";
                $response["data"] = [];
                return response($response, 404);
            }
           

            $refdata = ApiWebItemDetails::where('transaction_ref_no', $transaction_ref_no)->get();
            if (sizeof($refdata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "No data found for the specified request. Please check the TransactionRefNo";
                $response["data"] = [];
                return response($response, 200);
            }

            $old_model_id = $refdata[0]["model_id"];

            $modelData = ProductModels::query();
            $modelData = $modelData->select('brand_name', 'product_models.model_name')->leftJoin('product_brands as pb','pb.id','product_models.brand_id')->where('product_models.id',$old_model_id)->groupBy('product_models.id')->get();

          


            if ($store_id != $refdata[0]["store_id"]) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "TransactionRefNo does not belong to your account or request.";
                $response["data"] = [];
                return response($response, 200);
            }
            if ($branch_id != $refdata[0]["branch_id"]) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "TransactionRefNo does not belong to your branch or request.";
                $response["data"] = [];
                return response($response, 200);
            }
            if ($refdata[0]["status"] != 'created') {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "The requested TransactionRefNo has already been applied for an exchange.";
                $response["data"] = [];
                return response($response, 200);
            }

            $imei = $refdata[0]->imei;
            $valid_bill = $refdata[0]->valid_bill;
            
            $user_id = $userdata->id;
            $branch_id = $userdata->branch_id;
            //Duplicate IMEI validation
            $itmcount = ItemDetails::where('imei', $imei)->where("status", "active")
                ->where(DB::raw('DATE_FORMAT(created_at, "%Y-%m-%d")'), '>', DB::raw('DATE_SUB(curdate(), INTERVAL 5 DAY)'))->count();
            if ($itmcount > 0) {
                //Response for invalid iCloud mobile data
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "Oops! An exchange voucher has already been generated for this IMEI.";
                $response["data"] = [];
                return response($response, 200);
            }




            if (sizeof($refdata) > 0) {

                
                $partner_id = $refdata[0]->partner_id;
                

                

               

                if(empty($request->customer_name) || empty($request->customer_mobile) || empty($request->customer_address) || empty($request->customer_email))
                {
                    $response["status"] = 0;
                    $response["statuscode"] = 400;
                    $response["messagetype"] = "error";
                    $response["message"] = "Please fill customer information";
                    $response["data"] = [];
                    return response($response, 200);

                }
                $emailpattern = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/";

                if (!preg_match($emailpattern, $request->customer_email)) {
                    $response["status"] = 0;
                    $response["statuscode"] = 400;
                    $response["messagetype"] = "error";
                    $response["message"] = "Invalid email Address";
                    $response["data"] = [];
                    return response($response, 200);
                }

                $previousBrandName = $modelData[0]->brand_name;
                $previousBrandModel = $modelData[0]->model_name;

                
                $pincode = $this->extractPincode($request->customer_address);
                
                if(empty($pincode))
                {
                    $response["status"] = 0;
                    $response["statuscode"] = 400;
                    $response["messagetype"] = "error";
                    $response["message"] = "Pincode getting empty";
                    $response["data"] = [];
                    return response($response, 200);

                }


                $pincodedata = LogisticsServicePincodes::where('status', 'active')->where('pincode', $pincode)->count();
                if($pincodedata == 0)
                {
                    $response["status"] = 0;
                    $response["statuscode"] = 400;
                    $response["messagetype"] = "error";
                    $response["message"] = "Pickup service is currently not available in your area. We’ve received your request and will notify you once it becomes available.";
                    $response["data"] = [];
                    return response($response, 200);
                }
                
              

                //For generating exchange voucher number
                $store_location = $storebranchdata['0']->store_location;
                $store_city = $storebranchdata['0']->store_city;
                $store_branch = $storebranchdata['0']->store_branch;

                $locationDetails = Location::where('id', $store_location)->get();
                $stateCode = str_pad($locationDetails['0']->state_code, 2, '0', STR_PAD_LEFT);
                $storeCode = str_pad($store_id, 3, '0', STR_PAD_LEFT);
                $cityDetails = City::where('id', $store_city)->get();
                $cityCode = str_pad($cityDetails['0']->city_code, 3, '0', STR_PAD_LEFT);

                $branchsDetails = Branchs::where('id', $store_branch)->get();
                $branchCode = str_pad($branchsDetails['0']->branch_code, 3, '0', STR_PAD_LEFT);
                $dateCode = date("dmy");

                $today = date("Y-m-d");
                $itemscount1 = ApiWebItemDetails::where('store_id', $store_id)
                    // ->where('branch_id', $branch_id)
                    ->where(DB::raw('DATE_FORMAT(created_at, "%Y-%m-%d")'), date('Y-m-d', strtotime($today)))
                    ->count();
                $itemscount = str_pad($itemscount1 + 1, 3, '0', STR_PAD_LEFT);

                $credit_note = "REF" . $storeCode . time() . $itemscount;
                // return response($update, 200);
                
             
                
               
                $user_id = Auth::user()->id;

                

                
                // return response($credit_note, 200);

                $update['cust_name'] = $request->customer_name;
                $update['cust_mobile'] = $request->customer_mobile;
                $update['cust_email'] = $request->customer_email;
                $update['cust_address'] = $request->customer_address;
                if(!empty($request->latLong))
                {
                    $update['latLong'] = $request->latLong;
                }
                $update['kyc_verified'] = "yes";
                $update['credit_note'] = $credit_note;
                $update['self_pickup'] = $request->self_pickup;
                $update['status'] = "generated";
                $update1 = ApiWebItemDetails::where('transaction_ref_no', $transaction_ref_no)->update($update);


                $subject = "Online Exchange Request Received #  $credit_note";

                $emailtemplate = EmailTemplate::where('name', 'commontemplate')->first();

                $template_id = $emailtemplate->template_id;
                $frommail = $emailtemplate->from_mail;
                // $from_name = $emailtemplate->from_name;
                $from_name = "Online Xchange";
                $access_token = $emailtemplate->access_token;

                
                $tomail = "analytics@letsloop.in";
                $ccmail = "tech@letsloop.in";

                $curdate = date("F d, Y - h:i A");

                $mail_body1 = "<body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #ffffff;'>
                                <div style='max-width: 800px; margin: 0 auto; padding: 20px;'>
                                    <div style='background-color: #2196F3; color: white; padding: 20px; margin-bottom: 20px;'>
                                        <div style='font-size: 24px; font-weight: bold;'>Exchange Request Received</div>
                                    </div>       
                                    <div style='background-color: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin-bottom: 20px;'>
                                        <div style='font-weight: bold; color: #856404; margin-bottom: 5px;'>⚠ Pending Assignment</div>
                                        <div style='color: #856404; font-size: 14px;'>Please assign a pickup person for collection and receiving</div>
                                    </div>        
                                    <div style='background-color: #f8f9fa; padding: 20px; margin-bottom: 20px; border: 1px solid #dee2e6;'>
                                        <div style='font-size: 18px; font-weight: bold; color: #333; margin-bottom: 15px;'>Request Details</div>            
                                        <div style='margin-bottom: 15px;'>
                                            <div style='font-weight: bold; color: #555; font-size: 14px; margin-bottom: 5px;'>Exchange Reference #</div>
                                            <div style='color: #333; font-size: 14px;'>$credit_note</div>
                                        </div>            
                                        <div style='margin-bottom: 15px;'>
                                            <div style='font-weight: bold; color: #555; font-size: 14px; margin-bottom: 5px;'>Customer Name:</div>
                                            <div style='color: #333; font-size: 14px;'>".ucwords($request->customer_name)."</div>
                                        </div>            
                                        <div style='margin-bottom: 15px;'>
                                            <div style='font-weight: bold; color: #555; font-size: 14px; margin-bottom: 5px;'>Contact #</div>
                                            <div style='color: #333; font-size: 14px;'>".ucwords($request->customer_mobile)."</div>
                                        </div>            
                                        <div style='margin-bottom: 15px;'>
                                            <div style='font-weight: bold; color: #555; font-size: 14px; margin-bottom: 5px;'>Pickup Address:</div>
                                            <div style='color: #333; font-size: 14px;'>".ucwords($request->customer_address)."</div>
                                        </div>            
                                        <!--<div style='margin-bottom: 15px;'>
                                            <div style='font-weight: bold; color: #555; font-size: 14px; margin-bottom: 5px;'>Item for Exchange:</div>
                                            <div style='color: #333; font-size: 14px;'>Apple Iphone 6 - 12 GB / 64GB</div>
                                        </div>  -->          
                                        <div style='margin-bottom: 15px;'>
                                            <div style='font-weight: bold; color: #555; font-size: 14px; margin-bottom: 5px;'>Request Date:</div>
                                            <div style='color: #333; font-size: 14px;'>$curdate</div>
                                        </div>
                                    </div>        
                                </div>
                            </body>";

                            $sanitizedHtml = json_encode($mail_body1);
                $mail_body = substr($sanitizedHtml, 1, -1);

                $mail_body = str_replace('\n', '', $mail_body);
                $mail_body = str_replace('\t', '', $mail_body);            

                $edt = '{
                        "personalizations": [
                        {
                            
                            "to": [
                            {
                                "email": "' . $tomail . '"
                            }
                            ],
                            "bcc": [
                            {
                                "email": "' . $ccmail . '"
                            }
                            ],
                        
                            
                            "dynamic_template_data": {
                                "subject":"' . $subject . '",
                                "mail_body": "'.$mail_body.'"
                            
                            },
                            "subject": "' . $subject . '"
                        }
                        ],
                        "from": {
                        "email": "' . $frommail . '",
                        "name": "' . $from_name . '"
                        },
                    
                        "reply_to": {
                        "email": "' . $frommail . '",
                        "name": "' . $from_name . '"
                        },
                        "template_id": "' . $template_id . '"
                    }';

                    $edt1 = json_decode($edt);
                    // return response($edt, 200);
                    $curl = curl_init();

                    curl_setopt_array($curl, array(
                        CURLOPT_URL => "https://api.sendgrid.com/v3/mail/send",
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_ENCODING => "",
                        CURLOPT_MAXREDIRS => 10,
                        CURLOPT_TIMEOUT => 30000,
                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                        CURLOPT_CUSTOMREQUEST => "POST",
                        CURLOPT_POSTFIELDS => json_encode($edt1),
                        CURLOPT_HTTPHEADER => array(
                            // Set here requred headers
                            "accept: */*",
                            "accept-language: en-US,en;q=0.8",
                            "content-type: application/json",
                            "Authorization: $access_token",
                        ),
                    ));

                    $rs1 = curl_exec($curl);
                    $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
                    $err = curl_error($curl);
                    //dd($response); 
                    curl_close($curl);
                    $resp = json_decode($rs1);


                // return response($data, 200); 
                //For successful fetch data
                $response["status"] = 1;
                $response["statuscode"] = 200;
                $response["messagetype"] = "sucessfully";
                $response["message"] = "Exchange Voucher generated successfully";
                $response["data"] = $credit_note;
                return response($response, 200);
            } else {
                //Response for invalid authentication
                $response["status"] = 0;
                $response["statuscode"] = 401;
                $response["messagetype"] = "No data found for the specified request";
                $response["message"] = "";
                $response["data"] = [];
                return response($response, 401);
            }
        } else {
            //Response for invalid authentication
            $response["status"] = 0;
            $response["statuscode"] = 404;
            $response["messagetype"] = "Unauthorized request";
            $response["message"] = "You do not have permission to access this resource1";
            $response["data"] = [];
            return response($response, 404);
        }


       
        
    }

    public function getTransactionDetails(Request $request)
    {

        
        $validator = Validator::make($request->all(), [

            'TransactionRefNo'     => ['required', 'string', 'max:255'],
        ], [
            'TransactionRefNo.required'    => 'Transaction reference number is required.',
            'TransactionRefNo.max'         => 'Transaction reference number must not exceed 255 characters.',
        ]);

        if ($validator->fails()) {
            $errors = $validator->errors()->toArray();
            $firstError = collect($errors)->flatten()->first(); // Get the first error

            $response["status"] = 0;
            $response["statusCode"] = 400;
            $response["message"] = $firstError;
            $response["data"] = [];
            return response($response, 200);
        }

        $transaction_ref_no = $request->TransactionRefNo;

        
        $userdata = Auth::user();

        $token = $request->bearerToken();
        [$id, $plainTextToken] = explode('|', $token, 2);
        $validToken = DB::table('personal_access_tokens')->where('token', hash('sha256', $plainTextToken))->get();
        
        if ($validToken->isNotEmpty()) 
        {
            // dd($validToken);
            $validToken = $validToken->first();
            $createdAt = $validToken->created_at;
            $currentTime = now();

            $createdAt = Carbon::parse($createdAt);

            $expiryTime = $createdAt->addDays(365);

            if ($currentTime->greaterThan($expiryTime)) {
                // Token is invalid
                // return response()->json(['message' => 'Token is expired'], 401);
                $response["status"] = 0;
                $response["statuscode"] = 401;
                $response["messagetype"] = "Unauthorised Access";
                $response["message"] = "Token is expired.Please Login again";
                $response["data"] = [];
                return response($response, 401);
            } else {
                // Token is still valid
                $user_id = $validToken->tokenable_id;
                $user = User::where('id', $user_id)->first();
                
                if($user->user_type == 2)
                {
                    $role_id = $user->role_id;
                    $store_id = $user->store_id;
                    $Stores = Stores::where('id', $store_id)->where('status', 'active')->count();
                    if($role_id == 4)
                    {
                        $branch_id = $user->branch_id;
                        $StoresRep = StoresRepeat::where('parent_id', $store_id)->where('store_branch', $branch_id)->where('status', 'active')->count();
                        if($StoresRep > 0)
                        {
                            $brCount = 1;
                        }else{
                            $brCount = 0;
                        }


                    }else{
                        $brCount = 0;
                    }
                    if($Stores > 0 && $brCount > 0)
                    {
                        $strStatus = "active";
                    }else{
                        $strStatus = "inactive";
                    }
                }else{
                    $strStatus = "active";
                }
                // return response($user->status, 200);
                if($user->status == 'inactive' || $strStatus == 'inactive')
                {
                    $response["status"] = 0;
                    $response["statuscode"] = 401;
                    $response["messagetype"] = "Unauthorised Access";
                    $response["message"] = "Your account appears to be inactive. Access to this page is restricted.";
                    $response["data"] = [];
                    return response($response, 401);
                }

            }
           
        }else{
            $response["status"] = 0;
            $response["statuscode"] = 401;
            $response["messagetype"] = "Unauthorised Access";
            $response["message"] = "Your account appears to be inactive. Access to this page is restricted.";
            $response["data"] = [];
            return response($response, 401);
        }
        
        $response = ["status" => 0, "message" => "No data found for the specified request", "description" => "", "data" => []];
        if (!empty($userdata) > 0) {
            $branch_id = $userdata->branch_id;
            $store_id = $userdata->store_id;
           
           

            // $refdata = ApiWebItemDetails::where('transaction_ref_no', $transaction_ref_no)->get();
            $table = \App\Models\ApiWebItemDetails::class;
            $clmname = "transaction_ref_no";
            $model = new $table;
            $tableName = $model->getTable();

            $columns = collect(DB::select("SHOW COLUMNS FROM `$tableName`"))
                ->reject(fn($col) => $col->Type === 'longblob')
                ->pluck('Field')
                ->toArray();
            $refdata = $table::where($clmname, $transaction_ref_no)->select($columns)->get();

            if (sizeof($refdata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "No data found for the specified request. Please check the TransactionRefNo";
                $response["data"] = [];
                return response($response, 200);
            }


            $category_id = $refdata[0]->category_id;
            $brand_id = $refdata[0]->brand_id;
            $model_id = $refdata[0]->model_id;
            $capacity_id = $refdata[0]->capacity_id;
            $color_id = $refdata[0]->color_id;
            $imei = $refdata[0]->imei;
            $exe_functional_option =  $refdata[0]->exe_functional_option;
            $exe_physical_option =  $refdata[0]->exe_physical_option;
            $exe_accessory =  $refdata[0]->exe_accessory;
            $exe_price =  $refdata[0]->exe_price;
            $status =  $refdata[0]->status;
            $final_status =  $refdata[0]->final_status;

            $category_name = "";
            $brand_name = "";
            $model_name = "";
            $capacity = "";
            $color = "";
            // $imei = "";
            $exe_functional_options = "";
            // $exe_physical_option = "";
            $exe_accessorys = "";
            // $exe_price = "";
            

            if(isset($category_id))
            {
                $CatDetails = Categories::where('id', $category_id)->first();
                $category_name = $CatDetails->category_name;
            }

            if(isset($brand_id))
            {
                $barndDetails = ProductBrands::where('id', $brand_id)->first();
                $brand_name = $barndDetails->brand_name;
            }

            if(isset($model_id))
            {
                $modelDetails = ProductModels::where('id', $model_id)->first();
                $model_name = $modelDetails->model_name;
            }

            if(isset($capacity_id))
            {
                $CapDetails = ProductCapacity::where('id', $capacity_id)->first();
                $capacity = $CapDetails->capacity;

                $ColDetails = ProductColor::where('id', $color_id)->first();
                $color = $ColDetails->color;
            }

            if(isset($exe_accessory))
            {
                $accids = explode(",", $exe_accessory);
                // $accDetails = AccessoryType::whereIn('id', $accids)->select()->first();

                $accDetails = DB::table('accessory')
                ->select(DB::raw("GROUP_CONCAT(accessory_name SEPARATOR ', ') as all_names"))
                ->whereIn('id', $accids)
                ->first();

                $exe_accessorys = collect(explode(',', $accDetails->all_names))
                ->map(fn($name) => ucwords(trim($name)))
                ->implode(', ');
                // $exe_accessorys = $accDetails->all_names;
            }

            $codcatdata = "";
            if(isset($exe_functional_option))
            {
                $funids = explode(",", $exe_functional_option);
                $con_options = ['no','fail','not working','false'];

                $codcatdata = ConditionOptions::whereIn('condition_options.id', $funids)->leftJoin('condition_categories as cc', 'cc.id', '=', 'condition_options.condition_categories_id')
                ->select('condition_categories_id as key','category_name as title',DB::raw("
                    CASE 
                        WHEN condition_options.con_option IN ('no','fail','not working','false') 
                        THEN 0 ELSE 1 
                    END as value
                "))->orderBy('priority', 'DESC')->get()->map(function ($item) {

                        $item->title = ucwords($item->title);
                        return $item;
                    });
                
               
            }

            $data["category_name"] = $category_name;
            $data["brand_name"] = $brand_name;
            $data["model_name"] = $model_name;
            $data["color"] = $color;
            $data["capacity"] = $capacity;
            $data["imei"] = isset($imei) ? $imei : "";
            $data["exe_physical_option"] = isset($exe_physical_option) ? ucwords($exe_physical_option) : "";
            $data["ConditionOptions"] = $codcatdata;
            $data["accessories"] = isset($exe_accessory) ? $exe_accessorys : "";
            $data["grandfinal_price"] = isset($exe_price) ? ucwords($exe_price) : "";
            $data["status"] = ($status == 'generated') ? "Exchange Transaction completed" : "Exchange Transaction pending";
            // $data["final_status"] = ucwords($final_status);
           


            return response($data, 200);
           
           
        }

       
        
    }
    private function makeApiCall($url, $headers, $data, $certPath, $keyPath, $keyPassword)
    {

       
                $ch = curl_init();
                // Set cURL options
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_SSLCERT, $certPath);
                curl_setopt($ch, CURLOPT_SSLKEY, $keyPath);
                curl_setopt($ch, CURLOPT_KEYPASSWD, $keyPassword);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
                // Execute cURL request
                $resp1 = curl_exec($ch);
                $error = curl_error($ch);
                $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

                $resp = json_decode($resp1, true);
                if (curl_errno($ch)) {
                    return $httpcode.'::@::'.curl_error($ch);
                }else{
                    return $httpcode.'::@::'.$resp1;
                }
    }

    private function handleSaleReporting($responseBody, $data, $headers, $storeId, $branchId, $serialNo, $mpn, $itemLogId, $defaultUrl, $certPath, $keyPath, $keyPassword)
    {
        $url = $defaultUrl . "report";
        $reportData = [
            'apiVersion' => 2,
            'transactionId' => $responseBody['transactionId'],
            'paymentInfo' => [
                'previousBrandName' => $data['previousBrandName'],
                'previousBrandModel' => $data['previousBrandModel'],
                'tradeInDeviceValue' => $data['tradeInDeviceValue'],
            ],
        ];

        if (is_numeric($serialNo)) {
            $reportData['imei'] = $serialNo;
        } else {
            $reportData['serialno'] = $serialNo;
        }

        $attempts = 0;
        $maxAttempts = 5;
        $delay = 3;

        while ($attempts < $maxAttempts) {
            $response = $this->makeApiCall($url, $headers, $reportData, $certPath, $keyPath, $keyPassword);

            if ($response->successful()) {
                $responseBody = $response->json();
                if ($responseBody['status'] === 'Success' && $responseBody['saleReported'] === true) {
                    return true;
                } elseif ($responseBody['status'] === 'Success' && !$responseBody['saleReported']) {
                    $attempts++;
                    sleep($delay);
                } else {
                    return response()->json($responseBody);
                }
            } else {
                return response()->json(['status' => 'Failure', 'errorMessage' => 'Error during sale reporting.']);
            }
        }

        return false;
    }

    public function getServicePincodes(Request $request)
    {

        $token = $request->bearerToken();
        
        if (empty($request->bearerToken())) {
            $response["status"] = 0;
            $response["statuscode"] = 404;
            $response["message"] = "Token cannot be empty";
            $response["data"] = [];
            return response($response, 200);
           
        }

        // $pincodedata = LogisticsServicePincodes::where('status','active')->pluck('pincode');

        $pincodedata = LogisticsServicePincodes::where('status', 'active')
                    ->distinct()
                    ->pluck('pincode')
                    ->toArray();


        $response["status"] = 1;
        $response["statuscode"] = 200;
        $response["messagetype"] = "";
        $response["message"] = "available Pincodes";
        $response["data"] = $pincodedata;
        return response($response, 200);




    }

    public function cancelXchange(Request $request)
    {

        $token = $request->bearerToken();
        // return response($token, 200);
        if (empty($request->bearerToken())) {
            $response["status"] = 0;
            $response["statuscode"] = 404;
            $response["message"] = "Token cannot be empty";
            $response["data"] = [];
            return response($response, 200);
           
        }

        $validator = Validator::make($request->all(), [
            'CustomerRefNo' => ['required', 'string', 'alpha_num', 'min:10', 'max:50'],
            'remarks' => ['required', 'string', 'max:255'],
            
           
        ], [
            'CustomerRefNo.required' => 'Transaction reference number is required.',
            'CustomerRefNo.alpha_num' => 'Only letters and numbers are allowed.',
            'CustomerRefNo.min' => 'Transaction reference number is too short.',
            'CustomerRefNo.max' => 'Transaction reference number is too long.',

            'remarks.required'          => 'Remarks are required.',
            'remarks.string'            => 'Remarks must be a valid string.',
            'remarks.max'               => 'Remarks must not exceed 255 characters.',

        ]);

        if ($validator->fails()) {
            $errors = $validator->errors()->toArray();
            $firstError = collect($errors)->flatten()->first(); // Get the first error

            $response["status"] = 0;
            $response["statusCode"] = 400;
            $response["message"] = $firstError;
            $response["data"] = [];
            return response($response, 200);
        }
        
      
        $credit_note = $request->CustomerRefNo;
        // return response($request->all(), 200);
        
        
        $userdata = Auth::user();

        $token = $request->bearerToken();
        [$id, $plainTextToken] = explode('|', $token, 2);
        $validToken = DB::table('personal_access_tokens')->where('token', hash('sha256', $plainTextToken))->get();
        
        if ($validToken->isNotEmpty()) 
        {
            // dd($validToken);
            $validToken = $validToken->first();
            $createdAt = $validToken->created_at;
            $currentTime = now();

            $createdAt = Carbon::parse($createdAt);

            $expiryTime = $createdAt->addDays(365);

            if ($currentTime->greaterThan($expiryTime)) {
                // Token is invalid
                // return response()->json(['message' => 'Token is expired'], 401);
                $response["status"] = 0;
                $response["statuscode"] = 401;
                $response["messagetype"] = "Unauthorised Access";
                $response["message"] = "Token is expired.Please Login again";
                $response["data"] = [];
                return response($response, 401);
            } else {
                // Token is still valid
                $user_id = $validToken->tokenable_id;
                $user = User::where('id', $user_id)->first();
                
                if($user->user_type == 2)
                {
                    $role_id = $user->role_id;
                    $store_id = $user->store_id;
                    $Stores = Stores::where('id', $store_id)->where('status', 'active')->count();
                    if($role_id == 4)
                    {
                        $branch_id = $user->branch_id;
                        $StoresRep = StoresRepeat::where('parent_id', $store_id)->where('store_branch', $branch_id)->where('status', 'active')->count();
                        if($StoresRep > 0)
                        {
                            $brCount = 1;
                        }else{
                            $brCount = 0;
                        }


                    }else{
                        $brCount = 0;
                    }
                    if($Stores > 0 && $brCount > 0)
                    {
                        $strStatus = "active";
                    }else{
                        $strStatus = "inactive";
                    }
                }else{
                    $strStatus = "active";
                }
                // return response($user->status, 200);
                if($user->status == 'inactive' || $strStatus == 'inactive')
                {
                    $response["status"] = 0;
                    $response["statuscode"] = 401;
                    $response["messagetype"] = "Unauthorised Access";
                    $response["message"] = "Your account appears to be inactive. Access to this page is restricted.";
                    $response["data"] = [];
                    return response($response, 401);
                }

            }
           
        }else{
            $response["status"] = 0;
            $response["statuscode"] = 401;
            $response["messagetype"] = "Unauthorised Access";
            $response["message"] = "Your account appears to be inactive. Access to this page is restricted.";
            $response["data"] = [];
            return response($response, 401);
        }
        
        $response = ["status" => 0, "message" => "No data found for the specified request", "description" => "", "data" => []];
        if (!empty($userdata) > 0) {
            $branch_id = $userdata->branch_id;
            $store_id = $userdata->store_id;
            
           

            $refdata = ApiWebItemDetails::select([
                    'id', 'transaction_ref_no', 'latLong', 'credit_note', 'imei', 'partner_id',
                    'category_id', 'brand_id', 'model_id', 'color_id', 'capacity_id', 'store_id', 'branch_id',
                    'is_fake', 'is_icloud_lock', 'coupon_avalibility', 'coupon_validated', 'coupon_code',
                    'coupon_validat', 'coupon_validby', 'coupon_value', 'base_price', 'accessory_price',
                    'accessory_data', 'valid_bill', 'bill_date', 'purchase_date',
                    'exe_functional_option', 'exe_physical_option', 'exe_physical_condition_id',
                    'fun_cond_name', 'exe_final_condition', 'exe_price', 'exe_accessory', 'is_neg_app',
                    'org_neg_val', 'applied_neg_val', 'buying_values', 'smartupgrade_models',
                    'minte_buy_val', 'lfr_buy_val', 'exc_price', 'good_price', 'fair_price', 'broken_price',
                    'str_percentage', 'discount_price', 'special_discount', 'cust_name', 'cust_mobile',
                    'cust_mobie_verified', 'cust_email', 'cust_address', 'kyc_verified', 'offers_data',
                    'offer_selected', 'offer_amount', 'schemes_data', 'schemes_response', 'sch_sale_data',
                    'sch_sale_response', 'status', 'created_at', 'updated_at', 'pickup_otp', 'pickup_latLong',
                    'conf_model_id', 'conf_capacity_id', 'conf_color_id', 'conf_functional_option',
                    'conf_physical_condition', 'conf_physical_condition_id', 'conf_fun_cond_name',
                    'conf_final_condition', 'conf_exe_price', 'conf_exe_accessory', 'final_status',
                    'cancel_remarks', 'confirmed_by', 'confirmed_at', 'closed_at','conf_accessory_data'
                ])
                ->where('credit_note', $credit_note)
                ->get();
            if (sizeof($refdata) < 1) {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "No data found for the specified request. Please check the TransactionRefNo";
                $response["data"] = [];
                return response($response, 200);
            }

           
            if ($refdata[0]["status"] == 'created') {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "The requested TransactionRefNo has not applied for an exchange.";
                $response["data"] = [];
                return response($response, 200);
            }

            if ($refdata[0]["final_status"] == 'completed') {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "The requested TransactionRefNo has been already applied for an exchange.";
                $response["data"] = [];
                return response($response, 200);
            }

            if ($refdata[0]["final_status"] == 'cancelled') {
                $response["status"] = 0;
                $response["statuscode"] = 400;
                $response["messagetype"] = "Bad Request";
                $response["message"] = "The requested TransactionRefNo has been Cancelled.";
                $response["data"] = [];
                return response($response, 200);
            }

            $transaction_ref_no = $refdata[0]["transaction_ref_no"];


            




            if (sizeof($refdata) > 0) {

                
                $update['cancel_remarks'] = $request->remarks;
                $update['final_status'] = "cancelled";
                $update['closed_at'] = date("Y-m-d H:i:s");
                $update1 = ApiWebItemDetails::where('transaction_ref_no', $transaction_ref_no)->update($update);   
            
                $response["status"] = 1;
                $response["statuscode"] = 200;
                $response["messagetype"] = "success";
                $response["message"] = "Exchange Voucher cancelled successfully";
                $response["data"] = [];
                return response($response, 200);
                
                
                
               
                
               

            } else {
                //Response for invalid authentication
                $response["status"] = 0;
                $response["statuscode"] = 401;
                $response["messagetype"] = "No data found for the specified request";
                $response["message"] = "";
                $response["data"] = [];
                return response($response, 401);
            }
        } else {
            //Response for invalid authentication
            $response["status"] = 0;
            $response["statuscode"] = 404;
            $response["messagetype"] = "Unauthorized request";
            $response["message"] = "You do not have permission to access this resource1";
            $response["data"] = [];
            return response($response, 404);
        }


       
        
    }






}
