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

// Apenas administradores podem acessar esta página
if ($_SESSION['role'] !== 'admin') {
    die("Acesso negado. Você não tem permissão para acessar esta página.");
}

$pdo = get_db_connection();
$message = '';
$errorMessage = '';

function admin_get_setting(PDO $pdo, string $key, string $default = ''): string {
    try {
        $stmt = $pdo->prepare("SELECT setting_value FROM system_settings WHERE setting_key = ? LIMIT 1");
        $stmt->execute([$key]);
        $value = $stmt->fetchColumn();
        return $value !== false && $value !== null ? (string)$value : $default;
    } catch (Throwable $e) {
        return $default;
    }
}

function admin_setting_defaults(PDO $pdo, array $defaults): void {
    try {
        $stmt = $pdo->prepare("INSERT IGNORE INTO system_settings (setting_key, setting_value) VALUES (?, ?)");
        foreach ($defaults as $k => $v) {
            $stmt->execute([(string)$k, (string)$v]);
        }
    } catch (Throwable $e) {
        return;
    }
}

admin_setting_defaults($pdo, [
    'email_imap_host' => '',
    'email_imap_port' => '993',
    'email_imap_encryption' => 'ssl',
    'email_imap_folder' => 'INBOX',
    'email_imap_username' => '',
    'email_imap_password' => '',
    'email_smtp_host' => '',
    'email_smtp_port' => '587',
    'email_smtp_encryption' => 'tls',
    'email_smtp_username' => '',
    'email_smtp_password' => '',
    'email_from_name' => 'Central de Contratos',
    'email_from_address' => '',
    'email_notifications_enabled' => '1',
]);

function admin_imap_connect(array $config, string &$error): mixed {
    $error = '';
    if (!function_exists('imap_open')) {
        $error = 'Extensão IMAP do PHP não está habilitada. Ative no php.ini (extension=imap) e reinicie o Apache.';
        return false;
    }

    $host = trim((string)($config['host'] ?? ''));
    $folder = trim((string)($config['folder'] ?? 'INBOX'));
    $user = (string)($config['user'] ?? '');
    $pass = (string)($config['pass'] ?? '');
    $port = (int)($config['port'] ?? 993);
    $enc = strtolower(trim((string)($config['enc'] ?? 'ssl')));
    if ($host === '' || $user === '' || $pass === '') {
        $error = 'Preencha Host, Usuário e Senha do IMAP.';
        return false;
    }
    if ($port < 1 || $port > 65535) {
        $error = 'Porta IMAP inválida.';
        return false;
    }
    if (!in_array($enc, ['ssl', 'tls', 'none'], true)) {
        $enc = 'ssl';
    }

    $encPart = $enc === 'none' ? 'notls' : $enc;
    $mailbox = '{' . $host . ':' . $port . '/imap/' . $encPart . '/novalidate-cert}' . ($folder !== '' ? $folder : 'INBOX');
    $stream = @imap_open($mailbox, $user, $pass);
    if (!$stream) {
        $last = imap_last_error();
        $error = $last ? (string)$last : 'Falha ao conectar no IMAP.';
        return false;
    }
    return $stream;
}

