<?php

namespace App\Http\Controllers\API;

use App\Models\LineModel;
use App\Models\ShopModel;
use App\Models\UserModel;
use Illuminate\Http\Request;
use App\Models\BasicSettingModel;
use App\Models\NotificationModel;
use App\Http\Controllers\Controller;
use App\Models\PrescriptionOrderModel;

class ShopController extends Controller
{
    // public function api_show()
    // {

    //     $shops = ShopModel::where('status', 1)->get();

    //     if ($shops->isEmpty()) {
    //         return response()->json(['message' => 'No shops found'], 422);
    //     }

    //      // Transform the data to remove unnecessary fields
    // $transformedData = $shops->map(function ($shop) {

    //     $botIds = BasicSettingModel::where('created_by', $shop->id)->first();

    //     if ($botIds) {
    //         return [
    //             'id' => $shop->id,
    //             'status' => $shop->status,
    //             'active_status' => $shop->active_status,
    //             'shopname' => $shop->shopname,
    //             'adress' => $shop->adress,
    //             'zipcode' => $shop->zipcode,
    //             'dues' => $shop->dues,
    //             'shopimage' => $shop->shopimage,
    //             'shopnumber' => $shop->shopnumber,
    //             'plan_type' => $shop->plan_type,
    //             'lat' => $shop->lat,
    //             'lng' => $shop->lng,
    //         ];
    //     }

    //     // Return an empty array when the condition is not met
    //     return null;
    // })->filter()->values();; // This will remove empty arrays from the result

    //     return response()->json(['data' => $transformedData], 200);
    // }


    public function get_shop_sorted(Request $request)
    {
        // $data = $request->validate([

        //     'u_lat' =>  'required',
        //     'u_long' =>  'required',
        // ]);        

            $data = $request->validate([
                'u_lat' => 'nullable',
                'u_long' => 'nullable',
            ]);
            
            if (is_null($data['u_lat']) || is_null($data['u_long'])) {
                // Both u_lat and u_long are null.
                $shops = ShopModel::where('status', 1)
                                 ->where('active_status', 1)
                                 ->get();
            } else {
                // u_lat and u_long are not null.
                $shops = ShopModel::selectRaw('*, SQRT(POW(lat - ?, 2) + POW(lng - ?, 2)) AS distance', [$data['u_lat'], $data['u_long']])
                    ->where('status', 1)
                    ->where('active_status', 1)
                    ->orderBy('distance')
                    ->get();
            }

   
        if ($shops->isEmpty()) {
            return response()->json(['message' => __("noShopsFound")], 422);
        }

        // Transform the data to remove unnecessary fields
        $transformedData = $shops->map(function ($shop) {
            return [
                'id' => $shop->id,
                'status' => $shop->status,
                'active_status' => $shop->active_status,
                'shopname' => $shop->shopname,
                'adress' => $shop->adress,
                'zipcode' => $shop->zipcode,
                'dues' => $shop->dues,
                'shopimage' => $shop->shopimage,
                'shopnumber' => $shop->shopnumber,
                'business_hours' => $shop->business_hours,
                'holiday' => $shop->holiday,
                'permission_number' => $shop->permission_number,
                'plan_type' => $shop->plan_type,
                'lat' => $shop->lat,
                'lng' => $shop->lng,
            ];
        });

        return response()->json(['data' => $transformedData], 200);
    }

    public function api_show()
    {

        //active_status
        $shops = ShopModel::where('status', 1)->where('active_status', 1)->get();

        if ($shops->isEmpty()) {
            // return response()->json(['message' => 'No shops found'], 422);
            return response()->json(['message' => __("noShopsFound")], 422);
        }

        // Transform the data to remove unnecessary fields
        $transformedData = $shops->map(function ($shop) {
            return [
                'id' => $shop->id,
                'status' => $shop->status,
                'active_status' => $shop->active_status,
                'shopname' => $shop->shopname,
                'adress' => $shop->adress,
                'zipcode' => $shop->zipcode,
                'dues' => $shop->dues,
                'shopimage' => $shop->shopimage,
                'shopnumber' => $shop->shopnumber,
                'business_hours' => $shop->business_hours,
                'holiday' => $shop->holiday,
                'permission_number' => $shop->permission_number,
                'plan_type' => $shop->plan_type,
                'lat' => $shop->lat,
                'lng' => $shop->lng,
            ];
        });

        return response()->json(['data' => $transformedData], 200);
    }


