<?php

namespace App\Http\Controllers\Client;

use App\Models\Company;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Resources\Client\CompanyResource;
use Illuminate\Support\Facades\Storage;
use Greenter\See;
use Greenter\Ws\Services\SunatEndpoints;

class CompanyController extends Controller
{
    public function index(){
        $company = Company::first();
        return response()->json([
            "company" => $company ? CompanyResource::make($company) : null,
        ]);
    }

    public function store(Request $request){
        $company = Company::first();
        $newEnv = $request->input('app_env');
        
        if ($newEnv === 'production') {
            $ruc = $request->input('n_document');
            $userSol = $request->input('user_sol');
            $userPass = $request->input('user_pass');
            
            if (!$ruc || !$userSol || !$userPass) {
                return response()->json(["code" => 422, "message" => "Faltan credenciales para producción"], 422);
            }
            
            $certificateProvided = $request->hasFile('certificate');
            $hasStoredCertificate = $company && $company->certificate_path;
            if (!$certificateProvided && !$hasStoredCertificate) {
                return response()->json(["code" => 422, "message" => "Certificado requerido para producción"], 422);
            }

            // Determinar certificado a usar (archivo subido o certificado ya almacenado)
            $certificateSource = $certificateProvided ? $request->file('certificate') : ($company->certificate_path ?? null);

            // Validar credenciales contra SUNAT usando el certificado determinado
            $valid = $this->validateSunatCredentialsWithSoap($ruc, $userSol, $userPass, $certificateSource);
            if (!$valid['ok']) {
                return response()->json(["code" => 422, "message" => "Validación SUNAT falló: " . $valid['message']], 422);
            }
        }
        
        $data = $request->except('logo', 'certificate');
        
        if ($request->hasFile('logo')) {
            if ($company && $company->logo_url) {
                $oldLogoPath = str_replace('/storage/', 'public/', $company->logo_url);
                Storage::delete($oldLogoPath);
            }
            $path = $request->file('logo')->store('logos', 'public');
            $data['logo_url'] = Storage::url($path);
        }
        
        if ($request->hasFile('certificate')) {
            if ($company && $company->certificate_path) {
                Storage::delete($company->certificate_path);
            }
            $certPath = $request->file('certificate')->store('certificates', 'public');
            $data['certificate_path'] = $certPath;
        }
        
        if ($company) {
            $company->update($data);
        } else {
            $company = Company::create($data);
        }

        return response()->json([
            "code" => 200,
            "message" => "Se actualizó la información",
            "company" => CompanyResource::make($company)
        ]);
    }

    /**
     * Valida credenciales en SUNAT realizando una llamada SOAP mínima (getStatus).
     * Devuelve array ['ok' => bool, 'message' => string]
     */
    private function validateSunatCredentialsWithSoap($ruc, $userSol, $userPass, $certificateSource)
    {
        $wsdl = 'https://e-factura.sunat.gob.pe/ol-ti-itcpfegem/billService?wsdl'; // ENDPOINT PRODUCCIÓN
        $tmp = tempnam(sys_get_temp_dir(), 'sunat_cert_');
        try {
            // Guardar contenido del certificado en un archivo temporal
            if ($certificateSource instanceof \Illuminate\Http\UploadedFile) {
                file_put_contents($tmp, $certificateSource->get());
            } elseif (is_string($certificateSource)) {
                $certContent = Storage::get($certificateSource);
                if (!$certContent) {
                    return ['ok' => false, 'message' => 'No se encontró el certificado almacenado.'];
                }
                file_put_contents($tmp, $certContent);
            } else {
                return ['ok' => false, 'message' => 'Certificado no proporcionado.'];
            }

            $context = stream_context_create([
                'ssl' => [
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true,
                    'local_cert' => $tmp,
                ]
            ]);

            $client = new \SoapClient($wsdl, [
                'cache_wsdl' => WSDL_CACHE_NONE,
                'trace' => 1,
                'stream_context' => $context,
                'login' => $userSol,
                'password' => $userPass,
                'exceptions' => true,
            ]);

            // Llamamos 'getStatus' con un ticket inválido para forzar autenticación y obtener posible SoapFault
            try {
                $response = $client->__soapCall('getStatus', [[ 'ticket' => '0' ]]);
                // Si no lanza excepción, asumimos credenciales válidas (SUNAT respondió)
                return ['ok' => true, 'message' => 'Credenciales y certificado válidos.'];
            } catch (\SoapFault $sf) {
                $msg = $sf->getMessage();
                return ['ok' => false, 'message' => $msg];
            }

        } catch (\Exception $e) {
            return ['ok' => false, 'message' => $e->getMessage()];
        } finally {
            if (file_exists($tmp)) @unlink($tmp);
        }
    }
}


