<?php

namespace App\Http\Controllers;

use App\Models\Cart;
use App\Models\RestaurantPOS_BillingInfoHD;
use App\Models\RestaurantPOS_OrderedProductBillHD;
use App\Models\OtherSetting;
use App\Models\Address;
use App\Models\Modifier;
use App\Models\CartModifier;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;

class CheckoutController extends Controller
{
    public function index()
    {
        return view('checkout.index');
    }

    public function store(Request $request)
    {
        $random_string = Str::random(4);

        $userId = Auth::check() ? Auth::user()->id : null;
        $sessionId = Session::getId();
        $name = $request->name;
        $address = $request->address;
        $email = $request->email;
        $postal_code = $request->postal_code;
        $city = $request->city;
        $contact_number = $request->contact_number;

        try {
            DB::beginTransaction();

            $cart_data = Cart::where(function ($query) use ($userId, $sessionId) {
                if ($userId) {
                    $query->where('user_id', $userId);
                } else {
                    // User is not logged in, use session ID
                    $query->where('session_id', $sessionId);
                }
            })
                ->with('dish.category')
                ->get();

            $sub_total = 0;

            foreach ($cart_data as $cart) {
                $sub_total += $cart->price * $cart->quantity;
            }

            $last_id = RestaurantPOS_BillingInfoHD::latest('id')->first();
            if (!$last_id || $last_id == null) {
                $id = 1;
            } else {
                $id = $last_id->Id + 1;
            }

            $data = [
                'Id' => $id,
                'BillNo' => 'HBD-W-' . $random_string,
                'BillDate' => Carbon::parse(Carbon::now())->format('Y-d-m H:i:s'),
                'Operator' => 'sa',
                'SubTotal' => $sub_total,
                'user_id' => $userId,
                'HDDiscountPer' => 0,
                'HDDiscountAmt' => 0,
                'HomeDeliveryCharges' => 0,
                'GrandTotal' => $sub_total,
                'CustomerName' => $name,
                'Address' => $address,
                'ContactNo' => $contact_number,
                'PostalCode' => $postal_code,
                'Employee_ID' => 1,
                'PaymentMode' => 'Cash',
                'HD_Status' => 'Confirmed',
                'GiftCardAmount' => 0,
            ];

            $bill = RestaurantPOS_BillingInfoHD::create($data);

            $other_setting = OtherSetting::first();

            foreach ($cart_data as $cart) {

                $amount = $cart->price * $cart->quantity;

                $new_cart_bill = new RestaurantPOS_OrderedProductBillHD();
                $new_cart_bill->BillID = $bill->Id;
                $new_cart_bill->Dish = $cart->dish_name;
                $new_cart_bill->Rate = $cart->price;
                $new_cart_bill->Quantity = $cart->quantity;
                $new_cart_bill->Amount = $amount;
                $new_cart_bill->VATPer = $other_setting->VAT;
                $new_cart_bill->VATAmount = ($other_setting->VAT / 100) * $amount;
                $new_cart_bill->STPer = $other_setting->ServiceTax;
                $new_cart_bill->STAmount = $amount * ($other_setting->ServiceTax / 100);
                $new_cart_bill->SCPer = $other_setting->ServiceCharges;
                $new_cart_bill->SCAmount = $amount * ($other_setting->ServiceCharges / 100);
                $new_cart_bill->TotalAmount = $amount + (($other_setting->VAT / 100) * $amount) + ($amount * ($other_setting->ServiceTax / 100)) + ($amount * ($other_setting->ServiceCharges / 100));
                $new_cart_bill->Category = $cart->dish->Category;
                $new_cart_bill->save();
            }

            Cart::where(function ($query) use ($userId, $sessionId) {
                if ($userId) {
                    $query->where('user_id', $userId);
                } else {
                    // User is not logged in, use session ID
                    $query->where('session_id', $sessionId);
                }
            })
                ->delete();

            DB::commit(); // Commit the transaction if everything was successful.
            return redirect()->route('home')->with('success', 'Your order has been placed.');
        } catch (\Throwable $th) {
            DB::rollBack(); // Rollback the transaction in case of an error.
            return redirect()->route('home')->with('error', 'An error occurred while processing your order.');
        }
    }

