<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Models\Studentdetails;
use App\Models\Sponsor;
use App\Models\Payment;


class PaymentController extends Controller
{
    public function processPayment(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'sponsor_id' => 'required',
            'student_id' => 'required',
            'method' => 'required',
            'amount' => 'required|numeric',
        ]);

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

        $payment = Payment::create($validator->validated());

        return response()->json(['message' => 'Payment processed successfully!', 'payment' => $payment], 201);
    }

    public function list()
    {
        $payments = Payment::with(['sponsor', 'student'])->get();

        return response()->json(['payments' => $payments], 200);
    }

   

    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'sponsor_id' => 'required',
            'student_id' => 'required',
            'method' => 'required',
            'amount' => 'required|numeric',
        ]);

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

        $payment = Payment::findOrFail($id);
        $payment->update($validator->validated());

        return response()->json(['message' => 'Payment updated successfully!', 'payment' => $payment], 200);
    }

    public function destroy($id)
    {
        $payment = Payment::findOrFail($id);
        $payment->delete();

        return response()->json(['message' => 'Payment deleted successfully!'], 200);
    }
}