function admin_smtp_send(array $config, string $to, string $subject, string $body, string &$log): bool {
    $log = '';
    $host = trim((string)($config['host'] ?? ''));
    $user = trim((string)($config['user'] ?? ''));
    $pass = (string)($config['pass'] ?? '');
    $port = (int)($config['port'] ?? 587);
    $enc = strtolower(trim((string)($config['enc'] ?? 'tls')));
    $fromAddr = trim((string)($config['from_addr'] ?? ''));
    $fromName = trim((string)($config['from_name'] ?? ''));

    if ($host === '') {
        $log = "SMTP: host não configurado.";
        return false;
    }
    if ($port < 1 || $port > 65535) {
        $log = "SMTP: porta inválida.";
        return false;
    }
    if (!in_array($enc, ['tls', 'ssl', 'none'], true)) {
        $enc = 'tls';
    }
    if ($fromAddr === '') {
        $fromAddr = $user;
    }
    if ($fromAddr === '' || !filter_var($fromAddr, FILTER_VALIDATE_EMAIL)) {
        $log = "SMTP: e-mail do remetente inválido.";
        return false;
    }
    if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
        $log = "SMTP: e-mail de destino inválido.";
        return false;
    }

    $socketHost = $enc === 'ssl' ? 'ssl://' . $host : $host;
    $fp = @fsockopen($socketHost, $port, $errno, $errstr, 15);
    if (!$fp) {
        $log = "Falha ao conectar no SMTP: $errstr ($errno)";
        return false;
    }
    stream_set_timeout($fp, 15);

    $read = static function() use ($fp): string {
        $data = '';
        while (!feof($fp)) {
            $line = fgets($fp, 515);
            if ($line === false) {
                break;
            }
            $data .= $line;
            if (strlen($line) >= 4 && $line[3] === ' ') {
                break;
            }
        }
        return $data;
    };
    $write = static function(string $cmd) use ($fp): void {
        fwrite($fp, $cmd . "\r\n");
    };

    $logLines = [];
    $logLines[] = trim($read());
    $write('EHLO localhost');
    $ehlo = $read();
    $logLines[] = trim($ehlo);

    if ($enc === 'tls') {
        if (stripos($ehlo, 'STARTTLS') !== false) {
            $write('STARTTLS');
            $logLines[] = trim($read());
            $cryptoOk = @stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
            if ($cryptoOk !== true) {
                fclose($fp);
                $log = implode("\n", $logLines) . "\nFalha ao ativar TLS no SMTP.";
                return false;
            }
            $write('EHLO localhost');
            $logLines[] = trim($read());
        } else {
            $logLines[] = 'Servidor SMTP não anunciou STARTTLS.';
        }
    }

    if ($user !== '') {
        $write('AUTH LOGIN');
        $logLines[] = trim($read());
        $write(base64_encode($user));
        $logLines[] = trim($read());
        $write(base64_encode($pass));
        $authResp = $read();
        $logLines[] = trim($authResp);
        if (strpos($authResp, '235') !== 0) {
            fclose($fp);
            $log = implode("\n", $logLines) . "\nFalha na autenticação SMTP.";
            return false;
        }
    }

    $write('MAIL FROM:<' . $fromAddr . '>');
    $logLines[] = trim($read());
    $write('RCPT TO:<' . $to . '>');
    $logLines[] = trim($read());
    $write('DATA');
    $logLines[] = trim($read());

    $headers = [];
    $headers[] = 'From: ' . ($fromName !== '' ? $fromName . ' ' : '') . '<' . $fromAddr . '>';
    $headers[] = 'To: <' . $to . '>';
    $headers[] = 'Subject: ' . $subject;
    $headers[] = 'MIME-Version: 1.0';
    $headers[] = 'Content-Type: text/plain; charset=UTF-8';
    $headers[] = 'Content-Transfer-Encoding: 8bit';
    $headers[] = 'Date: ' . date('r');
    $headers[] = 'Message-ID: <' . bin2hex(random_bytes(8)) . '.' . time() . '@' . preg_replace('/^www\./', '', (string)($_SERVER['HTTP_HOST'] ?? 'localhost')) . '>';

    $dataLines = preg_split("/\r\n|\n|\r/", $body);
    $safeBody = [];
    foreach ($dataLines as $l) {
        $safeBody[] = (isset($l[0]) && $l[0] === '.') ? '.' . $l : $l;
    }
    $payload = implode("\r\n", $headers) . "\r\n\r\n" . implode("\r\n", $safeBody) . "\r\n.\r\n";
    fwrite($fp, $payload);
    $logLines[] = trim($read());
    $write('QUIT');
    $logLines[] = trim($read());
    fclose($fp);

    $log = implode("\n", array_filter($logLines, static fn($l) => $l !== ''));
    return true;
}

// Handle Role Update
if (isset($_POST['action']) && $_POST['action'] === 'update_role') {
    $user_id = $_POST['user_id'];
    $new_role = $_POST['role'];
    
    $stmt = $pdo->prepare("UPDATE users SET role = ? WHERE id = ?");
    if ($stmt->execute([$new_role, $user_id])) {
        $message = "Papel do usuário atualizado com sucesso!";
    }
}

// Handle Settings Update
if (isset($_POST['action']) && $_POST['action'] === 'update_settings') {
    foreach ($_POST['settings'] as $key => $value) {
        $stmt = $pdo->prepare("
            INSERT INTO system_settings (setting_key, setting_value)
            VALUES (?, ?)
            ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)
        ");
        $stmt->execute([$key, $value]);
    }
    $message = "Configurações atualizadas com sucesso!";
}

