<?php

namespace App\Http\Controllers\Api\V1\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\CartItem;
use App\Models\Notification;
use App\Models\WhatsappSettings;
use App\Models\Product;
use App\Models\Orders;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Mail\WelcomeMail;
use App\Mail\KYCVerificationMail;
use Illuminate\Support\Facades\Mail;
use App\Jobs\SendWelcomeEmail;
use Illuminate\Support\Facades\Auth;
use App\Jobs\SendKYCVerificationEmail;
use App\Jobs\SendBecameASellerRequestEmail;
use Illuminate\Support\Facades\File;
use GuzzleHttp\Client;
use Twilio\Rest\Client as TClient;
use App\Models\TwilioSMSSettings;

class AuthApiController extends Controller
{   
    public function login(Request $request){
        $validator = Validator::make($request->all(), [
            'country_id' => ['required'],
            'phone' => ['required'],
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors(),
            ], 422);
        }

        $country_id = $request->country_id;
        $country_details = getCountrydetailsById($country_id);
        $phone_code = $country_details->phone_code;

        // $otp = random_int(1000, 9999);
        
        $full_number = $phone_code.$request->phone;
        
        $twilio_sms_config = TwilioSMSSettings::first();

        $client_ip = $request->ip(); // get current request IP
        
        if($client_ip != '122.179.156.23' && $twilio_sms_config->status == 'active'){
        	// ✅ Twilio Verify API Call
    	    $curl = curl_init();

    	    curl_setopt_array($curl, array(
        		CURLOPT_URL => 'https://verify.twilio.com/v2/Services/VA729cd3a77c747f44f9b815d55f3e8edd/Verifications',
        		CURLOPT_RETURNTRANSFER => true,
        		CURLOPT_ENCODING => '',
        		CURLOPT_MAXREDIRS => 10,
        		CURLOPT_TIMEOUT => 0,
        		CURLOPT_FOLLOWLOCATION => true,
        		CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        		CURLOPT_CUSTOMREQUEST => 'POST',
        		CURLOPT_POSTFIELDS => http_build_query([
        		    'To' => '+' . $full_number,
        		    'Channel' => 'sms',
        		]),
        		CURLOPT_HTTPHEADER => array(
        		    'Content-Type: application/x-www-form-urlencoded',
        		    'Authorization: Basic ' . base64_encode("{$twilio_sms_config->twilio_sid}:{$twilio_sms_config->twilio_token}"), 
        		)
    	    ));

    	    $response = curl_exec($curl);
    	    curl_close($curl);

    	    $result = json_decode($response, true);
    	    
    	    // Check API response
    	    if(isset($result['status']) && $result['status'] == 'pending'){
        		// User insert/update logic
        		$already_user = User::where('country_id', $country_id)->where('phone', $request->phone)->first();
        		if(!$already_user){
        		    $user = new User;
        		    $user->country_id = $country_id;
        		    $user->phone = $request->phone;
        		    $user->email = $phone_code.$request->phone.'@demo.com';
        		    $user->password = bcrypt('password');
        		    $user->save();
        		}

        		return response()->json([
        		    'success' => true,
        		    'message' => "OTP sent successfully",
        		    // 'service_sid' => $result['service_sid']
        		]);
    	    } else {
        		return response()->json($result, 400);
    	    }
    	} else {
    		$otp = 1234;
    		$existingOtp = DB::table('user_otp')->where(['fullNumber' => $full_number])->first();
    		if($existingOtp) {
    		    DB::table('user_otp')->where(['fullNumber' => $full_number])->update([
    		        'otp' => $otp,
    		        'expires_at' => Carbon::now()->addMinutes(5),
    		    ]);
    		} else {
    		    DB::table('user_otp')->insert([
    		        'phone_code' => $phone_code,
    		        'fullNumber' => $full_number,
    		        'otp' => $otp,
    		        'expires_at' => Carbon::now()->addMinutes(5),
    		        'phone_number' => $request->phone,
    		    ]);
    		}

    		$already_user = User::where('country_id', $country_id)->where('phone', $request->phone)->first();
    		if(!$already_user){
    		    $user = new User;
    		    $user->country_id = $country_id;
    		    $user->phone = $request->phone;
    		    $user->email = $phone_code.$request->phone.'@demo.com';
    		    $user->password = bcrypt('password');
    		    $user->save();
    		}

    		return response()->json([
    		    'success' => true,
    		    'message' => "OTP send sucessfully",
                'service_sid' => null
    		]);
    	}

