<?php

namespace App\Http\Controllers\Payment;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Http;
use App\Models\Order;
use paystack;

class PaystackController extends Controller
{
    public function pay(Request $request)
    {
        $order_id = $request->order_id ?? Session::get('paystack_order_id');
        $order = Order::findOrFail($order_id);

        // Replace with your actual values
        $paystackSecretKey = env('PAYSTACK_SECRET_KEY'); // Should be in .env
        $callback_url = route('paystack.callback');

        $response = Http::withToken($paystackSecretKey)->post('https://api.paystack.co/transaction/initialize', [
            'email' => $order->email, // or user's email
            'amount' => $order->pay_amount * 100, // Paystack uses kobo
            'reference' => $order->transaction_number,
            'callback_url' => $callback_url,
            'currency' => 'NGN', // or use $order->currency
        ]);

        $body = $response->json();

        if (!$response->successful() || !isset($body['data']['authorization_url'])) {
            return redirect()->back()->with('error', 'Paystack payment failed to initialize.');
        }

        return redirect($body['data']['authorization_url']);
    }

    public function callback()
{
    try {
        $paymentDetails = Paystack::getPaymentData(); // This returns payment info from Paystack
        $order_id = Session::get('paystack_order_id');

        if (!$order_id) {
            return redirect()->route('front.checkout')->with('error', 'No order reference found.');
        }

        $order = Order::findOrFail($order_id);

        // Validate status
        if ($paymentDetails['data']['status'] === 'success') {
            $order->payment_status = 'Paid';
            $order->order_status = 'Processing'; // or your preferred status
            $order->txnid = $paymentDetails['data']['reference'];
            $order->save();

            // Clear cart and session
            Session::forget('cart');
            Session::forget('paystack_order_id');

            return redirect()->route('front.checkout.success');
        } else {
            return redirect()->route('front.checkout')->with('error', 'Payment failed or was cancelled.');
        }

    } catch (\Exception $e) {
        return redirect()->route('front.checkout')->with('error', 'Payment verification failed.');
    }
}

    
   // public function pay($order_id)
//{
    //$order = Order::findOrFail($order_id);

    // Store order ID in session to retrieve on callback
    //Session::put('paystack_order_id', $order->id);

    // Get Paystack keys from settings
   // $paystackSettings = PaymentSetting::where('unique_keyword', 'paystack'//)->first();
    //$paystackData = $paystackSettings ? json_decode($paystackSettings->settings, //true) : [];

   // $secret_key = $paystackData['secret_key'] ?? null;

    //if (!$secret_key) {
   // //    return redirect()->route('front.checkout')->with('error', 'Paystack //Secret Key not set.');
   // }

   // \Config::set('paystack.secretKey', $secret_key);

   // $amount = round($order->pay_amount * 100); // amount in kobo

    // Create payment request
    //return Paystack::getAuthorizationUrl()->redirectNow();
//}

}
