<?php

namespace App\Controllers;

use App\Models\AuditLogModel;
use App\Models\SignatureModel;
use CodeIgniter\HTTP\ResponseInterface;

class SignatureController extends BaseController
{
    public function upload(): ResponseInterface
    {
        $type = $this->request->getPost('signable_type');
        $id = (int) $this->request->getPost('signable_id');
        $role = $this->request->getPost('role');
        $name = trim((string) $this->request->getPost('name')) ?: null;
        $dataUrl = (string) $this->request->getPost('image');

        if (
            ! in_array($type, ['inspection', 'report', 'delivery_note'], true)
            || $id === 0
            || ! preg_match('/^[a-z0-9_:-]{1,80}$/i', (string) $role)
        ) {
            return $this->response->setStatusCode(400)->setJSON(['ok' => false, 'msg' => 'Parámetros inválidos.']);
        }

        if (! preg_match('#^data:image/png;base64,(?<b64>.+)$#', $dataUrl, $m)) {
            return $this->response->setStatusCode(400)->setJSON(['ok' => false, 'msg' => 'Imagen inválida.']);
        }

        $bin = base64_decode($m['b64'], true);
        if ($bin === false || strlen($bin) > 2_000_000) {
            return $this->response->setStatusCode(400)->setJSON(['ok' => false, 'msg' => 'Imagen inválida o muy grande.']);
        }

        $dir = WRITEPATH . 'uploads/signatures';
        if (! is_dir($dir)) {
            mkdir($dir, 0775, true);
        }
        $filename = sprintf('%s_%d_%s_%s.png', $type, $id, $role, bin2hex(random_bytes(4)));
        file_put_contents($dir . '/' . $filename, $bin);

        $relPath = 'uploads/signatures/' . $filename;
        $sigId = (new SignatureModel())->insert([
            'signable_type' => $type,
            'signable_id' => $id,
            'role' => $role,
            'name' => $name,
            'png_path' => $relPath,
            'signed_at' => date('Y-m-d H:i:s'),
        ], true);

        (new AuditLogModel())->record($type, $id, 'sign_' . $role, ['signature_id' => $sigId]);

        return $this->response->setJSON([
            'ok' => true,
            'id' => $sigId,
            'path' => $relPath,
            'csrf_token' => csrf_hash(),
        ]);
    }
}
