<?php

namespace App\Http\Controllers\Hotel;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;

use App\Models\Hotel\Client;

use App\Helpers\Environment\SystemFeaturesHelper;

use App\Enums\Hotel\CustomerSegment;
use App\Enums\Hotel\BehaviorReport;

class ClientsController extends Controller
{
  //* Constructor
    public function __construct() {
        $this->middleware(['auth', 'role:administrador,gerente'])->only(['destroy']);
    }

  //* Basic CRUD
    public function index() {
      //- Table Data
        if(request()->ajax()){
          // Basic Data
            $datatable = datatables()->of(Client::latest()->get())
                ->addColumn('customer_segment', function($data){
                    return "
                        <span class='adjusted_badge' style='{$data->segment_badge}'>
                            {$data->segment_label}
                        </span>
                    ";
                })
                ->addColumn('action', function($data){
                    $button = '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-sm"><i class="fas fa-edit"></i></button>';

                    if(in_array(Auth::user()->role, ['administrador', 'gerente'])) {
                        $button .= '&nbsp;&nbsp;';
                        $button .= '<button type="button" name="delete" id="'.$data->id.'" class="delete btn btn-danger btn-sm"><i class="fas fa-trash-alt"></i></button>';
                    }

                    return $button;
                });

         // Identity Documents
            if (SystemFeaturesHelper::getFeatureStatus("identity_documents")) {
                $datatable->addColumn('identity_document', function($data){
                    $identity_document_type = __('entity_forms')['client'][$data->identity_document_type];

                    $identity_document_number = $identity_document_type === "none"
                        ? "" : "<br> <small>{$data->identity_document_number}</small>";

                    return "{$identity_document_type} {$identity_document_number}";
                });
            }

          // Return Table Data
            return $datatable->rawColumns(['customer_segment', 'identity_document', 'action'])->make(true);
        }

      //- View Data
        $custom_segments = CustomerSegment::cases();
        $behavior_reports = BehaviorReport::cases();

        return view('hotel.clients.index', compact('custom_segments', 'behavior_reports'));
    }

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

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

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

        return view('errors.404');
    }

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

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

    public function destroy($id) {
        try {
            $data = Client::findOrFail($id);
            $data->delete();
        } catch (\Exception $e) {
            return response()->json([
                'message' => $e->getMessage(),
            ], 400);
        }
    }

  //* Special Functions
    public function byName($name) {
        return Client::where('client_name', $name)->first();
    }

    public function search($term) {
        return Client::select('id', 'client_name', 'client_phone', 'client_email', 'identity_document_number')
            ->where('client_name', 'LIKE', '%'.$term.'%')
            ->orWhere('client_phone', 'LIKE', '%'.$term.'%')
            ->orWhere('client_email', 'LIKE', '%'.$term.'%')
            ->orWhere('identity_document_number', 'LIKE', '%'.$term.'%')
            ->take(5)->get();
    }

  //* Support Functions
    public function prepareClientData(Request $request) {
        return array_filter([
            'client_name' => $request->client_name,
            'client_phone' => $request->client_phone ?? __('neutral_words')['none_2'],
            'client_email' => $request->client_email ?? __('neutral_words')['none_2'],
            'client_state' => $request->client_state ?? __('neutral_words')['none_2'],

            'identity_document_type' => $request->document_type,
            'identity_document_number' => $request->document_number ?? "--- --- ---",

            'customer_segment' => $request->customer_segment,
            'behavior_report' => $request->behavior_report,

            'discount_per_loyalty' => $request->discount_per_loyalty ?? 0.0,
        ], fn ($value) => $value !== null); // Retrieves only non-null fields
    }
}