    public function shop_info($shop_id)
    {
        // active_status = 1 mean shop admin is visible
        //status = 1 mean Normal shop admin.
        // $shop = ShopModel::where('id', $shop_id)->where('status', 1)->where('active_status', 1)->first();
        $shop = ShopModel::where('id', $shop_id)->where('status', 1)->first();

        if (!$shop) {
            return response()->json(['message' => __("noShopsFound")], 422);
        }

        // Transform the data to remove unnecessary fields
        $transformedData = [
            'id' => $shop->id,
            'status' => $shop->status,
            'active_status' => $shop->active_status,
            'shopname' => $shop->shopname,
            'address' => $shop->adress,
            'zipcode' => $shop->zipcode,
            'dues' => $shop->dues,
            'shopimage' => $shop->shopimage,
            'shopnumber' => $shop->shopnumber,
            'business_hours' => $shop->business_hours,
            'holiday' => $shop->holiday,
            'permission_number' => $shop->permission_number,
            'plan_type' => $shop->plan_type,
            'lat' => $shop->lat,
            'lng' => $shop->lng,
        ];

        return response()->json($transformedData, 200);
    }


    // public function line_list_api_show($user_id)
    // {
    //     // Retrieve prescription orders where uid matches $user_id
    //     $prescriptionOrders = PrescriptionOrderModel::where('uid', $user_id)->get();

    //     if ($prescriptionOrders->isEmpty()) {
    //         return response()->json(['message' => 'No shops found for this user'], 401);
    //     }

    //     $uniqueCreatedByCount = $prescriptionOrders->pluck('created_by')->unique()->values()->all();

    //     return response()->json($uniqueCreatedByCount, 200);
    // }



    // public function line_list_api_show($user_id)
    // {
    //     // Retrieve prescription orders where uid matches $user_id
    //     $prescriptionOrders = PrescriptionOrderModel::where('uid', $user_id)->get();

    //     if ($prescriptionOrders->isEmpty()) {
    //         return response()->json(['message' => 'No shops found for this user'], 401);
    //     }

    //     $uniqueCreatedByCount = $prescriptionOrders->pluck('created_by')->unique()->values()->all();

    //     $shopsData = [];

    //     foreach ($uniqueCreatedByCount as $createdBy) {
    //         $shop = ShopModel::find($createdBy);

    //         if ($shop) {
    //             $shopsData[] = $shop;
    //         }
    //     }

    //     // $UsersList = PrescriptionOrderModel::where('uid', $user_id)
    //     //     ->with('admin')
    //     //     ->get();

    //     // // $adminsData = $UsersList->pluck('admin')->filter()->unique();


    //     // return response()->json("data"=>$shopsData, 200);
    //     return response()->json(['data' => $shopsData], 200);
    // }


    public function line_list_api_show($user_id)
    {
        $lineList = LineModel::where('u_id', $user_id)->with('admin')->get();

        $transformedData = [];

        foreach ($lineList as $line) {

            if ($line->admin->active_status == 1) {
                $transformedData[] = [
                    "id" => $line->admin->id,
                    "uid" => $line->u_id,
                    "active_status" => $line->admin->active_status,
                    "shopname" => $line->admin->shopname,
                    "shopadress" => $line->admin->adress,
                    "shopimage" => $line->admin->shopimage,
                    "plan_type" => $line->admin->plan_type,
                    "line_id" => $line->line_id,
                    "bot_id" => $line->bot_id
                ];
            }
        }

        return response()->json(['data' => $transformedData], 200);
    }

    public function add_tmp_shop(Request $request)
    {
        if ($request->filled('uid') && $request->filled('shop_id')) {
            $user = UserModel::where('id', $request->input('uid'))->first();

            if ($user) {
                $user->temp_shop = $request->input('shop_id');
                $user->save();

                return response()->json(['message' => 'Updated successfully'], 200);
            } else {
                return response()->json(['message' => 'User not found'], 404);
            }
        } else {
            return response()->json(['message' => 'Missing data'], 400);
        }
    }
}