    public function storeMobile(Request $request)
    {
        $random_string = Str::random(4);

        $userId = $request->user_id;
        $name = $request->name;
        $address = $request->address;
        $email = $request->email;
        $postal_code = $request->postal_code;
        $city = $request->city;
        $contact_number = $request->contact_number;

        $cart_data = Cart::where(function ($query) use ($userId) {
            if ($userId) {
                $query->where('user_id', $userId);
            }
        })
            ->with('dish.category')
            ->get();

        $sub_total = 0;

        $modifier_total = 0;
        
        foreach ($cart_data as $cart) {
            $sub_total += $cart->price * $cart->quantity;
            
            $modifiers = CartModifier::where('cart_id',$cart->id)->get();
            foreach($modifiers as $modifier){
                $mod = Modifier::where('MIM_ID',$modifier->MIM_ID)->first();
                
                $modifier_total += $mod->Rate;
            }
        }
        
        $total = $sub_total + $modifier_total;

        $last_id = RestaurantPOS_BillingInfoHD::latest('id')->first();
        if (!$last_id || $last_id == null) {
            $id = 1;
        } else {
            $id = $last_id->Id + 1;
        }

        $data = [
            'Id' => $id,
            'BillNo' => 'HBD-M-' . $random_string,
            'BillDate' => Carbon::parse(Carbon::now())->format('Y-d-m H:i:s'),
            'Operator' => 'sa',
            'user_id' => $userId,
            'SubTotal' => $total,
            'HDDiscountPer' => 0,
            'HDDiscountAmt' => 0,
            'HomeDeliveryCharges' => 0,
            'GrandTotal' => $total,
            'CustomerName' => $name,
            'Address' => $address,
            'ContactNo' => $contact_number,
            'PostalCode' => $postal_code,
            'Employee_ID' => 1,
            'PaymentMode' => 'Cash',
            'HD_Status' => 'Confirmed',
            'GiftCardAmount' => 0,
        ];

        $bill = RestaurantPOS_BillingInfoHD::create($data);

        $other_setting = OtherSetting::first();
        
        $string = '';

        foreach ($cart_data as $cart) {
            
            $modifiers = CartModifier::where('cart_id',$cart->id)->get();
            foreach($modifiers as $modifier){
                $mod = Modifier::where('MIM_ID',$modifier->MIM_ID)->first();
                if ($mod) {
                    // Concatenate ModifierName with a space
                    $string .= $mod->ModifierName . ' ';
                }
            }
            
            $dish_name = $cart->dish_name . ' Add : ' . $string;

            $amount = $cart->price * $cart->quantity + $modifier_total;

            $new_cart_bill = new RestaurantPOS_OrderedProductBillHD();
            $new_cart_bill->BillID = $bill->Id;
            $new_cart_bill->Dish = $dish_name;
            $new_cart_bill->Rate = $cart->price;
            $new_cart_bill->Quantity = $cart->quantity;
            $new_cart_bill->Amount = $amount;
            $new_cart_bill->VATPer = $other_setting->VAT;
            $new_cart_bill->VATAmount = ($other_setting->VAT / 100) * $amount;
            $new_cart_bill->STPer = $other_setting->ServiceTax;
            $new_cart_bill->STAmount = $amount * ($other_setting->ServiceTax / 100);
            $new_cart_bill->SCPer = $other_setting->ServiceCharges;
            $new_cart_bill->SCAmount = $amount * ($other_setting->ServiceCharges / 100);
            $new_cart_bill->TotalAmount = $amount + (($other_setting->VAT / 100) * $amount) + ($amount * ($other_setting->ServiceTax / 100)) + ($amount * ($other_setting->ServiceCharges / 100));
            $new_cart_bill->Category = $cart->dish->Category;
            $new_cart_bill->save();
        }

        Cart::where(function ($query) use ($userId) {
            if ($userId) {
                $query->where('user_id', $userId);
            }
        })
            ->delete();
            
        $save_address = $request->save_address;
        
        if($save_address == 1)
        {
            $already_exist = Address::where('user_id',$userId)->where('address',$address)->first();
            if($already_exist == null){
                $new_address = new Address();
                $new_address->user_id = $userId;
                $new_address->address = $address;
                $new_address->save();
            }
        }

        return response()->json(['status' => 200, 'message' => 'Order Placed successfully!']);
    }
}