<?php

namespace App\Http\Controllers;

use App\Helpers\Helper;
use App\Models\Payment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PaymentLogController extends Controller
{
    use Helper;

    public function __construct()
    {
        $this->model = new Payment();
    }
    public function index()
    {
        $keyword = input('name');
        $end_date = input('end_date');
        $start_date = input('start_date');

        $user = auth()->user();
        $data = $this->model->with('users:id,name')->orderBy('id','desc')->where('user_id', $user->id)
            ->when($keyword, function ($query) use ($keyword) {
                $query->whereHas('users', function ($query) use ($keyword) {
                    $query->where('name', 'LIKE', "%$keyword%");
                });
            })
            ->when(($start_date || $end_date), function ($query) use ($start_date, $end_date) {
                if ($start_date) {
                    $query->where('created_at', '>=', $start_date);
                }
                if ($end_date) {
                    $query->where('created_at', '<=', $end_date);
                }
            })
            ->paginate(request()->input('perPage'));
        return returnData(2000, $data);
    }

    public function create()
    {
        //
    }


    public function store(Request $request)
    {
        try {
            $validate = $this->model->validate($request->all());

            if($validate->fails()){
                return returnData(3000, $validate->errors(), 'Validation Failed');
            }

            DB::beginTransaction();

            $this->model->fill($request->all());
            $this->model->user_id = auth()->user()->id;
            $this->model->save();

            DB::commit();

            return returnData(2000, null, 'Successfully Inserted');

        } catch (\Exception $exception) {
            return returnData(5000, $exception->getMessage(), $exception->getMessage());
        }
    }


    public function show($id)
    {
        $data = $this->model->with('users:id,name')->where('user_id', user()->id)->orderBy('id','desc')
        ->get();
        // dd($data);

    return returnData(2000, $data);
    }

    public function edit($id)
    {
        //
    }

    public function update(Request $request, $id)
    {
        //
    }

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