<?php

namespace App\Http\Controllers;

use App\Http\Requests\PaymentRequest;
use App\Models\Payment;
use App\Models\Project;
use Illuminate\Http\Request;

class PaymentController extends Controller
{
    private function createOrEdit(Payment $payment)
    {
        $paymentStatuses = __('enums.payment_status');
        $paymentTypes = __('enums.payment_type');
        $projectQuery = Project::orderBy('id', 'DESC');
        if($projectId = request()->input('project_id')) {
            $projectQuery->where('id', $projectId);
        }
        $projects = $projectQuery->get()->pluck('title', 'id');
        return view('payment.edit', [
            'payment' => $payment,
            'paymentTypes' => $paymentTypes,
            'paymentStatuses' => $paymentStatuses,
            'projects' => $projects]);
    }
    public function index()
    {
        $payments = Payment::orderBy('id', 'DESC')->get();
        return view('payment.index', ['payments' => $payments]);
    }

    public function create()
    {
        $payment = new Payment();
        return $this->createOrEdit($payment);
    }

    public function store(PaymentRequest $request)
    {
        $validated = $request->validated();
        if(!$validated) {
            return redirect()->back()->withInput()->withErrors($request->messages());
        }
        $payment = Payment::create($request->all());
        return redirect()->route('adm.payment.edit', ['payment' => $payment->id]);
    }

    public function show($id)
    {
        //
    }

    public function edit($id)
    {
        $payment = Payment::find($id);
        return $this->createOrEdit($payment);
    }

    public function update(Request $request, $id)
    {
        $validated = $request->validated();
        if(!$validated) {
            return redirect()->back()->withInput()->withErrors($request->messages());
        }
        $payment = Payment::find($id);
        $payment->fill($request->all());
        $payment->save();
        session()->flash('success_alert', 'Updated');
        return redirect()->route('adm.payment.edit', ['payment' => $payment->id]);
    }

    public function destroy($id)
    {
        //
    }
}