if (isset($_POST['action']) && $_POST['action'] === 'update_email_settings') {
    $data = $_POST['email_settings'] ?? [];
    $values = [];

    $values['email_imap_host'] = substr(trim((string)($data['email_imap_host'] ?? '')), 0, 255);
    $values['email_imap_folder'] = substr(trim((string)($data['email_imap_folder'] ?? 'INBOX')), 0, 120);
    $values['email_imap_username'] = substr(trim((string)($data['email_imap_username'] ?? '')), 0, 255);

    $imapEnc = strtolower(trim((string)($data['email_imap_encryption'] ?? 'ssl')));
    $values['email_imap_encryption'] = in_array($imapEnc, ['ssl', 'tls', 'none'], true) ? $imapEnc : 'ssl';

    $imapPort = (int)($data['email_imap_port'] ?? 993);
    if ($imapPort < 1 || $imapPort > 65535) {
        $errorMessage = 'Porta IMAP inválida.';
    } else {
        $values['email_imap_port'] = (string)$imapPort;
    }

    $values['email_smtp_host'] = substr(trim((string)($data['email_smtp_host'] ?? '')), 0, 255);
    $values['email_smtp_username'] = substr(trim((string)($data['email_smtp_username'] ?? '')), 0, 255);

    $smtpEnc = strtolower(trim((string)($data['email_smtp_encryption'] ?? 'tls')));
    $values['email_smtp_encryption'] = in_array($smtpEnc, ['tls', 'ssl', 'none'], true) ? $smtpEnc : 'tls';

    $smtpPort = (int)($data['email_smtp_port'] ?? 587);
    if ($errorMessage === '' && ($smtpPort < 1 || $smtpPort > 65535)) {
        $errorMessage = 'Porta SMTP inválida.';
    } else {
        $values['email_smtp_port'] = (string)$smtpPort;
    }

    $values['email_from_name'] = substr(trim((string)($data['email_from_name'] ?? 'Central de Contratos')), 0, 120);
    $values['email_from_address'] = substr(trim((string)($data['email_from_address'] ?? '')), 0, 255);
    if ($errorMessage === '' && $values['email_from_address'] !== '' && !filter_var($values['email_from_address'], FILTER_VALIDATE_EMAIL)) {
        $errorMessage = 'E-mail do remetente inválido.';
    }

    $values['email_notifications_enabled'] = (($data['email_notifications_enabled'] ?? '') === '1') ? '1' : '0';

    $imapPass = (string)($data['email_imap_password'] ?? '');
    $smtpPass = (string)($data['email_smtp_password'] ?? '');

    try {
        if ($errorMessage === '') {
            $stmt = $pdo->prepare("
                INSERT INTO system_settings (setting_key, setting_value)
                VALUES (?, ?)
                ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)
            ");

            foreach ($values as $k => $v) {
                $stmt->execute([$k, $v]);
            }

            if (trim($imapPass) !== '') {
                $stmt->execute(['email_imap_password', $imapPass]);
            }
            if (trim($smtpPass) !== '') {
                $stmt->execute(['email_smtp_password', $smtpPass]);
            }

            $message = "Configurações de e-mail atualizadas com sucesso!";
        }
    } catch (Throwable $e) {
        $errorMessage = 'Erro ao salvar configurações de e-mail: ' . $e->getMessage();
    }
}

if (isset($_POST['action']) && $_POST['action'] === 'test_imap') {
    $imapConfig = [
        'host' => admin_get_setting($pdo, 'email_imap_host', ''),
        'port' => (int)admin_get_setting($pdo, 'email_imap_port', '993'),
        'enc' => admin_get_setting($pdo, 'email_imap_encryption', 'ssl'),
        'folder' => admin_get_setting($pdo, 'email_imap_folder', 'INBOX'),
        'user' => admin_get_setting($pdo, 'email_imap_username', ''),
        'pass' => admin_get_setting($pdo, 'email_imap_password', ''),
    ];

    $imapErr = '';
    $mbox = admin_imap_connect($imapConfig, $imapErr);
    if (!$mbox) {
        $errorMessage = "Teste IMAP falhou: " . $imapErr;
    } else {
        $total = (int)imap_num_msg($mbox);
        $lines = [];
        $lines[] = "IMAP conectado com sucesso.";
        $lines[] = "Pasta: " . $imapConfig['folder'];
        $lines[] = "Total de mensagens: " . $total;
        $lines[] = "";

        $start = max(1, $total - 4);
        for ($i = $total; $i >= $start; $i--) {
            $ov = @imap_fetch_overview($mbox, (string)$i, 0);
            $ov0 = is_array($ov) && isset($ov[0]) ? $ov[0] : null;
            $sub = $ov0 && isset($ov0->subject) ? imap_utf8((string)$ov0->subject) : '(sem assunto)';
            $from = $ov0 && isset($ov0->from) ? imap_utf8((string)$ov0->from) : '-';
            $date = $ov0 && isset($ov0->date) ? (string)$ov0->date : '';
            $lines[] = "• " . $date . " | " . $from . " | " . $sub;
        }
        imap_close($mbox);
        $message = implode("\n", $lines);
    }
}

