<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Course;
use App\Models\Subscription;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class PaymentController extends Controller
{
    public function payCourse(Request $request)
    {
        try {
            $request->validate([
                'course_id' => 'required|exists:courses,id',
                // Add other necessary validation rules for payment details
            ]);
        } catch (ValidationException $e) {
            return sendCustomResponse(false, '', $e->getMessage(), $e->errors(), 422);
        }

        // check if user is already subscribed to the course
        $user = $request->user();
        $courseId = $request->course_id;

        $isSubscribed = Subscription::where('user_id', $user->id)
            ->where('course_id', $courseId)
            ->whereDate('expires_at', '>', now())
            ->exists();

        if ($isSubscribed) {
            return sendCustomResponse(false, '', 'You are already subscribed to this course.', '', 422);
        }

        // Implement your payment logic here
        $course = Course::find($courseId);
        // Create a new subscription record
        Subscription::create([
            'user_id' => $user->id,
            'course_id' => $courseId,
            'price' => $course->price,
            'expires_at' => now()->addDays(30), // Set the expiration date
        ]);

        return sendCustomResponse(true, [
            'payment_url' => null,
        ], 'Payment processed successfully', '', 200);
    }


    public function myReceipts(Request $request)
    {
        $user = $request->user();

        $receipts = Subscription::where('user_id', $user->id)
            ->with('course:id,title,category_id', 'course.category:id,name')
            ->select(['id', 'course_id', 'price', 'expires_at', 'created_at'])
            ->get();

        return sendCustomResponse(true, $receipts, '', '', 200);
    }
}
