<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Payment;
use App\Models\PlanPurchase;
use Illuminate\Http\Request;
use App\Models\TradingYear;
use Stripe\Stripe;
use Stripe\PaymentIntent;
use Illuminate\Support\Facades\Validator;

class PaymentController extends Controller
{

    public function CreatePaymentIntent(Request $request)
    {
        try {

            Stripe::setApiKey(env('STRIPE_SECRET'));

            // dd(env('STRIPE_SECRET'));

            $amount = $request->amount;
            $currency = $request->currency;
            // dd($amount);

            $paymentIntent = PaymentIntent::create([
                'amount' => $amount,
                'currency' => $currency,
                'automatic_payment_methods' => [
                    'enabled' => true,
                    'allow_redirects' => 'never',
                ],
            ]);

            return response()->json([
                'success' => true,
                'amount' => $amount,
                'currency' => $currency,
                'id' => $paymentIntent->id,
                'clientSecret' => $paymentIntent->client_secret,
            ], 200);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 500);
        }
    } 


    public function ConfirmPayment(Request $request)
    {           
   
        Stripe::setApiKey(env('STRIPE_SECRET'));

        try {

            $paymentIntentId = $request->payment_intent_id;
            $paymentMethodId = $request->payment_method_id;

            $paymentIntent = PaymentIntent::retrieve($paymentIntentId);
            $paymentIntent->confirm([
                // 'payment_method' => 'pm_card_visa',
                'payment_method' => $paymentMethodId,
            ]);

            if($paymentIntent->status === 'succeeded')
            {
                $user = auth()->user();
                $user_id = $user->id;
                $trading_year_id = $user->current_trading_year_id;
                $trading_year = TradingYear::find($trading_year_id);
                
                $payment = Payment::create([
                    'user_id' => $user_id,
                    'trading_year_id' => $trading_year_id,
                    'amount' => $paymentIntent->amount/100,
                    'payment_method' => "Stripe",
                    'transaction_id' => $paymentIntentId,
                    'payment_date' => now(),
                    'payment_status' => $paymentIntent->status,
                ]);

                $plan_purchase = PlanPurchase::create([
                    'user_id' => $user_id,
                    'trading_year_id' => $trading_year_id,
                    'plan_id' => 1,
                    'payment_id' => $payment->id,
                    'amount' => $paymentIntent->amount/100,
                    'start_date' => now(),
                    'end_date' => $trading_year->tradingyear_enddate,
                    'tradingyear_startdate' => date('Y-m-d', strtotime($trading_year->tradingyear_startdate)),
                    'tradingyear_enddate'   => date('Y-m-d', strtotime($trading_year->tradingyear_enddate)),
                    'payment_status' => $paymentIntent->status,
                    'plan_status' => 1,
                    'expiry_status' => 1,
                ]);

                return response()->json([
                    'success' => true,
                    'message' => 'Payment Confirmed and Saved Successfully.',
                    'payment' => $payment,
                    'plan_purchases' => $plan_purchase,
                ], 200);
            }

            return response()->json([
                'success' => false,
                'status' => $paymentIntent->status,
                'message' => 'Payment Not Completed.'
            ], 400);

        } catch (\Exception $e) {

            return response()->json([
                'error' => $e->getMessage()
            ], 500);

        }
    }



    // public function storePayment(Request $request)
    // {
    //     // Define the validation rules
    //     $rules = [
    //         'amount' => 'required|numeric|min:0.01',
    //         'payment_method' => 'required|string',
    //         'transaction_id' => 'required|string|unique:payments,transaction_id', // Ensure unique transaction ID
    //         'payment_date' => 'required|date',
    //         'payment_status' => 'required|string',
    //         // 'plan_id' => 'required|exists:plans,id', // Validate the plan ID
    //     ];

    //     // Create a validator instance
    //     $validator = Validator::make($request->all(), $rules);

    //     // Check if the validation fails
    //     if ($validator->fails()) {
    //         return response()->json([
    //             'success' => false,
    //             'errors' => $validator->errors()
    //         ], 422);
    //     }

    //     try {
    //         // Check if the user is authenticated
    //         if (!auth()->check()) {
    //             return response()->json(['success' => false, 'error' => 'User is not authenticated'], 401);
    //         }

    //         $user = auth()->user();  // Get authenticated user
    //         $user_id = $user->id; // Retrieve the authenticated user ID
    //         $trading_year_id = $user->current_trading_year_id; // Retrieve the current trading year ID

    //         // Ensure the trading year is valid
    //         if (!$trading_year_id) {
    //             return response()->json(['success' => false, 'error' => 'Current trading year not found'], 404);
    //         }

    //         // Add the authenticated user_id and trading_year_id to the validated data
    //         $validatedData = $validator->validated();
    //         $validatedData['user_id'] = $user_id;
    //         $validatedData['trading_year_id'] = $trading_year_id;

    //         // Create the payment record
    //         $payment = Payment::create($validatedData);


    //         // Create the plan purchase record
    //         $plan_purchase = PlanPurchase::create([
    //             'user_id' => $user_id,
    //             'trading_year_id' => $trading_year_id,
    //             'plan_id' => '1', //$request->plan_id,
    //             'payment_id' => $payment->id, // Associate the payment ID
    //             'plan_status' => '1', // Default to active
    //             'expiry_status' => '0', // Default expiry status
    //         ]);


    //         // Add is_plan_purchased to the payment object
    //         $payment->is_plan_purchased = PlanPurchase::where('payment_id', $payment->id)->exists();

    //         return response()->json([
    //             'success' => true,
    //             'message' => 'Payment and plan purchase record created successfully',
    //             'data' => $payment,
    //             'plan_purchase' => $plan_purchase,
    //             //  [
    //             //     'payment' => $payment,
    //             //     'plan_purchase' => $plan_purchase,
    //             // ] //0932413202
    //         ], 201);
    //     } catch (\Exception $e) {
    //         return response()->json([
    //             'success' => false,
    //             'message' => 'Failed to create payment or plan purchase record',
    //             'error' => $e->getMessage()
    //         ], 500);
    //     }
    // }



    public function getUserPayments()
    {
        try {
            // Ensure the user is authenticated
            if (auth()->check()) {
                $user_id = auth()->id();
            } else {
                return response()->json(['success' => false, 'error' => 'User is not authenticated'], 401);
            }

            // Retrieve the user's payments along with associated plan and trading_year
            $payments = Payment::with(['plan', 'tradingYear'])
                ->where('user_id', $user_id)
                ->get();

            // Check if the user has any payments
            if ($payments->isEmpty()) {
                return response()->json([
                    'success' => true,
                    'message' => 'No payments found for this user',
                    'data' => []
                ], 200);
            }

            // Return the payments with plan and trading year data
            return response()->json([
                'success' => true,
                'message' => 'Payments retrieved successfully',
                'data' => $payments
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve payments',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
