<?php
namespace App\Http\Controllers\Member;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class PaymentController extends Controller
{
    /**
     * Display the payment confirmation form to the member.
     * * @param string $id (UUID of the card request)
     * @return \Illuminate\View\View
     */
    public function showForm($id)
    {
        // Retrieve card request details along with its settings (title and price)
        $request_data = DB::table('card_requests')
            ->join('card_settings', 'card_requests.card_id', '=', 'card_settings.id')
            ->where('card_requests.id', $id)
            ->select('card_requests.id', 'card_settings.card_title', 'card_settings.price')
            ->first();

        // If the request is not found, return 404
        if (!$request_data) { 
            abort(404); 
        }

        return view('member.payment.confirm_form', compact('request_data'));
    }

    /**
     * Handle the submission of payment proof (Image & Transaction details).
     * * @param Request $request
     * @param string $id (UUID of the card request)
     * @return \Illuminate\Http\RedirectResponse
     */
    public function submitProof(Request $request, $id)
    {
        // Validate input fields to ensure data integrity
        $request->validate([
            'transaction_number' => 'required|string|max:100',
            'amount_paid'        => 'required|numeric',
            'receipt_photo'      => 'required|image|mimes:jpg,jpeg,png|max:2048', // 2MB Max
        ]);

        // Handle the file upload process
        $fileName = time() . '_' . $id . '.' . $request->receipt_photo->extension();
        $request->receipt_photo->move(public_path('uploads/receipts'), $fileName);
        $path = 'uploads/receipts/' . $fileName;

        // Store the payment proof details in the 'payment_proofs' table
        DB::table('payment_proofs')->insert([
            'id'                 => Str::uuid(),
            'card_request_id'    => $id,
            'transaction_number' => $request->transaction_number,
            'receipt_path'       => $path,
            'amount_paid'        => $request->amount_paid,
            'member_note'        => $request->note,
            'status'             => 'pending',
            'created_at'         => now(),
            'updated_at'         => now(),
        ]);

        // Update the original card request status to '2' (Awaiting Admin Review)
        DB::table('card_requests')
            ->where('id', $id)
            ->update(['is_active' => 2]);

        // Return back with a success message for the user
        return redirect()->back()->with('success', 'Payment proof submitted successfully. Our team will review it shortly.');
    }
}