<?php

namespace App\Http\Controllers;

use App\Models\Address;
use App\Models\Location;
use App\Repositories\Member\Cart\MemberCartRepository;
use App\Repositories\Member\ShippingRepository;
use App\Repositories\Member\Transaction\TransactionRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CheckoutController extends Controller
{
    public function index(Request $request, MemberCartRepository $memberCartRepository)
    {
        $request->merge(['location_id' => $request->input('location_id', session('location_id', 22))]);

        $store = Location::find($request->input('location_id'));

        $subtotal = $memberCartRepository->getSubtotal($request->input('location_id'));

        $address_list = Address::where('user_id', $request->user()->id)->orderBy('is_primary','desc')->get();


        $total = $subtotal;


  
        $carts = $memberCartRepository->getList($request);


        return view('checkout.v1-delivery-1', [
            'carts' => $carts,
            'subtotal' => $subtotal,
            'total' => $total,
            'store' => $store,
            'address_list'   => $address_list,
        ]);
    }

    public function indexProcess(Request $request)
    {
        $delivery_method = $request->input('delivery_method') ?? 'shipping';
        $address_id = $request->input('address_id');

    
        if ($address_id == null) {
            $address_list = Address::where('user_id', $request->user()->id)->orderBy('is_primary','desc')->get();
            $address_id = $address_list->first()->id;
        }

        if ($delivery_method == null || $address_id == null) {
    
            return redirect()->back()->with('error', 'Delivery method or address is required');
        }

        if ($delivery_method == 'shipping') {
            session(['checkout_delivery_method' => $delivery_method]);
            session(['checkout_address_id' => $address_id]);
            return redirect()->route('checkout.shipping');
        }

        if ($delivery_method == 'pickup') {
            session(['checkout_delivery_method' => $delivery_method]);
            session(['checkout_address_id' => null]);
            return redirect()->route('checkout.payment');
        }

        return redirect()->back()->with('error', 'Delivery method is not valid');
    }


    public function chooseShipping(Request $request, MemberCartRepository $memberCartRepository, ShippingRepository $shippingRepository)
    {
        try {
            $delivery_method = session('checkout_delivery_method');
            $address_id = session('checkout_address_id');

            $location_id = session('location_id', 22);


            if ($delivery_method == null || $address_id == null || $location_id == null) {

                return redirect()->route('checkout.delivery');
            }

            $subtotal = $memberCartRepository->getSubtotal($location_id);
            $total = $subtotal;


            $request->merge(['location_id' => $location_id]);
            $carts = $memberCartRepository->getList($request);

            $shipping_list = collect($shippingRepository->getList([
                "location_id" => $location_id,
                "address_id" => $address_id,
                "items" => $carts,
            ])['pricing'])->map(function($row){
                return [
                    'courier'  => $row['courier_code'],
                    'service'  => $row['courier_service_code'],
                    'title' => $row['courier_name']." - ".$row['courier_service_name'],
                    'description' => $row['duration'],
                    'cost'     => $row['shipping_fee'],
                ];
            });
            
            return view('checkout.v1-delivery-1-shipping', [
                'carts' => $request->user()->carts,
                'subtotal' => $subtotal,
                'total' => $total,
                'delivery_method' => $delivery_method,
                'address_id' => $address_id,
                'address' => Address::find($address_id),
                'shipping_list' => $shipping_list,
            ]);
        } catch (\Exception $e) {
            Log::info($e);
            return redirect()->route('checkout.delivery')->with('error', 'Invalid checkout data');
        }
    }

    public function chooseShippingProcess(Request $request)
    {
        $shipping_option = $request->input('shipping_option');

        // Parse shipping option (format: courier|service|cost)
        $shipping_data = explode('|', $shipping_option);
        $courier = $shipping_data[0] ?? '';
        $service = $shipping_data[1] ?? '';
        $cost = $shipping_data[2] ?? 0;

        session(['checkout_courier' => $courier]);
        session(['checkout_service' => $service]);
        // session(['checkout_shipping_cost' => $cost]);

        return redirect()->route('checkout.payment');
    }

    public function choosePayment(Request $request, TransactionRepository $repository, MemberCartRepository $memberCartRepository)
    {
        try {

            $address_id = session('checkout_address_id');

            $courier = session('checkout_courier');
            $service = session('checkout_service');

            $location_id = session('location_id', 22);

            $items = [];

            $request->merge(['location_id' => $location_id]);
            $carts = $memberCartRepository->getList($request);

            if (count($carts) == 0) {
                return redirect()->route('checkout.delivery')->with('error', 'No items in cart');
            }
            
            foreach ($carts as $cart) {
                $items[] = [
                    "item_reference_id" => $cart->item_reference_id,
                    "qty" => $cart->qty
                ];
            }

            $data = [
                "address_id" => $address_id,
                "note" => "",
                "courier_company" => $courier,
                "courier_type" => $service,
                "location_id" => $location_id,
                "items" => $items,
                "vouchers" => [],
                "use_customer_points" => 0,
            ];
            
            $item = $repository->create($data);

            $notification = new \App\Notifications\Member\Transaction\OrderWaitPayment($item);
            $user = auth()->user();
            $user->notify($notification->delay(now()->addMinutes(1)));

            // return new CheckoutResource($item);

            // proses payment


               $payment = $item->payments()->where("method_type",'App\Models\XenditLink')
                    ->where("status",'PENDING')
                    ->first();
        $invoice_url = $payment ? @$payment->method->invoice_url: "";

        return redirect()->to($invoice_url)->withHeaders([
            'Cache-Control' => 'no-cache, no-store, must-revalidate',
            'Pragma' => 'no-cache',
            'Expires' => '0'
        ]);



        } catch (\Exception $e) {

            Log::info($e);

            return redirect()->route('checkout.delivery')->with('error', 'Invalid checkout data');
        }
    }
}
