<?php
require_once __DIR__ . '/src/auth.php';
require_once __DIR__ . '/src/db.php';
require_login();

$isAdmin = ($_SESSION['role'] ?? '') === 'admin';
$messages = [];
$success = false;

if ($isAdmin && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $pdo = get_db_connection();
    $sqlFile = __DIR__ . '/db/update_v12_email_contracts.sql';

    if (!file_exists($sqlFile)) {
        $messages[] = 'Arquivo SQL do modulo nao encontrado.';
    } else {
        $sql = file_get_contents($sqlFile);
        $lines = preg_split("/\r\n|\n|\r/", (string)$sql);
        $buffer = '';
        $statements = [];

        foreach ($lines as $line) {
            $trimmed = trim($line);
            if ($trimmed === '' || strpos($trimmed, '--') === 0) {
                continue;
            }

            $buffer .= $line . "\n";
            if (substr(rtrim($line), -1) === ';') {
                $statements[] = trim($buffer);
                $buffer = '';
            }
        }

        if (trim($buffer) !== '') {
            $statements[] = trim($buffer);
        }

        try {
            $pdo->beginTransaction();
            foreach ($statements as $statement) {
                $statement = trim($statement);
                if ($statement !== '') {
                    $pdo->exec($statement);
                }
            }
            $pdo->commit();
            $success = true;
            $messages[] = 'Modulo de contratos por e-mail instalado com sucesso.';
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $messages[] = 'Erro ao instalar o modulo: ' . $e->getMessage();
        }
    }
}

require_once __DIR__ . '/templates/header.php';
?>

<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="mb-1">Instalar Modulo de Contratos por E-mail</h2>
            <p class="text-muted mb-0">Cria as tabelas e configuracoes iniciais do novo modulo administrativo.</p>
        </div>
        <a href="email_contracts.php" class="btn btn-outline-primary">
            <i class="fas fa-arrow-left me-1"></i> Voltar ao Modulo
        </a>
    </div>

    <?php if (!$isAdmin): ?>
        <div class="alert alert-danger">Apenas administradores podem executar esta instalacao.</div>
    <?php endif; ?>

    <?php foreach ($messages as $message): ?>
        <div class="alert <?= $success ? 'alert-success' : 'alert-warning' ?>">
            <?= htmlspecialchars($message) ?>
        </div>
    <?php endforeach; ?>

    <div class="card">
        <div class="card-body">
            <h5 class="card-title">O que sera criado</h5>
            <ul class="mb-4">
                <li>`email_contracts` para controle principal do contrato por e-mail</li>
                <li>`email_contract_messages` para entrada e saida da caixa postal</li>
                <li>`email_contract_attachments` para anexos PDF, DOCX e imagens</li>
                <li>`email_contract_history` para timeline e auditoria</li>
                <li>`email_contract_notifications` para alertas</li>
                <li>`email_contract_user_access` para niveis e permissoes do modulo</li>
            </ul>

            <form method="post">
                <button type="submit" class="btn btn-primary" <?= $isAdmin ? '' : 'disabled' ?>>
                    <i class="fas fa-database me-1"></i> Executar Instalacao
                </button>
            </form>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/templates/footer.php'; ?>
