<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Stripe\Stripe;
use Stripe\PaymentIntent;
use App\Models\Order;
use Omnipay\Omnipay;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class CheckoutController extends Controller
{
    protected $paypalGateway;

    public function __construct()
    {
        $this->paypalGateway = Omnipay::create('PayPal_Express');
        $this->paypalGateway->setUsername(config('services.paypal.username'));
        $this->paypalGateway->setPassword(config('services.paypal.password'));
        $this->paypalGateway->setSignature(config('services.paypal.signature'));
        $this->paypalGateway->setTestMode(config('services.paypal.sandbox'));
    }

    public function show()
    {
        $cartItems = session()->get('cart', []);
        
        if (empty($cartItems)) {
            return redirect()->route('cart.view')->with('error', 'Your cart is empty');
        }

        $total = array_reduce($cartItems, function($carry, $item) {
            return $carry + ($item['price'] * $item['quantity']);
        }, 0);
        
        return view('checkout.checkout', [
            'cartItems' => $cartItems,
            'total' => $total,
            'stripeKey' => config('services.stripe.key')
        ]);
    }

    public function paypalPayment(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:255',
                'email' => 'required|email|max:255',
                'address' => 'required|string|max:500',
                'city' => 'required|string|max:255',
                'state' => 'required|string|max:255',
                'number' => 'required|string|max:20',
                'amount' => 'required|numeric|min:0.01',
                'cart_items' => 'required|array|min:1'
            ]);

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

            $cartItems = session()->get('cart', []);
            
            if (empty($cartItems)) {
                return response()->json(['error' => 'Your cart is empty'], 400);
            }
    
            $total = array_reduce($cartItems, function($carry, $item) {
                return $carry + ($item['price'] * $item['quantity']);
            }, 0);
            
            $productNames = implode(', ', array_column($cartItems, 'name'));
            $sizes = implode(', ', array_column($cartItems, 'size'));
    
            // Create order
            $order = new Order();
            $order->name = $request->name;
            $order->user_id = Auth::id();
            $order->email = $request->email;
            $order->address = $request->address;
            $order->city = $request->city;
            $order->amount = $request->$total;
            $order->state = $request->state;
            $order->number = $request->number;
          
            $order->size = $sizes ?? '-';
            $order->product_name = $productNames;
            $order->amount = $total;
            $order->payment_method = 'paypal';
            $order->transaction_id = 'pending';
            $order->status = 'pending';
            $order->save();
    
            $response = $this->paypalGateway->purchase([
                'amount' => number_format($total, 2, '.', ''),
                'currency' => 'USD',
                'returnUrl' => route('thank-you', ['order_id' => $order->id]),
                'cancelUrl' => route('checkout'),
                'description' => 'Order #'.$order->id,
            ])->send();
    
            if ($response->isRedirect()) {
                return response()->json([
                    'success' => true,
                    'redirect_url' => $response->getRedirectUrl()
                ]);
            }
            
            $order->delete();
            return response()->json([
                'error' => $response->getMessage() ?? 'Payment failed'
            ], 400);
            
        } catch (\Exception $e) {
            Log::error('PayPal Payment Error: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
            return response()->json([
                'error' => 'Payment processing error. Please try again.'
            ], 500);
        }
    }
    
    public function createPaymentIntent(Request $request)
    {
        try {
            Log::info('Creating payment intent with data:', $request->all());
            
            $validator = Validator::make($request->all(), [
                'amount' => 'required|numeric|min:0.01'
            ]);
    
            if ($validator->fails()) {
                Log::error('Validation failed', $validator->errors()->toArray());
                return response()->json([
                    'error' => 'Invalid amount',
                    'errors' => $validator->errors()
                ], 422);
            }
    
            $cartItems = session()->get('cart', []);
            
            if (empty($cartItems)) {
                Log::error('Empty cart detected');
                return response()->json(['error' => 'Your cart is empty'], 400);
            }
    
            // Calculate amount from cart
            $calculatedAmount = array_reduce($cartItems, function($carry, $item) {
                return $carry + ($item['price'] * $item['quantity']);
            }, 0) * 100;
    
            Log::info('Calculated amount: '.$calculatedAmount);
            Log::info('Request amount: '.($request->amount * 100));
    
            // Verify the amount matches
            if (abs($calculatedAmount - ($request->amount * 100)) > 1) {
                Log::error('Amount mismatch detected');
                return response()->json([
                    'error' => 'Amount mismatch',
                    'details' => [
                        'calculated' => $calculatedAmount,
                        'requested' => $request->amount * 100
                    ]
                ], 400);
            }
    
            Stripe::setApiKey(config('services.stripe.secret'));
            
            Log::info('Creating Stripe payment intent with amount: '.$calculatedAmount);
            
            $intent = PaymentIntent::create([
                'amount' => $calculatedAmount,
                'currency' => 'usd',
                'metadata' => [
                    'user_id' => Auth::id(),
                    'session_id' => session()->getId()
                ],
                'payment_method_types' => ['card'],
            ]);
    
            Log::info('Payment intent created:', ['id' => $intent->id]);
            
            return response()->json([
                'clientSecret' => $intent->client_secret
            ]);
    
        } catch (\Exception $e) {
            Log::error('Payment Intent Error: '.$e->getMessage()."\n".$e->getTraceAsString());
            return response()->json([
                'error' => 'Payment processing error',
                'stripe_error' => $e->getMessage()
            ], 500);
        }
    }

    public function showThankYou($order_id)
    {
        $order = Order::findOrFail($order_id);
        
        // Verify PayPal payment if coming back from PayPal
        if (request()->has('token') && request()->has('PayerID') && $order->status === 'pending') {
            $this->verifyPayPalPayment($order);
            $order->refresh();
        }
        
        // Clear cart if payment was successful
        if ($order->status === 'completed') {
            session()->forget('cart');
        }
        
        return view('thank-you', ['order' => $order]);
    }

    protected function verifyPayPalPayment($order)
    {
        try {
            $response = $this->paypalGateway->completePurchase([
                'amount' => number_format($order->amount, 2, '.', ''),
                'transactionId' => request('token'),
                'PayerID' => request('PayerID'),
            ])->send();

            if ($response->isSuccessful()) {
                $order->update([
                    'status' => 'completed',
                    'transaction_id' => $response->getTransactionReference() ?? request('token')
                ]);
                return true;
            }
            
            return false;
            
        } catch (\Exception $e) {
            Log::error('PayPal verification error: '.$e->getMessage());
            return false;
        }
    }

  
   public function process(Request $request)
{
 
    $order= new Order;
    $order->email=$request->email;
    $order->name=$request->name;
    $order->product_name=$request->product_name;
    $order->city=$request->city;
    $order->amount=$request->amount;
    $order->quantity=$request->quantity;
    $order->address=$request->address;
    $order->state=$request->state;
    $order->number=$request->number;
  

    $order->save();

      foreach ($request->cart_items as $id => $item) {
            $order->items()->create([
                'product_id' => $id,
                'product_name' => $item['name'],
                'price' => $item['price'],
            
                'quantity' => $item['quantity'],
            ]);
        }
 session()->forget('cart');
    return redirect('/')->with('success','Your Order Has Been Succesfully Created');

   

   
}
}