<?php
namespace App\Http\Controllers\Invoicing;

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

use App\Helpers\Environment\FacturapiHelper;
use App\Helpers\Environment\SystemModulesHelper;


use App\Models\Environment\Business;

class SignedManifestController extends Controller
{
    //* Constructor
    public function __construct() {
        $this->middleware('auth');
    }

    //* Special Fucntions
    public function checkManifestStatus() {
      //* Validations
        if (!FacturapiHelper::isEnabled())
            return response()->json(['redirect' => null]); // Avoid execution on Disabled Module or Disabled notification feature

        $user = Auth::user(); // Logged In User
            if (!$user || $user->role !== 'administrador')
                return response()->json(['redirect' => null]);

      //* Get Record
        $business = Business::select(['signed_manifest', 'date_signature_manifest'])->first();
        $is_establishment_data_complete = SystemModulesHelper::isEstablishmentTaxDataComplete();

        $has_pending_signature =  $is_establishment_data_complete && (!$business->signed_manifest || is_null($business->date_signature_manifest));
        $redirect_route = $has_pending_signature ? route('signed-manifest.index') : null;

        return response()->json(['is_signed' => !$has_pending_signature, 'redirect' => $redirect_route]);
    }

    public function signedManifest() {
      //* Validations
        $is_establishment_data_complete = SystemModulesHelper::isEstablishmentTaxDataComplete();
        $user = Auth::user(); // Logged In User

        if (
            !FacturapiHelper::isEnabled()
            || !$is_establishment_data_complete
            || !$user || $user->role !== 'administrador'
        )
            return redirect()->route('home.index');

      //* Get Record
        $business = Business::select(['signed_manifest', 'date_signature_manifest'])->first();

        if ($business->signed_manifest || !is_null($business->date_signature_manifest))
            return redirect()->route('home.index');

        return view('invoicing.signed-manifest.iframe');
    }

    public function confirmManifest() {
      // Get data top update
        $business = Business::first();

        // Ensure record
        if (!$business) {
            return response()->json([
                'success' => false, 'message' => 'No se encontró la Configuración de la Empresa',
            ], 404);
        }

      // Update Data
        $business->update([
            'signed_manifest'         => true,
            'date_signature_manifest' => now(),
        ]);

      // Return response
        return response()->json([
            'success' => true,
            'message' => '¡Firma confirmada con éxito!',
        ]);
    }
}
