<?php

namespace App\Http\Controllers\Restaurant;

use App\Http\Controllers\Controller;
use Illuminate\Validation\Rule;
use Illuminate\Http\Request;

use App\Models\Restaurant\ProductCategory;
use App\Models\Restaurant\Product;

use App\Helpers\Environment\SystemModulesHelper;

class ProductController extends Controller
{
  //* Constructor
    public function __construct() {
        $this->middleware(['auth', 'role:administrador'])->except(['identifyProduct', 'getData', 'getByCodeBar']);
    }

  //* Basic CRUD
    public function index() {
      //- Avoid on disabled module
        if(!SystemModulesHelper::getModuleStatus('restaurant'))
            return view('errors.403');

      //- Table Data
        if(request()->ajax()){
            return datatables()->of(Product::latest()->get())
                ->addColumn('category',function($data){
                    return $data->productCategory->category_name;
                })
                ->addColumn('created_at', function($data){
                    return date("d-m-Y H:i:s", strtotime($data->created_at));
                })
                ->addColumn('updated_at', function($data){
                    return date("d-m-Y H:i:s", strtotime($data->updated_at));
                })
                ->addColumn('action', function($data){
                    $button = '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-ms"><i class="fa fa-edit"></i></button>';
                    $button .= '&nbsp;&nbsp;';
                    $button .= '<button type="button" name="delete" id="'.$data->id.'" class="delete btn btn-danger btn-ms"><i class="fa fa-trash"></i></button>';
                    return $button;
                })
                ->rawColumns(['action'])
                ->make(true);
        }

      //- View Data
        return view('restaurant.products.index', ['categories' => ProductCategory::all()]);
    }

    public function store(Request $request) {
        $form_data = $this->parseFormData($request);
        Product::Create($form_data);

        return response()->json(['success' => 'Registrado con éxito']);
    }

    public function edit($id) {
        if(request()->ajax()){
            $data = Product::findOrFail($id);
            return response()->json(['data' => $data]);
        }

        return view('errors.404');
    }

    public function update(Request $request) {
        $form_data = $this->parseFormData($request);
        Product::whereId($request->hidden_id)->update($form_data);

        return response()->json(['success', 'Actualizado con éxito']);
    }

    public function destroy($id) {
        $data = Product::findOrFail($id);
        $data->delete();
    }

  //* Special Functions
    public function identifyProduct(Request $request) {
        if (!$request->filled('value')) return;

        return Product::where('product_barcode', 'LIKE', '%'.$request->value.'%')
            ->orWhere('product_name', 'LIKE', '%'.$request->value.'%')
            ->get();
    }

    public function getByCodeBar(Request $request) {
        if (!$request->filled('barcode')) return;

        return Product::where('product_barcode', $request->barcode)->first();
    }

    public function getData($id) {
        return Product::select('id', 'product_name', 'product_price', 'category_id')
            ->where('id', $id)
            ->first();
    }

  //* Support Functions
    public function parseFormData(Request $request) {
        $request->validate(
            [
                'category_id'   => ['required', 'integer', 'exists:product_categories,id'],
                'titulo'  => ['required','string','max:250','min:1'],
                'precio' => ['required','numeric','min:0'],

                'barcode' => [
                    'nullable', 'string',
                    Rule::unique('products', 'product_barcode')->ignore($request->hidden_id),
                    'max:100','min:3'
                ],
            ],
            [],[
                'category_id' =>  __('entity_fields')['product']['category'],
                'titulo'      => __('entity_fields')['common']['name'],
                'precio'      =>  __('entity_fields')['common']['price'],
                'barcode'     => __('entity_fields')['product']['barcode'],
            ]
        );

        return array_filter([
            'category_id' => $request->input('category_id'),
            'product_name' => $request->input('titulo'),
            'product_barcode' => $request->input('barcode', null),
            'product_price' => $request->input('precio'),
        ], fn ($value) => $value !== null); // Exclude Null Values
    }
}
