<?php

declare(strict_types=1);

namespace App\Http\Controllers\Payment;

use App\Http\Controllers\Controller;
use App\Http\Resources\PaymentResource;
use App\Models\Payment;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Mortezaa97\Orders\Models\Order;

class PaymentController extends Controller
{
    public function index(Request $request)
    {
        $items = new Payment;

        if ($request->conditions) {
            $items = $items->where(json_decode($request->conditions, true));
        }

        if ($request->with) {
            $items = $items->with($request->with);
        }

        return $request->noPaginate ? $items->get() : $items->paginate();
    }

    public function store(Request $request)
    {
        Gate::authorize('create', Payment::class);
        $user = Auth::guard('api')->user();
        if (! $user) {
            return ApiResponse::response(message: 'شما وارد سایت نشده اید!', status: 420);
        }
        $payment = new Payment;
        $data = $request->all();
        $data['created_by'] = Auth::user()->id;

        return $payment->create($data);
    }

    public function show(Payment $payment)
    {
        $payment->load(['user', 'model']);
        if ($payment->model_type === Order::class) {
            $payment->loadMissing('model.address');
        }
        return new PaymentResource($payment);
    }

    public function update(Request $request, Payment $payment)
    {
        Gate::authorize('update', $payment);
        $data = $request->all();
        $data['updated_by'] = Auth::user()->id;
        $payment->update($data);

        return $payment;
    }

    public function destroy(Payment $payment)
    {
        Gate::authorize('delete', $payment);

        return $payment->delete();
    }
}