if (isset($_POST['action']) && $_POST['action'] === 'test_smtp') {
    $to = trim((string)($_POST['test_to'] ?? ''));
    $smtpConfig = [
        'host' => admin_get_setting($pdo, 'email_smtp_host', ''),
        'port' => (int)admin_get_setting($pdo, 'email_smtp_port', '587'),
        'enc' => admin_get_setting($pdo, 'email_smtp_encryption', 'tls'),
        'user' => admin_get_setting($pdo, 'email_smtp_username', ''),
        'pass' => admin_get_setting($pdo, 'email_smtp_password', ''),
        'from_addr' => admin_get_setting($pdo, 'email_from_address', ''),
        'from_name' => admin_get_setting($pdo, 'email_from_name', 'Central de Contratos'),
    ];

    $id = bin2hex(random_bytes(4));
    $subject = "Teste SMTP - Sistema de Contratos (" . $id . ")";
    $body = "Teste de envio SMTP.\n\nID: " . $id . "\nData/Hora: " . date('d/m/Y H:i:s') . "\n";

    $log = '';
    $ok = admin_smtp_send($smtpConfig, $to, $subject, $body, $log);
    if ($ok) {
        $message = "SMTP: envio concluído.\n\n" . $log . "\n\nAssunto enviado: " . $subject;
    } else {
        $errorMessage = "SMTP: falha no envio.\n\n" . $log . "\n\nAssunto: " . $subject;
    }
}

if (isset($_POST['action']) && $_POST['action'] === 'test_email_full') {
    $to = trim((string)($_POST['test_to'] ?? ''));
    $smtpConfig = [
        'host' => admin_get_setting($pdo, 'email_smtp_host', ''),
        'port' => (int)admin_get_setting($pdo, 'email_smtp_port', '587'),
        'enc' => admin_get_setting($pdo, 'email_smtp_encryption', 'tls'),
        'user' => admin_get_setting($pdo, 'email_smtp_username', ''),
        'pass' => admin_get_setting($pdo, 'email_smtp_password', ''),
        'from_addr' => admin_get_setting($pdo, 'email_from_address', ''),
        'from_name' => admin_get_setting($pdo, 'email_from_name', 'Central de Contratos'),
    ];
    $imapConfig = [
        'host' => admin_get_setting($pdo, 'email_imap_host', ''),
        'port' => (int)admin_get_setting($pdo, 'email_imap_port', '993'),
        'enc' => admin_get_setting($pdo, 'email_imap_encryption', 'ssl'),
        'folder' => admin_get_setting($pdo, 'email_imap_folder', 'INBOX'),
        'user' => admin_get_setting($pdo, 'email_imap_username', ''),
        'pass' => admin_get_setting($pdo, 'email_imap_password', ''),
    ];

    $id = bin2hex(random_bytes(4));
    $subject = "Teste COMPLETO SMTP→IMAP (" . $id . ")";
    $body = "Teste completo: enviar e buscar na entrada.\n\nID: " . $id . "\nData/Hora: " . date('d/m/Y H:i:s') . "\n";

    $smtpLog = '';
    $smtpOk = admin_smtp_send($smtpConfig, $to, $subject, $body, $smtpLog);
    if (!$smtpOk) {
        $errorMessage = "Falha no envio SMTP.\n\n" . $smtpLog . "\n\nAssunto: " . $subject;
    } else {
        $imapErr = '';
        $mbox = admin_imap_connect($imapConfig, $imapErr);
        if (!$mbox) {
            $errorMessage = "Enviado via SMTP, mas IMAP falhou.\n\nSMTP:\n" . $smtpLog . "\n\nIMAP:\n" . $imapErr . "\n\nAssunto: " . $subject;
        } else {
            sleep(5);
            $total = (int)imap_num_msg($mbox);
            $found = false;
            $start = max(1, $total - 24);
            for ($i = $total; $i >= $start; $i--) {
                $ov = @imap_fetch_overview($mbox, (string)$i, 0);
                $ov0 = is_array($ov) && isset($ov[0]) ? $ov[0] : null;
                $sub = $ov0 && isset($ov0->subject) ? imap_utf8((string)$ov0->subject) : '';
                if ($sub !== '' && strpos($sub, $id) !== false) {
                    $found = true;
                    break;
                }
            }
            imap_close($mbox);

            if ($found) {
                $message = "Teste completo OK: e-mail enviado e encontrado na entrada.\n\nSMTP:\n" . $smtpLog . "\n\nAssunto: " . $subject;
            } else {
                $errorMessage = "Enviado via SMTP, mas não encontrei na entrada (ainda).\n\nSMTP:\n" . $smtpLog . "\n\nAssunto: " . $subject . "\n\nDica: pode levar alguns segundos/minutos dependendo do provedor.";
            }
        }
    }
}

