<?php

namespace App\Http\Controllers\APIS\AdminApi;

use App\Http\Controllers\Controller;
use App\Http\Requests\CreateCustomerRequest;
use App\Models\Customer;
use Illuminate\Support\Str;
use App\Services\AdminService;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;



class CustomerController extends Controller

{
    protected $adminService;

    public function __construct(AdminService $adminService)
    {
        $this->adminService = $adminService;
    }


    public function createOrUpdateCustomer(Request $request)
    {
        try {

            $customerEmailExist = Customer::where('email', $request->email)->first();
            if ($customerEmailExist) {
                // return response()->json(['status' => 'error','message' => 'Email already exists'],200);
                return jsonResponseWithErrorMessage('Email already exists', 400);
            }

            $customerNameExist = Customer::where('title', $request->title)->first();
            if ($customerNameExist) {
                // return response()->json(['status' => 'error','message' => 'Name already exists'],200);
                return jsonResponseWithErrorMessage('Name already exists', 400);
            }

            $userData = [
                'title'       => $request->title,
                'email'       => $request->email,
                'country'     => $request->country,
                'state'       => $request->state,
                'city'       => $request->city,
                'zip'       => $request->zip,
                'name'        => $request->title,
                'phone'       => $request->phone,
                'address'       => $request->address,
                'address2'       => $request->address2,
                'description' => $request->description,
                'version' => $request->version,
                'additionalInfo' => $request->additionalInfo,

            ];

            if (!empty($request->id) && is_array($request->id) && isset($request->id['id'])) {
                $userData['id'] = [
                    'id' => $request->id['id'],
                    'entityType' => 'CUSTOMER',
                ];
            }

            if (!empty($request->tenantId) && is_array($request->tenantId) && isset($request->tenantId['id'])) {
                $userData['tenantId'] = [
                    'id' => $request->tenantId['id'],
                    'entityType' => 'TENANT',
                ];
            }

            // Call API to create/update customer
            $response = $this->adminService->createOrUpdateCustomer($userData);

            if (is_array($response)) {
                $apiData = $response; // If it's an array, use it directly
            } elseif (method_exists($response, 'json')) {
                $apiData = $response->json();
            } else {
                Log::error("Unexpected API response format.", ['response' => $response]);
                return jsonResponseWithErrorMessage('Unexpected API response format', 500);
            }



            // $tenantId = $apiResponse['tenantId']['id'] ?? null;
            $externalId = $apiData['externalId'] ?? null;
            $tenantId = is_array($apiData['tenantId']) ? ($apiData['tenantId']['id'] ?? null) : $apiData['tenantId'];

            //  Store customer in database
            $customer = Customer::updateOrCreate(
                ['id' => $apiData['id']['id'] ?? Str::uuid()->toString()],
                [
                    'entity_type'      => $apiData['id']['entityType'] ?? 'CUSTOMER',
                    'created_time'     => $apiData['createdTime'] ?? now()->timestamp,
                    'country'          => $apiData['country'] ?? null,
                    'state'            => $apiData['state'] ?? null,
                    'city'             => $apiData['city'] ?? null,
                    'address'          => $apiData['address'] ?? null,
                    'address2'         => $apiData['address2'] ?? null,
                    'zip'              => $apiData['zip'] ?? null,
                    'phone'            => $apiData['phone'] ?? null,
                    'email'            => $apiData['email'] ?? null,
                    'title'            => $apiData['title'] ?? null,
                    'external_id'     => $externalId,
                    'version'          => $apiData['version'] ?? 1,
                    'name'             => $apiData['name'] ?? null,
                    'tenant_id'       => $tenantId,
                    'additional_info'  => json_encode($apiData['additionalInfo'] ?? [])
                ]
            );

            return jsonResponseWithSuccessMessage(
                $request->customerId ? 'Customer updated successfully' : 'Customer created successfully',
                [
                    'customer' => $customer,
                    'api_response' => $apiData
                ]
            );
        } catch (Exception $e) {
            Log::error("An error occurred: " . $e->getMessage());

            $errorResponse = json_decode($e->getMessage(), true);
            if (json_last_error() === JSON_ERROR_NONE) {
                return jsonResponseWithErrorMessage($errorResponse['message'] ?? 'Something went wrong', 400, $errorResponse);
            }

            return jsonResponseWithErrorMessage($e->getMessage(), 500);
        }
    }

    public function listCustomers(Request $request)
    {
        try {
            $customers = Customer::orderBy('created_at', 'desc')->get();

            return jsonResponseWithSuccessMessage('Customers fetched successfully', [
                'customers' => $customers
            ]);
        } catch (Exception $e) {
            Log::error("An error occurred: " . $e->getMessage());
            return jsonResponseWithErrorMessage($e->getMessage(), 500);
        }
    }


    public function deleteCustomers(Request $request)
    {

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

                'customer_id' => 'required|string',
            ]);
            if ($validator->fails()) {
                return jsonResponseWithErrorMessage($validator->errors()->first(), 400);
            }
            $customerId = $request->input('customer_id');
            $response = $this->adminService->deleteCustomer(['customerId' => $customerId]);


            // Delete customer from local database if API deletion was successful
            $customer = Customer::where('id', $customerId)->first();
            if ($customer) {
                $customer->delete();
            }

            return jsonResponseWithSuccessMessage('Customer deleted successfully', ['api_response' => $response]);
        } catch (Exception $e) {
            Log::error("An error occurred: " . $e->getMessage());
            $errorResponse = json_decode($e->getMessage(), true);
            if (json_last_error() === JSON_ERROR_NONE) {
                return jsonResponseWithErrorMessage($errorResponse['message'] ?? 'Something went wrong', 400, $errorResponse);
            }

            return jsonResponseWithErrorMessage($e->getMessage(), 500);
        }
    }
}