        // $whatsappSetting = WhatsappSettings::find(1);
        // $contentVariables = [
        //     "1" => "$otp",
        // ];

        // $client = new Client();
        // $headers = [
        //     'Content-Type' => 'application/x-www-form-urlencoded',
        //     'Authorization' => 'Basic QUNmMzljZmQzZTQ5ZjM2ZjEyODAwNDRjNWJmY2YwYTQxNDphZWE1Njg5NGQ1NmI1NTBlMGEwZjY5ZmVmODRhNTNkMA=='
        // ];

        // $options = [
        //     'headers' => $headers,
        //     'form_params' => [
        //     'To' => 'whatsapp:+'.$phone_code.$request->phone,
        //     'From' => 'whatsapp:'.$whatsappSetting->twilio_whatsapp,
        //     'ContentSid' => $whatsappSetting->twilio_msid,
        //     'ContentVariables' => json_encode($contentVariables)
        // ]];

        // $response = $client->post(
        //     'https://api.twilio.com/2010-04-01/Accounts/ACf39cfd3e49f36f1280044c5bfcf0a414/Messages.json',
        //     $options
        // );

        // return response()->json([
            // 'success' => true,
            // 'message' => "OTP send sucessfully"
        // ]);
    }

    public function verify_otp(Request $request){
        $validator = Validator::make($request->all(), [
            'country_id' => ['required'],
            'phone' => ['required'],
            'otp' => ['required'],
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors(),
            ], 422);
        }

        $country_id = $request->country_id;
        $country_details = getCountrydetailsById($country_id);
        $phone_code = $country_details->phone_code;
        $full_number = $phone_code.$request->phone;

	    $twilio_sms_config = TwilioSMSSettings::first();
        
        $client_ip = $request->ip(); // get current request IP

        if($client_ip != '122.179.156.23' && $twilio_sms_config->status == 'active'){
            // ✅ Twilio Verify API Call for verification
    	    $curl = curl_init();

    	    curl_setopt_array($curl, array(
        		CURLOPT_URL => "https://verify.twilio.com/v2/Services/VA729cd3a77c747f44f9b815d55f3e8edd/VerificationCheck",
        		CURLOPT_RETURNTRANSFER => true,
        		CURLOPT_ENCODING => '',
        		CURLOPT_MAXREDIRS => 10,
        		CURLOPT_TIMEOUT => 0,
        		CURLOPT_FOLLOWLOCATION => true,
        		CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        		CURLOPT_CUSTOMREQUEST => 'POST',
        		CURLOPT_POSTFIELDS => http_build_query([
        		    'To' => '+' . $full_number,
        		    'Code' => $request->otp,
        		]),
        		CURLOPT_HTTPHEADER => array(
        		    'Content-Type: application/x-www-form-urlencoded',
        		    'Authorization: Basic ' . base64_encode("{$twilio_sms_config->twilio_sid}:{$twilio_sms_config->twilio_token}"),
        		),
    	    ));

    	    $response = curl_exec($curl);
    	    curl_close($curl);

    	    $result = json_decode($response, true);

    	    // ✅ Check response
    	    if (isset($result['status']) && $result['status'] == 'approved') {
        		// OTP verified successfully
        		$user = User::where('country_id', $country_id)->where('phone', $request->phone)->first();
        		if (!$user) {
            		return response()->json([
        			'success' => false,
        			'message' => "Account not found!"
        		    ], 422);
        		}
        		
        		$credentials = ["email" => $user->email, "password" => "password"];
                if (!auth()->attempt($credentials)) {
                    return response()->json([
                        'message' => 'The given data was invalid.',
                        'errors' => [
                            'password' => [
                                'Invalid credentials'
                            ],
                        ]
                    ], 422);
                }

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

        		return response()->json([
        		    'success' => true,
        		    'message' => "OTP verified successfully",
        		    'user' => $user,
        		    'access_token' => $token,
        		]);
    	    } else {
                return response()->json($result, 400);
            }
    	} else {
    		$already_user = User::where('country_id', $country_id)->where('phone', $request->phone)->first();
            if($already_user){
                $full_number = $phone_code.$request->phone;
                $account_data = DB::table('user_otp')->where(['fullNumber' => $full_number, 'otp' => $request->otp])->first();
                if (isset($account_data) && !empty($account_data)) {
                    if (Carbon::now('UTC')->greaterThan($account_data->expires_at)) {
                        return response()->json(['message' => 'OTP has expired.'], 401);
                    }

                    $credentials = ["email" => $already_user->email, "password" => "password"];
                    if (!auth()->attempt($credentials)) {
                        return response()->json([
                            'message' => 'The given data was invalid.',
                            'errors' => [
                                'password' => [
                                    'Invalid credentials'
                                ],
                            ]
                        ], 422);
                    }

                    // $authToken = $already_user->createToken('auth-token')->plainTextToken;
                    $authToken = $already_user->createToken('unlimited-access-token')->plainTextToken;

                    return response()->json([
                        'access_token' => $authToken,
                        'user' => $already_user
                    ]);
                } else {
                    return response()->json([
                        'success' => false,
                        'message' => "otp incorrect!",
                    ], 401);
                }
            } else {
                return response()->json([
                    'success' => false,
                    'message' => "Account not found!",
                ], 422);
            }
    	}
    }

    public function register(Request $request){
        $validator = Validator::make($request->all(), [
            'first_name' => ['required', 'string'],
            'last_name' => ['required', 'string'],
            'country_id' => ['required'],
            'phone' => ['required'],
            'email' => 'required|email',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors(),
            ], 422);
        }

        $country_id = $request->country_id;
        $already_user = User::where(['country_id' => $country_id, 'phone' => $request->phone])->first();

        if ($already_user) {
            $user = User::find($already_user->id);
            $user->first_name = $request->first_name;
            $user->last_name = $request->last_name;
            $user->country_id = $country_id;
            $user->phone = $request->phone;
            $user->email = $request->email;
            $user->kyc_status = 0; // Pending
            $user->password = bcrypt('password');
            $user->save();

            $user->roles()->sync(3);

            dispatch(new SendWelcomeEmail($user));
            // Mail::to($user->email)->send(new WelcomeMail($user));

            $message = "Thank you for registering. We're excited to have you on board!";
            pushNotification($user->id, $message);

            Notification::create([
                'user_id' => $user->id,
                'title' => "Welcome to Torathy Auction",
                'message' => $message,
            ]);

            $credentials = ["email" => $request->email, "password" => "password"];
            if (!auth()->attempt($credentials)) {
                return response()->json([
                    'message' => 'The given data was invalid.',
                    'errors' => [
                        'password' => [
                            'Invalid credentials'
                        ],
                    ]
                ], 422);
            }

            $environment_data = getEnvironmentData();
            $id_verification_section = $environment_data['ID_VERIFICATION_SECTION'];

            // $message = "Welcome to Torathy Auction! Explore exciting auctions, bid on unique items, and enjoy a seamless experience. Need help? Contact our support team.";
            // $notification_response = pushNotification($user->id, $message);

            // $authToken = $already_user->createToken('auth-token')->plainTextToken;
            $authToken = $already_user->createToken('unlimited-access-token')->plainTextToken;
            return response()->json([
                'access_token' => $authToken,
                'user' => $user,
                'id_verification_status' => $id_verification_section,
            ]);
        } else {
            return response()->json([
                'success' => true,
                'message' => "Account not found!",
            ]);
        }
    }

    public function getCountryCode(Request $request){
        $currencyMapping = [
            '973' => 'BHD',
            '965' => 'KWD',
            '968' => 'OMR',
            '974' => 'QR',
            '966' => 'SAR',
            '971' => 'AED',
            '91' => 'INR',
        ];

        $phoneDegits = [
            '973' => ['min' => 8, 'max' => 8], // Bahrain
            '965' => ['min' => 8, 'max' => 8], // Kuwait
            '968' => ['min' => 8, 'max' => 8], // Oman
            '974' => ['min' => 8, 'max' => 8], // Qatar
            '966' => ['min' => 9, 'max' => 9], // Saudi Arabia
            '971' => ['min' => 9, 'max' => 9], // UAE
            '91' => ['min' => 10, 'max' => 10], // UAE
        ];
        $countryMapping = [
            '973' => 'Bahrain',
            '965' => 'Kuwait',
            '968' => 'Oman',
            '974' => 'Qatar',
            '966' => 'Saudi Arabia',
            '971' => 'United Arab Emirates',
            '91' => 'India',
        ];

        $convertedArray = array_map(function ($key, $value) use ($currencyMapping, $countryMapping, $phoneDegits) {
            return [
                'code' => $key,
                'description' => '(+' . $key . ') ' . $value,
                'country' => $countryMapping[$key] ?? null, // Fetch country from $countryMapping
                'currency' => $currencyMapping[$key] ?? null, // Dynamically fetch currency
                'digits' => $phoneDegits[$key] ?? null, // Dynamically fetch phone digits
            ];
        }, array_keys($countryMapping), $countryMapping);

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

    public function logout(Request $request){
        $request->user()->tokens()->delete();

        return response()->json([
            'success' => true,
            'message' => "Logout sucessfully!",
        ], 200);
    }

    public function getUserDetails(){
        $user = auth()->user();

        $country_details = getCountrydetailsById($user->country_id);

        $cartCount = CartItem::where('user_id', $user->id)->sum('quantity');

        $walletAmount = User::where('id', $user->id)->sum('pending_balance');
        $user->wallet = $walletAmount;

        $environment_data = getEnvironmentData();
        $id_verification_section = $environment_data['ID_VERIFICATION_SECTION'];

        $payment_options = $environment_data['PAYMENT_OPTIONS'];
        $cashPaymentEnabled = data_get($payment_options, 'value', 0);

        return response()->json([
            'success'    => true,
            'user'       => $user,
            'cart_count' => $cartCount,
            'is_seller_flag' => $country_details->is_seller_flag,
            'id_verification_status' => $id_verification_section,
            'payment_options' => $cashPaymentEnabled
        ], 200);
    }

    public function userProfileUpdate(Request $request){
        $user = User::find(auth()->id());

        $document_picture = $request->input('document_picture');
        if ($document_picture) {
            if ($user->document_picture) {
                $oldImagePath = public_path($user->document_picture);
                if (file_exists($oldImagePath)) {
                    unlink($oldImagePath);
                }
            }

            // $imageName = time().'.'.$request->file('document_picture')->getClientOriginalExtension();
            // $request->file('document_picture')->move(public_path('uploads/documents'), $imageName);

            $imageName = time() . '.png';

            $imageData = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $document_picture));

            $directory = public_path('uploads/documents');

            file_put_contents($directory . '/' . $imageName, $imageData);

            $user->document_picture = 'uploads/documents/' . $imageName;
            $user->kyc_status = 1; // Under Review

            // SendKYCVerificationEmail::dispatch($user);
            dispatch(new SendKYCVerificationEmail($user));

            $message = "Your KYC documents are currently under review. We’ll notify you once it's completed.";
            pushNotification($user->id, $message);

            Notification::create([
                'user_id' => 1,
                'title' => "KYC Verification Request",
                'message' => $message,
            ]);
        }

        $environment_data = getEnvironmentData();
        $id_verification_section = $environment_data['ID_VERIFICATION_SECTION'];

        $fields = ['first_name', 'last_name', 'email', 'country_id', 'phone', 'address', 'document_type', 'new_address'];

        foreach ($fields as $field) {
            if ($request->has($field)) {
                $user->$field = $request->$field;
            }
        }

        // 👉 If ID verification disabled, mark KYC as completed
        if ($id_verification_section === 'disable') {
            $user->kyc_status = 1;
        }

        $user->save();

        return response()->json([
            'success' => true,
            'message' => "Profile Updated Successfully!",
            'user'    => $user
        ], 200);
    }

    public function sentBecameASellerRequest(Request $request){
        $user = User::find(auth()->id());
       
        $seller_profile_image = $request->input('seller_profile_image');
        if ($seller_profile_image) {
            if ($user->seller_profile_image) {
                $old_seller_profile_image_path = public_path($user->seller_profile_image);
                if (file_exists($old_seller_profile_image_path)) {
                    unlink($old_seller_profile_image_path);
                }
            }

            $seller_profile_image_name = time() . '.png';

            $imageData = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $seller_profile_image));

            $directory = public_path('uploads/seller_profile_image');

            file_put_contents($directory . '/' . $seller_profile_image_name, $imageData);

            // $seller_profile_image_name = time().'.'.$request->file('seller_profile_image')->getClientOriginalExtension();
            // $request->file('seller_profile_image')->move(public_path('uploads/seller_profile_image'), $seller_profile_image_name);
            $user->seller_profile_image = 'uploads/seller_profile_image/' . $seller_profile_image_name;
        }

        $seller_cover_image = $request->input('seller_cover_image');
        if ($seller_cover_image) {
            if ($user->seller_cover_image) {
                $old_seller_cover_image_path = public_path($user->seller_cover_image);
                if (file_exists($old_seller_cover_image_path)) {
                    unlink($old_seller_cover_image_path);
                }
            }

            // $seller_cover_image_name = time().'.'.$request->file('seller_cover_image')->getClientOriginalExtension();
            // $request->file('seller_cover_image')->move(public_path('uploads/seller_cover_image'), $seller_cover_image_name);

            $seller_cover_image_name = time() . '.png';

            $seller_cover_image_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $seller_cover_image));

            $seller_cover_image_directory = public_path('uploads/seller_cover_image');

            file_put_contents($seller_cover_image_directory . '/' . $seller_cover_image_name, $seller_cover_image_data);

            $user->seller_cover_image = 'uploads/seller_cover_image/' . $seller_cover_image_name;
        }

        if ($request->has('seller_bank_name')) {
            $user->seller_bank_name = $request->seller_bank_name;
        }

        if ($request->has('seller_iban')) {
            $user->seller_iban = $request->seller_iban;
        }

        if ($request->has('seller_description')) {
            $user->seller_description = $request->seller_description;
        }

        if($request->seller_request == 'add'){
            $user->seller_status = 1; // Requested    
        
            dispatch(new SendBecameASellerRequestEmail($user));

            $message = "Your request to become a seller has been received. Our team will review it shortly.";
            pushNotification($user->id, $message);

            Notification::create([
                'user_id' => 1,
                'title' => "Became A Seller Request",
                'message' => $message,
            ]);
        } else {
            if ($request->seller_status == 3) {
                $user->seller_status = 1; // Requested

                dispatch(new SendBecameASellerRequestEmail($user));

                $message = "Your request to become a seller has been received. Our team will review it shortly.";
                pushNotification($user->id, $message);

                Notification::create([
                    'user_id' => 1,
                    'title' => "Became A Seller Request",
                    'message' => $message,
                ]);
            }
        }
        
        $user->save();
        
        return response()->json([
            'success' => true,
            'message' => "Became A Seller Request Sent to Admin Successfully.",
            'user'    => $user
        ], 200);
    }

    public function deleteProfileImageCover(Request $request){
        $user = User::find(auth()->id());

        if ($request->type == 'seller_profile_image') {
            $old_seller_profile_image_path = public_path($user->seller_profile_image);
            if (file_exists($old_seller_profile_image_path)) {
                unlink($old_seller_profile_image_path);
            }

            $user->seller_profile_image = null;
        }

        if ($request->type == 'seller_cover_image') {
            $old_seller_cover_image_path = public_path($user->seller_cover_image);
            if (file_exists($old_seller_cover_image_path)) {
                unlink($old_seller_cover_image_path);
            }

            $user->seller_cover_image = null;
        }
    
        $user->save();

        return response()->json([
            'success' => true
        ], 200);
    }
}