// Handle Delete User
if (isset($_GET['delete'])) {
    $user_id = $_GET['delete'];
    // Evitar que o admin se delete
    if ($user_id != $_SESSION['user_id']) {
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        header("Location: admin.php");
        exit;
    } else {
        $message = "Você não pode excluir seu próprio usuário.";
    }
}

// Handle Backup
if (isset($_GET['backup'])) {
    $backup_file = 'backup_' . DB_NAME . '_' . date('Y-m-d_H-i-s') . '.sql';
    $backup_path = __DIR__ . '/backups/' . $backup_file;
    
    if (!is_dir(__DIR__ . '/backups/')) {
        mkdir(__DIR__ . '/backups/', 0777, true);
    }

    // Comando para mysqldump (assumindo que está no PATH, comum em XAMPP)
    // No Windows/XAMPP, o mysqldump costuma estar em C:\xampp\mysql\bin\mysqldump
    $mysqldump_path = 'mysqldump'; // Tentar comando direto primeiro
    
    $command = sprintf(
        '%s --user=%s --password=%s --host=%s %s > %s',
        $mysqldump_path,
        DB_USER,
        DB_PASS ? escapeshellarg(DB_PASS) : "''",
        DB_HOST,
        DB_NAME,
        escapeshellarg($backup_path)
    );

    exec($command, $output, $return_var);

    if ($return_var === 0) {
        // Oferecer download
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename=' . basename($backup_path));
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($backup_path));
        readfile($backup_path);
        exit;
    } else {
        $message = "Erro ao realizar backup. Certifique-se de que o mysqldump está configurado.";
    }
}

$users = $pdo->query("SELECT * FROM users ORDER BY username ASC")->fetchAll();

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

