<?php

namespace App\Repositories;

use App\Models\Order;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\StripCheckoutRepository;
use Gloudemans\Shoppingcart\Facades\Cart;
use Illuminate\Support\Facades\Auth;
use Stripe;

/**
 * Class StripCheckoutRepositoryEloquent.
 *
 * @package namespace App\Repositories;
 */
class StripeRepositoryEloquent extends BaseRepository implements StripeRepository
{


    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return Order::class;
    }
    public function frontCharge($stripeToken, $total)
    {
        try {
            Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));

            $charge = Stripe\Charge::create([
                "amount" => $total['amount_total'],
                "currency" => "usd",
                "source" => $stripeToken,
                "description" => "Test payment Luxury Candles"
            ]);

            \Log::info('Stripe Charge Successful', ['charge' => $charge]);

            return $charge;

        } catch (\Exception $e) {
            \Log::error('Stripe Charge Error: ' . $e->getMessage());
        }
    }




    public function checkFrontStripeToken($stripeToken)
    {
        if (!isset($stripeToken)) {
            return redirect()->back()->with('error', 'Stripe token is missing or invalid.');
        }
        return $stripeToken;
    }

    public function checkGuestUser($formData)
    {
        if (!Auth::user()) {
            if (!isset($formData['email']) && !isset($formData['password'])) {
                return redirect()->route('front.checkout.form')->with('error', 'Your data required');
            }
            return true;
        }
        return false;
    }

    public function calculateTaxForSale($data)
    {
        \Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));

        try {
            $lineItems = [];
            $cart = session('cart', []);
            if (empty($cart)) {
                return response()->json(['error' => 'Cart is empty'], 400);
            }

            foreach ($cart as $key => $item) {
                $amount = $item['price'] * $item['quantity'];
                $lineItems[] = [
                    'amount' => (int) ($amount * 100),
                    'reference' => 'li' . ($item['product_id'] ?? ($key + 1)),
                ];
            }


            $calculationData = [
                'currency' => 'usd',
                'line_items' => $lineItems,
                'customer_details' => [
                    'address' => [
                        'line1' => $data['address'],
                        'city' => $data['city'],
                        'state' => $data['state'],
                        'postal_code' => $data['postal_code'],
                        'country' => $data['country'],
                    ],
                    'address_source' => $data['address_source'] ?? 'shipping',
                ],
                'shipping_cost' => ['amount' => 12 * 100, 'tax_behavior' => 'inclusive',],
            ];

            $calculation = \Stripe\Tax\Calculation::create($calculationData);

            return response()->json($calculation);

        } catch (\Stripe\Exception\ApiErrorException $e) {
            return response()->json(['error' => 'Stripe Error: ' . $e->getMessage()], 500);
        } catch (\Exception $e) {
            return response()->json(['error' => 'An error occurred: ' . $e->getMessage()], 500);
        }
    }



}
