<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Events\TransactionStatusUpdated;
class SubscriptionPurchaseController extends Controller
{
    /**
     * Get the authenticated user's ID.
     *
     * @return int|null
     */
    private function getUserId()
    {
        $user = Auth::user();
        return $user ? $user->user_id : null;
    }

    /**
     * Handle transaction entry.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
  public function createTransaction(Request $request)
{
    $user_id = $this->getUserId();
    
    if (!$user_id) {
        return response()->json(['message' => 'Unauthorized'], 401);
    }

    // Validate input data
    $validator = Validator::make($request->all(), [
        'amount' => 'required|numeric',
        'payment_method' => 'required|string',
        'status' => 'required|string|in:pending,completed,failed',
        'trxid' => 'nullable|string|unique:transactions,trxid,' . $request->transaction_id, // Ignore unique check if updating
        'transaction_id' => 'nullable|integer|exists:transactions,id' // Ensure transaction_id exists if provided
    ]);

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

    try {
        if ($request->has('transaction_id')) {
            // Update existing transaction
            DB::update(
                'UPDATE transactions SET amount = ?, status = ?, payment_method = ?, trxid = ?, updated_at = NOW() 
                 WHERE id = ? AND user_id = ?',
                [
                    $request->amount,
                    $request->status,
                    $request->payment_method,
                    $request->trxid,
                    $request->transaction_id,
                    $user_id
                ]
            );

            return response()->json([
                'message' => 'Transaction updated successfully',
                'transaction_id' => $request->transaction_id
            ], 200);
        } else {
            // Insert a new transaction
            DB::insert(
                'INSERT INTO transactions (user_id, transaction_date, amount, status, payment_method, trxid, created_at, updated_at) 
                 VALUES (?, NOW(), ?, ?, ?, ?, NOW(), NOW())',
                [
                    $user_id,
                    $request->amount,
                    $request->status,
                    $request->payment_method,
                    $request->trxid
                ]
            );

            // Get the last inserted transaction ID
            $transaction_id = DB::getPdo()->lastInsertId();

            return response()->json([
                'message' => 'Transaction created successfully',
                'transaction_id' => $transaction_id
            ], 201);
        }
    } catch (\Exception $e) {
        return response()->json(['error' => 'Failed to create/update transaction', 'details' => $e->getMessage()], 500);
    }
}



    /**
     * Handle subscription purchase entry.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function createSubscriptionPurchase(Request $request)
    {
        $user_id = $this->getUserId();
        
        if (!$user_id) {
            return response()->json(['message' => 'Unauthorized'], 401);
        }

        // Validate input data
        $validator = Validator::make($request->all(), [
            'subscription_plan_id' => 'required|integer',
            'transaction_id' => 'required|integer',
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

        // Check if the transaction exists
        $transaction = DB::selectOne('SELECT status FROM transactions WHERE id = ? AND user_id = ?', [
            $request->transaction_id,
            $user_id
        ]);

        if (!$transaction) {
            return response()->json(['message' => 'Invalid transaction.'], 400);
        }

        // Determine valid_until based on transaction status
        $valid_until = $transaction->status === 'completed' ? now()->addMonth() : null;

        // Insert subscription purchase record
        DB::insert('INSERT INTO subscription_purchases (user_id, subscription_plan_id, purchase_date, valid_until, transaction_id, created_at, updated_at) VALUES (?, ?, NOW(), ?, ?, NOW(), NOW())', [
            $user_id,
            $request->subscription_plan_id,
            $valid_until,
            $request->transaction_id
        ]);

        return response()->json([
            'message' => 'Subscription purchased successfully',
            'valid_until' => $valid_until
        ]);
    }
}
