<?php

namespace App\Http\Controllers\Invoicing;

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

use App\Models\Invoicing\TaxFormat;
use App\Models\User;

use App\Helpers\Environment\SystemEnvHelper;
use App\Helpers\Environment\SystemModulesHelper;

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

  //* Basic CRUD
    public function index() {
      //- Avoid Module on Other Countries
        if (!SystemEnvHelper::areCurrentCountries(['MEX'])) return view('errors.503-modular');

      //- Ensure Establishment TaxData
        if (!SystemModulesHelper::isEstablishmentTaxDataComplete())
            return view('invoicing.invoices.errors.tax-data-not-configured');

      //- Table Data
        if(request()->ajax()){
            return datatables()->of(TaxFormat::latest()->get())
                ->addColumn('url_logo', function($data){
                    return "<img src='{$data->url_logo}' alt='{$data->serie} Logo'
                        style='max-height: 2.5rem; border-radius: 0.5rem; object-fit: container'
                    >";
                })
                ->addColumn('base_color', function($data){
                    return "
                        <div style='border-radius:4px; background-color: {$data->base_color}; border:1px solid #ccc;
                            margin:auto; width:50%; height:1.7rem;'
                        ></div>
                    ";
                })
                ->addColumn('action', function($data){
                    return "
                        <button type='button' id='{$data->id}' class='edit btn btn-primary btn-ms'>
                            <i class='fas fa-pen'></i>
                        </button>
                        &nbsp;&nbsp;
                        <button type='button' id='{$data->id}' class='delete btn btn-danger btn-sm'>
                            <i class='fas fa-trash'></i>
                        </button>
                    ";
                })
                ->rawColumns(['url_logo', 'base_color','action'])
                ->make(true);
        }

      //- View Data
        return view('invoicing.formats.index');
    }

    public function store(Request $request) {
        $form_data = $this->processTaxFormatData($request);
        TaxFormat::create($form_data);

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

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

        return view('errors.404');
    }

    public function update(Request $request) {
        $form_data = $this->processTaxFormatData($request, $request->hidden_id);
        TaxFormat::whereId($request->hidden_id)->update($form_data);

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

    public function destroy($id) {
      // Search Record
        $data = TaxFormat::findOrFail($id);

      // Remove Logo
        if ($data->url_logo && !str_contains($data->url_logo, "only_harsi_bigger.png")) {
            // Convertir la URL a ruta absoluta en disco
            $oldPath = str_replace(request()->getSchemeAndHttpHost(), '', $data->url_logo);
            $fullPath = public_path($oldPath);

            // Verificar existencia y eliminar
            if (file_exists($fullPath)) @unlink($fullPath);
        }

      // Delete Record
        $data->delete();
    }

  //* Support Functions
    // Form
        private function processTaxFormatData(Request $request, $id = null) {
            // Validar Datos
            $request->validate([
                'serie' => [
                    'required',
                    'string',
                    Rule::unique('tax_formats', 'serie')->ignore($id),
                    'max:15',
                    'min:1',
                ]
            ]);

            // Obtener el registro previo si existe (para mantener el logo actual)
            $existing = $id ? TaxFormat::find($id) : null;

            // Manejo del logo
            if ($request->hasFile('format_logo')) {
                // Eliminar el logo anterior si existe y no es nulo
                if ($existing && $existing->url_logo && !str_contains($existing->url_logo, "only_harsi_bigger.png")) {
                    // Extraer la ruta relativa del archivo
                    $oldPath = str_replace($request->getSchemeAndHttpHost(), '', $existing->url_logo);
                    $fullPath = public_path($oldPath);

                    if (file_exists($fullPath)) @unlink($fullPath);
                }

                // Segurar que la carpeta de guardado exista
                $path = public_path('storage/tax-logos');
                    if (!is_dir($path)) @mkdir($path, 0775, true);

                // Subir nuevo logo
                $filename = time() . '.' . $request->format_logo->extension();
                $request->format_logo->move($path, $filename);
                $filename = $request->getSchemeAndHttpHost() . '/storage/tax-logos/' . $filename;
            } else {
                // Usar el logo anterior o  en su defecto, usa el logo del hotel que manejan los usuario como foto de perfil
                $filename = $existing?->url_logo
                    ?? User::first()->profile_photo
                    ?? $request->getSchemeAndHttpHost() . '/images/only_harsi_bigger.png';
            }

            return [
                'serie' => $request->serie,
                'base_color' => $request->base_color,
                'url_logo' => $filename,
            ];
        }
}
