<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\DB;
use App\Config\Config;
use App\Services\CryptoService;

class TenantController extends Controller
{
    public function form(): void
    {
        $tenantId = $_SESSION['tenant_id'] ?? null;
        if (!$tenantId) {
            header('Location: /login');
            return;
        }
        $plans = DB::pdo()->query("SELECT * FROM plans")->fetchAll();
        $stmt = DB::pdo()->prepare("SELECT plan_id, uf, cert_path, ambiente FROM tenants WHERE id = ?");
        $stmt->execute([$tenantId]);
        $tenant = $stmt->fetch() ?: ['plan_id' => null, 'uf' => '', 'cert_path' => '', 'ambiente' => 'homologacao'];
        $hasCert = !empty($tenant['cert_path']) && file_exists($tenant['cert_path']);
        $uploadError = '';
        if (!empty($_GET['upload']) && $_GET['upload'] === 'fail') {
            $uploadError = 'Falha ao enviar o certificado. Verifique o arquivo .pfx e o limite de tamanho de upload do PHP.';
        }
        $this->view('tenant/form', [
            'plans' => $plans,
            'tenant' => $tenant,
            'hasCert' => $hasCert,
            'uploadError' => $uploadError,
        ]);
    }

    public function save(): void
    {
        $tenantId = $_SESSION['tenant_id'] ?? null;
        if (!$tenantId) {
            header('Location: /login');
            return;
        }
        $current = DB::pdo()->prepare("SELECT cert_path FROM tenants WHERE id = ?");
        $current->execute([$tenantId]);
        $rowCurrent = $current->fetch();
        $existingCertPath = $rowCurrent['cert_path'] ?? '';
        $planId = (int)($_POST['plan_id'] ?? 0);
        $uf = strtoupper($_POST['uf'] ?? '');
        $ambiente = $_POST['ambiente'] ?? 'homologacao';
        $certPassword = $_POST['cert_password'] ?? '';
        $certPath = $existingCertPath;
        $uploadFailed = false;
        if (!empty($_FILES['cert_file']['name'])) {
            if (!empty($_FILES['cert_file']['error']) && $_FILES['cert_file']['error'] !== UPLOAD_ERR_OK) {
                $uploadFailed = true;
            }
            $storage = Config::get('storage_path') . '/tenants/' . $tenantId;
            if (!is_dir($storage)) {
                @mkdir($storage, 0777, true);
            }
            $target = $storage . '/cert.pfx';
            if (is_uploaded_file($_FILES['cert_file']['tmp_name']) && move_uploaded_file($_FILES['cert_file']['tmp_name'], $target)) {
                $certPath = $target;
            } elseif (!$existingCertPath) {
                $uploadFailed = true;
            }
        }
        $enc = $certPassword !== '' ? CryptoService::encrypt($certPassword) : null;
        $stmt = DB::pdo()->prepare("UPDATE tenants SET plan_id = ?, uf = ?, ambiente = ?, cert_path = ?, cert_password = ?, cert_password_enc = ?, updated_at = ? WHERE id = ?");
        $stmt->execute([$planId, $uf, $ambiente, $certPath, $certPassword, $enc, date('Y-m-d H:i:s'), $tenantId]);
        if (!$certPath && $uploadFailed) {
            header('Location: /tenant?upload=fail');
            return;
        }
        if ($certPath) {
            header('Location: /sefaz/consultar');
        } else {
            header('Location: /dashboard');
        }
    }

    public function checkCert(): void
    {
        $tenantId = $_SESSION['tenant_id'] ?? null;
        if (!$tenantId) {
            header('Location: /login');
            return;
        }
        $stmt = DB::pdo()->prepare("SELECT name, cnpj, uf, ambiente, cert_path, cert_password, cert_password_enc FROM tenants WHERE id = ?");
        $stmt->execute([$tenantId]);
        $t = $stmt->fetch() ?: [];
        $path = (string)($t['cert_path'] ?? '');
        $exists = $path !== '' && is_file($path);
        $senhaPlain = (string)($t['cert_password'] ?? '');
        $senhaDec = $senhaPlain;
        if ($senhaDec === '' && !empty($t['cert_password_enc'])) {
            try {
                $senhaDec = \App\Services\CryptoService::decrypt((string)$t['cert_password_enc']);
            } catch (\Throwable $e) {
            }
        }
        $canRead = false;
        $errMsg = '';
        $hasNfephp = class_exists('\\NFePHP\\Common\\Certificate');
        if ($exists && $senhaDec !== '' && $hasNfephp) {
            try {
                $pfxContent = file_get_contents($path);
                \NFePHP\Common\Certificate::readPfx($pfxContent, $senhaDec);
                $canRead = true;
            } catch (\Throwable $e) {
                $canRead = false;
                $errMsg = $e->getMessage();
            }
        } elseif (!$hasNfephp) {
            $errMsg = 'Biblioteca NFePHP não instalada. Execute "composer install" na raiz do projeto.';
        }
        $this->view('tenant/check_cert', [
            'tenant' => $t,
            'path' => $path,
            'exists' => $exists,
            'senhaInformada' => $senhaPlain !== '',
            'senhaDec' => $senhaDec !== '',
            'canRead' => $canRead,
            'errMsg' => $errMsg,
            'isPfx' => (strtolower(pathinfo($path, PATHINFO_EXTENSION)) === 'pfx'),
            'expectedPath' => \App\Config\Config::get('storage_path') . '/tenants/' . $tenantId . '/cert.pfx',
        ]);
    }
}
