<?php
namespace App\Controllers;

class RucController extends BaseController
{
    public function lookup(): void
    {
        $ruc = preg_replace('/[^0-9]/', '', $this->getRouteParam('ruc'));
        if (strlen($ruc) !== 11) {
            $this->json(['success'=> false, 'message'=> 'El RUC debe tener 11 dígitos'], 422);
            return;
        }

        $token = trim(file_get_contents(dirname(__DIR__) . '/../.env'));
        preg_match('/TOKEN_APIPERUDEV=(.+)/', $token, $m);
        $token = trim($m[1] ?? '');
        if (empty($token)) {
            $this->json(['success'=> false, 'message'=> 'Token no configurado'], 500);
            return;
        }

        $ch = curl_init('https://apiperu.dev/api/ruc');
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode(['ruc' => $ruc]),
            CURLOPT_HTTPHEADER => [
                'Accept: application/json',
                'Content-Type: application/json',
                'Authorization: Bearer ' . $token,
            ],
            CURLOPT_TIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
        $res = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $err = curl_error($ch);
        curl_close($ch);

        if ($err) {
            $this->json(['success'=> false, 'message'=> 'Error de conexión: '.$err], 502);
            return;
        }
        $data = json_decode($res, true);
        if ($code !== 200 || !($data['success'] ?? false)) {
            $this->json(['success'=> false, 'message'=> $data['message'] ?? 'RUC no encontrado'], 404);
            return;
        }
        $info = $data['data'] ?? [];
        $this->json(['success'=> true, 'data'=> [
            'ruc' => $info['ruc'] ?? $ruc,
            'business_name' => $info['nombre_o_razon_social'] ?? '',
            'address' => $info['direccion'] ?? $info['direccion_completa'] ?? '',
        ]]);
    }

    public function representatives(): void
    {
        $ruc = preg_replace('/[^0-9]/', '', $this->getRouteParam('ruc'));
        if (strlen($ruc) !== 11) {
            $this->json(['success'=> false, 'message'=> 'El RUC debe tener 11 dígitos'], 422);
            return;
        }

        $token = $this->getToken();
        if (empty($token)) {
            $this->json(['success'=> false, 'message'=> 'Token no configurado'], 500);
            return;
        }

        $ch = curl_init('https://apiperu.dev/api/ruc-representantes');
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode(['ruc' => $ruc]),
            CURLOPT_HTTPHEADER => [
                'Accept: application/json',
                'Content-Type: application/json',
                'Authorization: Bearer ' . $token,
            ],
            CURLOPT_TIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
        $res = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $err = curl_error($ch);
        curl_close($ch);

        if ($err) {
            $this->json(['success'=> false, 'message'=> 'Error de conexión: '.$err], 502);
            return;
        }
        $data = json_decode($res, true);
        if ($code !== 200 || !($data['success'] ?? false)) {
            $this->json(['success'=> false, 'message'=> $data['message'] ?? 'No se encontraron representantes'], 404);
            return;
        }
        $this->json(['success'=> true, 'data'=> $data['data'] ?? []]);
    }

    private function getToken(): string
    {
        $content = trim(file_get_contents(dirname(__DIR__) . '/../.env'));
        preg_match('/TOKEN_APIPERUDEV=(.+)/', $content, $m);
        return trim($m[1] ?? '');
    }

    private function json(array $data, int $status = 200): void
    {
        http_response_code($status);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
    }
}
