<?php

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

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ContactUs;
use App\Models\CmsPage;
use App\Models\User;
use App\Models\Product;
use App\Models\Advertisement;
use App\Models\Country;
use App\Models\Notification;
use App\Models\ProductReceipt;
use App\Models\CartItem;
use App\Models\ShippingDetails;
use App\Jobs\SendContactUsEmail;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Auth;
use App\Models\Payment;
use App\Models\Orders;
use Illuminate\Support\Facades\URL;


class CommaonApiController extends Controller
{
    public function contactUs(Request $request)
    {
        $contactUS = new ContactUs;
        $contactUS->full_name = $request->full_name;
        $contactUS->email = $request->email;
        $contactUS->phone_number = $request->phone_number;
        $contactUS->description = $request->description;
        $contactUS->save();

        dispatch(new SendContactUsEmail($contactUS));

        return response()->json([
            'success' => true,
            'message' => "Your inquiry sent successfully.",
        ], 200);
    }

    public function cmsPages(Request $request){
        if($request->language == "ar"){
            $cmsData = CmsPage::select('title_arabic as title', 'content_arabic as content', 'updated_at')->where('slug', $request->type)->first();
        } else {
            $cmsData = CmsPage::select('title', 'content', 'updated_at')->where('slug', $request->type)->first();
        }
        
        return response()->json([
            'data' => $cmsData,
        ], 200);
    }

    public function getAdvertisementList(Request $request){
        $advertisement_data = Advertisement::where('status', 1)->orderBy('id', 'desc')->get();

        return response()->json([
            'success' => true,
            'message' => 'Advertisement list retrieved successfully',
            'data' => $advertisement_data
        ]);
    }

