<?php

namespace Modules\Weight\Http\Controllers;

use App\Http\Controllers\BasicController;
use Illuminate\Http\Request;
use Modules\Weight\Entities\Model;
use Modules\Weight\Http\Requests\StoreRequest;
use Modules\Weight\Http\Requests\UpdateRequest;
use Yajra\DataTables\DataTables;
use Modules\Country\Entities\Country;

class WebController extends BasicController
{
    public function index(Request $request)
    {
        return view('weight::index');
    }

    public function create()
    {
        $countries = Country::all();
        return view('weight::create', compact('countries'));
    }

    public function store(StoreRequest $request)
    {
        Model::create($request->validated());
        toast(__('trans.addedSuccessfully'), 'success');
        return redirect()->back();
    }

    public function show($id)
    {
        $Model = Model::with('country')->findOrFail($id);
        return view('weight::show', compact('Model'));
    }

    public function edit($id)
    {
        $Model = Model::findOrFail($id);
        $countries = Country::all();
        return view('weight::edit', compact('Model', 'countries'));
    }

    public function update(UpdateRequest $request, $id)
    {
        Model::where('id', $id)->update($request->validated());
        toast(__('trans.updatedSuccessfully'), 'success');
        return redirect()->back();
    }

    public function destroy($id)
    {
        Model::where('id', $id)->delete();
    }

    public function datatable(Request $request)
    {
        try {
            $locale = lang();
            $titleColumn = "title_" . $locale;

            $query = Model::query()
                ->with('country')
                ->orderBy('country_id')
                ->orderBy('price')
                ->when(
                    $request->filled(['sort_column', 'sort_direction']),
                    fn($query) => $query->orderBy($request->sort_column, $request->sort_direction)
                );
            return DataTables::of($query)
                ->addColumn('title', fn($model) => $model->country->title() ?? '')
                ->addColumn('actions', fn($model) => view('weight::layouts.actions', ['Model' => $model]))
                ->editColumn('price', fn($model) => number_format($model->price, 2))
                ->editColumn('weight', fn($model) => $model->weight)
                ->editColumn('created_at', fn($model) => optional($model->created_at)->translatedFormat("F j, Y, g:i a"))
                ->addIndexColumn()
                ->rawColumns(['actions'])
                ->make(true);

        } catch (\Throwable $e) {
            return response()->json([
                'error' => true,
                'message' => $e->getMessage(),
                'line' => $e->getLine(),
            ], 500);
        }
    }
}
