<?php
namespace Modules\Estoque\Controllers;

use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Http\Response;
use Gestoreasy\Core\Tenant\ConnectionManager;
use Gestoreasy\Core\View\View;
use Gestoreasy\Core\Audit\AuditLogger;
use Gestoreasy\Core\Auth\UserContext;

class InventorySettingsController {
    private function getSettingsRow(\PDO $pdo): array {
        $stmt = $pdo->query('SELECT id, permitir_estoque_negativo, updated_at, updated_by FROM inventory_settings ORDER BY id ASC LIMIT 1');
        $row = $stmt->fetch() ?: [];
        if (!$row) { $row = ['id' => null, 'permitir_estoque_negativo' => 0, 'updated_at' => null, 'updated_by' => null]; }
        return $row;
    }

    public function viewSettings(Request $r): Response {
        $pdo = ConnectionManager::forTenant();
        $row = $this->getSettingsRow($pdo);
        return View::renderWithLayout('estoque/settings', [
            'title' => 'Configurações de Estoque',
            'permitir_estoque_negativo' => (int)($row['permitir_estoque_negativo'] ?? 0) === 1,
            'updated_at' => $row['updated_at'] ?? null,
        ]);
    }

    public function getSettings(Request $r): Response {
        $pdo = ConnectionManager::forTenant();
        $row = $this->getSettingsRow($pdo);
        return Response::json(['data' => [
            'permitir_estoque_negativo' => (int)($row['permitir_estoque_negativo'] ?? 0) === 1,
            'updated_at' => $row['updated_at'] ?? null,
            'updated_by' => $row['updated_by'] ?? null,
        ]]);
    }

    public function updateSettings(Request $r): Response {
        $pdo = ConnectionManager::forTenant();
        $user = UserContext::get($r) ?? [];
        $uid = (int)($user['sub'] ?? 0) ?: null;
        $val = $r->body['permitir_estoque_negativo'] ?? null;
        $enable = null;
        if (is_bool($val)) $enable = $val ? 1 : 0; elseif (is_numeric($val)) $enable = ((int)$val) ? 1 : 0; elseif (is_string($val)) {
            $v = strtolower(trim($val));
            $enable = in_array($v, ['1','true','on','yes','sim'], true) ? 1 : 0;
        }
        if ($enable === null) {
            return new Response(422, ['error' => ['code' => 'invalid_config', 'message' => 'Valor inválido para permitir_estoque_negativo']]);
        }
        try {
            $pdo->beginTransaction();
            $cur = $this->getSettingsRow($pdo);
            if (!isset($cur['id']) || !$cur['id']) {
                $ins = $pdo->prepare('INSERT INTO inventory_settings (permitir_estoque_negativo, updated_at, updated_by) VALUES (?,?,?)');
                $ins->execute([$enable, date('Y-m-d H:i:s'), $uid]);
                $sid = (int)$pdo->lastInsertId();
            } else {
                $sid = (int)$cur['id'];
                $upd = $pdo->prepare('UPDATE inventory_settings SET permitir_estoque_negativo = ?, updated_at = NOW(), updated_by = ? WHERE id = ?');
                $upd->execute([$enable, $uid, $sid]);
            }
            // Histórico
            $hist = $pdo->prepare('INSERT INTO inventory_settings_history (setting_id, changed_by, old_permitir, new_permitir) VALUES (?,?,?,?)');
            $hist->execute([$sid, $uid, (int)($cur['permitir_estoque_negativo'] ?? 0), (int)$enable]);
            $pdo->commit();
            AuditLogger::logUpdate('inventory_settings', $sid, $cur ?: [], ['permitir_estoque_negativo' => (int)$enable], ['endpoint' => 'estoque.settings.update', 'user_id' => $uid]);
            return Response::json(['ok' => true, 'data' => ['permitir_estoque_negativo' => (int)$enable]], 200);
        } catch (\Throwable $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            return new Response(500, ['error' => ['code' => 'update_failed', 'message' => $e->getMessage()]]);
        }
    }
}