    public function getGeneralSettings(Request $request){
        if ($request->has('key')) {
            $value = getGeneralSettingData($request->key);
            return response()->json([
                'success' => true,
                'value' => $value,
            ]);
        }

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

    public function paymentProcess(Request $request){
        $user = User::where('id', $request->user_id)->first();

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

        $product_data = Product::where('id', $request->product_id)->first();

        $client = new Client();

        // Prepare the payment data
        $paymentData = [
            'amount' => $product_data->highest_bid_amount != '' ? $product_data->price + $shipping_details->shipping_fee : $product_data->highest_bid_amount + $shipping_details->shipping_fee,
            'currency' => 'BHD', 
            'threeDSecure' => true,
            // 'currency' => $country_details->currency,// Change to your currency as needed
            'description' => 'Payment for Order',
            'customer' => [
                'first_name' => $user->first_name,
                'last_name' => $user->last_name,
                'email' => $user->email,
                'phone' => [
                    'country_code' => $phone_code,
                    'number' => $user->phone
                ]
            ],
            "source" => [
                // "id" => $bookingData->authorize_id
            ],
            'auto' => [
                'type' =>'VOID',
                'time' => 5
            ],
        ];

        // Send the request to Tap's API
        // $api_tap_company = env('API_TAP_COMPANY');
        $environment_data = getEnvironmentData();
        $response = $client->post('https://api.tap.company/v2/authorize', [
            'headers' => [
                'Authorization' => $environment_data['API_TAP_COMPANY'],
                'Content-Type' => 'application/json',
            ],
            'json' => $paymentData,
        ]);

        $responseBody = json_decode($response->getBody(), true);

        // Check if the response contains a payment URL
        if (isset($responseBody['id'])) {
            $client2 = new Client();
            $tapChargeId = $responseBody['id'];
            $responseData = $client2->get("https://api.tap.company/v2/authorize/{$tapChargeId}", [
                'headers' => [
                    'Authorization' => 'Bearer sk_test_XKokBfNWv6FIYuTMg5sLPjhJ',
                    'Content-Type' => 'application/json',
                ],
            ]);

            $responseRealBody = json_decode($responseData->getBody(), true);
        }

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

    public function getCountryList(Request $request){
        $country_data = Country::select('id', 'country_name', 'top_level_domain', 'phone_code', 'phone_number_length_min', 'phone_number_length_max', 'continent', 'currency', 'is_seller_flag')->get();

        return response()->json([
            'success' => true,
            'message' => 'Country list retrieved successfully',
            'data' => $country_data
        ]);
    }

    public function getNotificationList(Request $request){
        $query = Notification::select('*')
		->where('user_id', Auth::id())
		->whereNull('deleted_at'); // exclude soft deleted records

	    if ($request->is_read == 0) {
		$query->where('is_read', 0);
	    }

	    $notification_data = $query->orderBy('id', 'DESC')->paginate(10);

	    $notification_count = Notification::where('user_id', Auth::id())
		->where('is_read', 0)
		->whereNull('deleted_at') // exclude soft deleted here too
		->count();

	    return response()->json([
		'success' => true,
		'message' => 'Notification list retrieved successfully',
		'data' => $notification_data,
		'notification_count' => $notification_count
	    ]);
    }

    public function notificationRead(Request $request){
        Notification::where('id', $request->id)->update(['is_read' => $request->is_read]);

        return response()->json([
            'success' => true,
            'message' => 'Notification read successfully'
        ]);
    }

    public function getBuyerDetails(Request $request){
        $buyer_details = Orders::with(['user', 'productReceipt'])->where('product_sku', $request->product_sku)->get();

        return response()->json([
            'status' => true,
            'message' => 'My purchase list fetched successfully.',
            'data' => $buyer_details
        ]);        
    }

    public function purchaseSellProduct(Request $request){
        $user = $request->user();

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

        // $shipping_ids_array = explode(',', $request->shipping_ids);

        // $shipping_fee_total = ShippingDetails::whereIn('id', $shipping_ids_array)->sum('shipping_fee');

        $environment_data = getEnvironmentData();
        $payment_options = $environment_data['PAYMENT_OPTIONS'];
        $codEnabled = data_get($payment_options, 'value', 0);
        $PAYMENT_DEADLINE_FOR_AUCTION_WINNER_DAYS = $environment_data['PAYMENT_DEADLINE_FOR_AUCTION_WINNER_DAYS'];

        if($codEnabled == 1){
            // Proceed with Cash Payment

            $cart_data = CartItem::select('cart_items.product_sku', 'cart_items.quantity', 'products.product_quantity as stock_qty')
                ->join('products', 'products.sku', '=', 'cart_items.product_sku')
                ->where('cart_items.user_id', $user->id)
                ->get();

            // Example check — filter only products where cart qty > stock qty (out of stock / insufficient)
            $invalid_products = $cart_data->filter(function ($item) {
                return $item->quantity > $item->stock_qty;
            });

            // Check condition
            if ($invalid_products->isEmpty()) {
                // Stock is fine
                $data['status'] = true;
                $data['url'] = URL::temporarySignedRoute(
                        'admin.payment.select_payment_option_for_sell_product', // named route
                        now()->addDays($PAYMENT_DEADLINE_FOR_AUCTION_WINNER_DAYS)->endOfDay(), // 15th day 11:59 PM
                        [
                            'user_id' => $user->id,
                            'shipping_id' => $request->shipping_id,
                            'total_amount' => $request->total_amount
                        ]
                    );
            } else {
                // Some products have insufficient stock
                $data['status'] = false;
                $data['url'] = null;
            }
        } else {
            // Proceed with online payment

            $client = new Client();
            // Prepare the payment data
            $paymentData = [
                'amount' => $request->total_amount,
                'currency' => 'BHD', 
                //'currency' => $user->user_currancy,// Change to your currency as needed
                'description' => 'Payment for Order',
                'customer' => [
                    'first_name' => $user->first_name.' '.$user->last_name,
                    'email' => $user->email,
                ],
                'metadata' => [ // Using metadata to store additional information
                    'user_id' => $user->id,
                    'phone' => $user->phone,
                    'phone_code' => $phone_code,
                    'shipping_id' => $request->shipping_id
                ],
                'source' => [
                    'id' => 'src_all', // Use 'src_all' to allow all payment methods
                ],
                'redirect' => [
                    'url' => route('payment.payment_callback_api'), // Callback URL
                ],
            ];

            try {
                // Send the request to Tap's API
                $environment_data = getEnvironmentData();
                $response = $client->post('https://api.tap.company/v2/charges', [
                    'headers' => [
                        'Authorization' => $environment_data['API_TAP_COMPANY'],
                        'Content-Type' => 'application/json',
                    ],
                    'json' => $paymentData,
                ]);

                $responseBody = json_decode($response->getBody(), true);
                // echo '<pre>'; print_r($responseBody); die();

                $cart_data = CartItem::select('cart_items.product_sku', 'cart_items.quantity', 'products.product_quantity as stock_qty')
                    ->join('products', 'products.sku', '=', 'cart_items.product_sku')
                    ->where('cart_items.user_id', $user->id)
                    ->get();

                // Example check — filter only products where cart qty > stock qty (out of stock / insufficient)
                $invalid_products = $cart_data->filter(function ($item) {
                    return $item->quantity > $item->stock_qty;
                });

                // Check condition
                if ($invalid_products->isEmpty()) {
                    // Stock is fine
                    if (isset($responseBody['transaction']['url'])) {
                        $data['status'] = true;
                        $data['url'] = $responseBody['transaction']['url'];
                    } else {
                        $data['status'] = false;
                        $data['url'] = null;
                    }
                } else {
                    // Some products have insufficient stock
                    $data['status'] = false;
                    $data['url'] = null;
                }
            } catch (\Exception $e) {
                $data['status'] = false;
            }
        }
        
        return response()->json([
            'data' => $data,
        ]);
    }

    public function getCurrentAppVersion(){
        $environment_data = getEnvironmentData();
        $current_app_version = $environment_data['CURRENT_APP_VERSION'];

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