<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Payment;
use App\Models\Order;
use Illuminate\Support\Facades\Auth;

class PaymentController extends Controller
{
    /**
     * Store a newly created payment in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        // Validate request
        $validated = $request->validate([
            'order_id' => 'required|integer|exists:orders,id',
            'received_amount' => 'required|numeric|min:0',
            'payment_type' => 'required|integer|in:1,2,3,4,5,6',
            'payment_note' => 'nullable|string',
            'customer_id' => 'nullable|integer|exists:customers,id',
            'customer_name' => 'nullable|string',
            'payment_date' => 'required|date',
        ]);

        try {
            // Get authenticated user
            $user = Auth::user();

            // Create payment
            $payment = Payment::create([
                'order_id' => $validated['order_id'],
                'received_amount' => $validated['received_amount'],
                'payment_type' => $validated['payment_type'],
                'payment_note' => $validated['payment_note'] ?? null,
                'customer_id' => $validated['customer_id'] ?? null,
                'customer_name' => $validated['customer_name'] ?? null,
                'payment_date' => $validated['payment_date'],
                'financial_year_id' => $user->financial_year_id ?? null,
                'created_by' => $user->id,
            ]);

            // Load payment with relationships
            $payment->load(['order', 'customer']);

            return response()->json([
                'message' => 'Payment successfully added',
                'data' => $payment
            ], 201);

        } catch (\Exception $e) {
            return response()->json([
                'message' => 'Failed to add payment',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