<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Painel Administrativo</h2>
        <a href="admin.php?backup=1" class="btn btn-success"><i class="fas fa-database me-2"></i> Realizar Backup do Banco</a>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-info"><?= nl2br(htmlspecialchars($message)) ?></div>
    <?php endif; ?>

    <?php if ($errorMessage): ?>
        <div class="alert alert-danger"><?= nl2br(htmlspecialchars($errorMessage)) ?></div>
    <?php endif; ?>

    <?php if (isset($_GET['message'])): ?>
        <div class="alert alert-success"><?= nl2br(htmlspecialchars($_GET['message'])) ?></div>
    <?php endif; ?>

    <?php if (isset($_GET['error'])): ?>
        <div class="alert alert-danger"><?= nl2br(htmlspecialchars($_GET['error'])) ?></div>
    <?php endif; ?>

    <div class="row">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Gerenciar Usuários (Sincronizados via Nextcloud)</div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Usuário</th>
                                    <th>Papel (Role)</th>
                                    <th>Data Cadastro</th>
                                    <th>Ações</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($users as $u): ?>
                                <tr>
                                    <td><?= htmlspecialchars($u['username']) ?></td>
                                    <td>
                                        <form method="POST" class="d-flex gap-2">
                                            <input type="hidden" name="action" value="update_role">
                                            <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                                            <select name="role" class="form-select form-select-sm" onchange="this.form.submit()">
                                                <option value="user" <?= $u['role'] === 'user' ? 'selected' : '' ?>>Usuário</option>
                                                <option value="admin" <?= $u['role'] === 'admin' ? 'selected' : '' ?>>Administrador</option>
                                            </select>
                                        </form>
                                    </td>
                                    <td><?= date('d/m/Y H:i', strtotime($u['created_at'])) ?></td>
                                    <td>
                                        <?php if ($u['id'] != $_SESSION['user_id']): ?>
                                            <a href="admin.php?delete=<?= $u['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Excluir este usuário do sistema? (Não afeta o Nextcloud)')"><i class="fas fa-trash"></i></a>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-4">
            <div class="card mb-4">
                <div class="card-header">Configurar E-mail (IMAP/SMTP)</div>
                <div class="card-body">
                    <?php
                        $email_imap_host = admin_get_setting($pdo, 'email_imap_host', '');
                        $email_imap_port = admin_get_setting($pdo, 'email_imap_port', '993');
                        $email_imap_encryption = admin_get_setting($pdo, 'email_imap_encryption', 'ssl');
                        $email_imap_folder = admin_get_setting($pdo, 'email_imap_folder', 'INBOX');
                        $email_imap_username = admin_get_setting($pdo, 'email_imap_username', '');
                        $email_imap_password = admin_get_setting($pdo, 'email_imap_password', '');

                        $email_smtp_host = admin_get_setting($pdo, 'email_smtp_host', '');
                        $email_smtp_port = admin_get_setting($pdo, 'email_smtp_port', '587');
                        $email_smtp_encryption = admin_get_setting($pdo, 'email_smtp_encryption', 'tls');
                        $email_smtp_username = admin_get_setting($pdo, 'email_smtp_username', '');
                        $email_smtp_password = admin_get_setting($pdo, 'email_smtp_password', '');

                        $email_from_name = admin_get_setting($pdo, 'email_from_name', 'Central de Contratos');
                        $email_from_address = admin_get_setting($pdo, 'email_from_address', '');
                        $email_notifications_enabled = admin_get_setting($pdo, 'email_notifications_enabled', '1') === '1';
                    ?>

                    <form method="POST" autocomplete="off">
                        <input type="hidden" name="action" value="update_email_settings">

                        <ul class="nav nav-pills mb-3" id="adminEmailTabs" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="admin-imap-tab" data-bs-toggle="tab" data-bs-target="#admin-imap" type="button" role="tab" aria-controls="admin-imap" aria-selected="true">
                                    IMAP
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="admin-smtp-tab" data-bs-toggle="tab" data-bs-target="#admin-smtp" type="button" role="tab" aria-controls="admin-smtp" aria-selected="false">
                                    SMTP
                                </button>
                            </li>
                        </ul>

                        <div class="tab-content">
                            <div class="tab-pane fade show active" id="admin-imap" role="tabpanel" aria-labelledby="admin-imap-tab">
                                <div class="mb-3">
                                    <label class="form-label">Host IMAP</label>
                                    <input type="text" name="email_settings[email_imap_host]" class="form-control" value="<?= htmlspecialchars($email_imap_host) ?>" placeholder="imap.seudominio.com">
                                </div>
                                <div class="row g-2">
                                    <div class="col-6">
                                        <label class="form-label">Porta</label>
                                        <input type="number" name="email_settings[email_imap_port]" class="form-control" value="<?= htmlspecialchars($email_imap_port) ?>" min="1" max="65535">
                                    </div>
                                    <div class="col-6">
                                        <label class="form-label">Criptografia</label>
                                        <select name="email_settings[email_imap_encryption]" class="form-select">
                                            <option value="ssl" <?= $email_imap_encryption === 'ssl' ? 'selected' : '' ?>>SSL</option>
                                            <option value="tls" <?= $email_imap_encryption === 'tls' ? 'selected' : '' ?>>TLS</option>
                                            <option value="none" <?= $email_imap_encryption === 'none' ? 'selected' : '' ?>>Sem</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="mt-3 mb-3">
                                    <label class="form-label">Pasta</label>
                                    <input type="text" name="email_settings[email_imap_folder]" class="form-control" value="<?= htmlspecialchars($email_imap_folder) ?>" placeholder="INBOX">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Usuário</label>
                                    <input type="text" name="email_settings[email_imap_username]" class="form-control" value="<?= htmlspecialchars($email_imap_username) ?>" placeholder="email@seudominio.com">
                                </div>
                                <div class="mb-0">
                                    <label class="form-label">Senha (opcional)</label>
                                    <input type="password" name="email_settings[email_imap_password]" class="form-control" value="" placeholder="<?= $email_imap_password !== '' ? 'Deixe em branco para manter' : '' ?>">
                                </div>
                            </div>

                            <div class="tab-pane fade" id="admin-smtp" role="tabpanel" aria-labelledby="admin-smtp-tab">
                                <div class="mb-3">
                                    <label class="form-label">Host SMTP</label>
                                    <input type="text" name="email_settings[email_smtp_host]" class="form-control" value="<?= htmlspecialchars($email_smtp_host) ?>" placeholder="smtp.seudominio.com">
                                </div>
                                <div class="row g-2">
                                    <div class="col-6">
                                        <label class="form-label">Porta</label>
                                        <input type="number" name="email_settings[email_smtp_port]" class="form-control" value="<?= htmlspecialchars($email_smtp_port) ?>" min="1" max="65535">
                                    </div>
                                    <div class="col-6">
                                        <label class="form-label">Criptografia</label>
                                        <select name="email_settings[email_smtp_encryption]" class="form-select">
                                            <option value="tls" <?= $email_smtp_encryption === 'tls' ? 'selected' : '' ?>>TLS</option>
                                            <option value="ssl" <?= $email_smtp_encryption === 'ssl' ? 'selected' : '' ?>>SSL</option>
                                            <option value="none" <?= $email_smtp_encryption === 'none' ? 'selected' : '' ?>>Sem</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="mt-3 mb-3">
                                    <label class="form-label">Usuário</label>
                                    <input type="text" name="email_settings[email_smtp_username]" class="form-control" value="<?= htmlspecialchars($email_smtp_username) ?>" placeholder="email@seudominio.com">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Senha (opcional)</label>
                                    <input type="password" name="email_settings[email_smtp_password]" class="form-control" value="" placeholder="<?= $email_smtp_password !== '' ? 'Deixe em branco para manter' : '' ?>">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Nome do Remetente</label>
                                    <input type="text" name="email_settings[email_from_name]" class="form-control" value="<?= htmlspecialchars($email_from_name) ?>">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">E-mail do Remetente</label>
                                    <input type="email" name="email_settings[email_from_address]" class="form-control" value="<?= htmlspecialchars($email_from_address) ?>" placeholder="<?= htmlspecialchars($email_smtp_username) ?>">
                                </div>
                                <div class="form-check form-switch mb-0">
                                    <input class="form-check-input" type="checkbox" role="switch" id="admin_email_notifications_enabled" name="email_settings[email_notifications_enabled]" value="1" <?= $email_notifications_enabled ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="admin_email_notifications_enabled">Ativar notificações</label>
                                </div>
                            </div>
                        </div>

                        <div class="d-grid mt-3">
                            <button type="submit" class="btn btn-primary">Salvar E-mail</button>
                        </div>
                    </form>

                    <hr>

                    <?php
                        $defaultTestTo = $email_imap_username !== '' ? $email_imap_username : $email_from_address;
                        if ($defaultTestTo === '') {
                            $defaultTestTo = admin_get_setting($pdo, 'alert_email', '');
                        }
                    ?>

                    <div class="d-grid gap-2">
                        <form method="POST">
                            <input type="hidden" name="action" value="test_imap">
                            <button type="submit" class="btn btn-outline-primary w-100"><i class="fas fa-inbox me-2"></i> Testar IMAP (listar 5)</button>
                        </form>

                        <form method="POST">
                            <input type="hidden" name="action" value="test_smtp">
                            <label class="form-label small mb-1">Destino do teste SMTP</label>
                            <input type="email" name="test_to" class="form-control mb-2" value="<?= htmlspecialchars($defaultTestTo) ?>" placeholder="email@destino.com" required>
                            <button type="submit" class="btn btn-outline-success w-100"><i class="fas fa-paper-plane me-2"></i> Testar SMTP (enviar)</button>
                        </form>

                        <form method="POST">
                            <input type="hidden" name="action" value="test_email_full">
                            <input type="hidden" name="test_to" value="<?= htmlspecialchars($defaultTestTo) ?>">
                            <button type="submit" class="btn btn-outline-dark w-100"><i class="fas fa-rotate me-2"></i> Teste Completo (SMTP→IMAP)</button>
                        </form>
                    </div>
                </div>
            </div>

            <div class="card mb-4">
                <div class="card-header">Configuração de Alertas</div>
                <div class="card-body">
                    <?php
                        $stmtEmail = $pdo->prepare("SELECT setting_value FROM system_settings WHERE setting_key = 'alert_email'");
                        $stmtEmail->execute();
                        $alert_email = $stmtEmail->fetchColumn() ?: '';

                        $stmtDays = $pdo->prepare("SELECT setting_value FROM system_settings WHERE setting_key = 'alert_days'");
                        $stmtDays->execute();
                        $alert_days = $stmtDays->fetchColumn() ?: '15';

                        $stmtPath = $pdo->prepare("SELECT setting_value FROM system_settings WHERE setting_key = 'nc_path'");
                        $stmtPath->execute();
                        $nc_path = $stmtPath->fetchColumn() ?: NC_CONTRACTS_PATH_DEFAULT;

                        $stmtWebdavUser = $pdo->prepare("SELECT setting_value FROM system_settings WHERE setting_key = 'nc_webdav_user'");
                        $stmtWebdavUser->execute();
                        $nc_webdav_user = $stmtWebdavUser->fetchColumn() ?: '';

                        $stmtWebdavPass = $pdo->prepare("SELECT setting_value FROM system_settings WHERE setting_key = 'nc_webdav_pass'");
                        $stmtWebdavPass->execute();
                        $nc_webdav_pass = $stmtWebdavPass->fetchColumn() ?: '';
                    ?>
                    <form method="POST">
                        <input type="hidden" name="action" value="update_settings">
                        <div class="mb-3">
                            <label class="form-label">E-mail Destinatário</label>
                            <input type="email" name="settings[alert_email]" class="form-control" value="<?= htmlspecialchars($alert_email) ?>" required>
                            <small class="text-muted">Este e-mail receberá os alertas automáticos de vencimento.</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Pasta Remota do Nextcloud</label>
                            <input type="text" name="settings[nc_path]" class="form-control" value="<?= htmlspecialchars($nc_path) ?>" required>
                            <small class="text-muted">Use a pasta raiz dos contratos. Exemplo: <code>C:\Users\aivm\Nextcloud\CONTRATOS</code> no local ou <code>CONTRATOS</code> para a raiz remota.</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Usuário Técnico WebDAV</label>
                            <input type="text" name="settings[nc_webdav_user]" class="form-control" value="<?= htmlspecialchars($nc_webdav_user) ?>" placeholder="Ex: aivm">
                            <small class="text-muted">Opcional. Se preenchido, a leitura e movimentação no Nextcloud usarão esse usuário fixo em vez do usuário logado.</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Senha do Usuário Técnico WebDAV</label>
                            <input type="password" name="settings[nc_webdav_pass]" class="form-control" value="<?= htmlspecialchars($nc_webdav_pass) ?>" placeholder="Senha do usuário técnico">
                            <small class="text-muted">Use a senha da conta que realmente enxerga a pasta <code>CONTRATOS</code>.</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Dias de Antecedência para o Alerta</label>
                            <div class="input-group">
                                <input type="number" name="settings[alert_days]" class="form-control" value="<?= htmlspecialchars($alert_days) ?>" required min="1" max="180">
                                <span class="input-group-text">dias antes do vencimento</span>
                            </div>
                            <small class="text-muted">O sistema enviará alertas para contratos que vencem neste período.</small>
                        </div>
                        <div class="d-grid gap-2">
                            <button type="submit" class="btn btn-primary">Salvar Configurações</button>
                            <a href="test_email_action.php" class="btn btn-outline-info"><i class="fas fa-paper-plane me-2"></i> Testar Envio Agora</a>
                        </div>
                    </form>
                </div>
            </div>

            <div class="card">
                <div class="card-header">Configurações do Sistema</div>
                <div class="card-body">
                    <p class="small text-muted">As configurações principais (API Nextcloud, Banco de Dados) devem ser editadas no arquivo <code>config/config.php</code>.</p>
                    <hr>
                    <h6>Informações do Ambiente:</h6>
                    <ul class="list-unstyled small">
                        <li><strong>Versão PHP:</strong> <?= phpversion() ?></li>
                        <li><strong>Servidor:</strong> <?= $_SERVER['SERVER_SOFTWARE'] ?></li>
                        <li><strong>Banco de Dados:</strong> <?= DB_NAME ?></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

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