<?php
require_once __DIR__ . '/../../../includes/config.php';
require_once __DIR__ . '/../../../includes/check-access.php';

$pdo = getDB();
$userId = $_SESSION['user_id'] ?? null;
$storeId = $_SESSION['store_id'] ?? null;

if (!$userId || !$storeId) {
    header('Location: /pages/login.php');
    exit;
}

$storeStmt = $pdo->prepare("SELECT * FROM stores WHERE id = ?");
$storeStmt->execute([$storeId]);
$store = $storeStmt->fetch(PDO::FETCH_ASSOC);

// Criar tabela se não existir
$pdo->exec("CREATE TABLE IF NOT EXISTS whatsapp_auto_messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    store_id INT NOT NULL,
    message_type VARCHAR(50) NOT NULL,
    enabled TINYINT(1) DEFAULT 1,
    message_text TEXT,
    delay_minutes INT DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY unique_store_type (store_id, message_type)
) DEFAULT CHARSET=utf8mb4");

$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $types = ['welcome', 'away', 'business_hours', 'faq', 'feedback'];
        foreach ($types as $type) {
            $enabled = isset($_POST['enabled_' . $type]) ? 1 : 0;
            $message = trim($_POST['message_' . $type] ?? '');
            $delay = intval($_POST['delay_' . $type] ?? 0);

            $stmt = $pdo->prepare("INSERT INTO whatsapp_auto_messages (store_id, message_type, enabled, message_text, delay_minutes)
                VALUES (?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE enabled = VALUES(enabled), message_text = VALUES(message_text), delay_minutes = VALUES(delay_minutes)");
            $stmt->execute([$storeId, $type, $enabled, $message, $delay]);
        }
        $success = 'Configurações salvas com sucesso!';
    } catch (Exception $e) {
        $error = 'Erro ao salvar: ' . $e->getMessage();
    }
}

$messagesStmt = $pdo->prepare("SELECT * FROM whatsapp_auto_messages WHERE store_id = ?");
$messagesStmt->execute([$storeId]);
$messages = [];
while ($row = $messagesStmt->fetch(PDO::FETCH_ASSOC)) {
    $messages[$row['message_type']] = $row;
}

$autoMessages = [
    'welcome' => [
        'title' => 'Mensagem de Boas-vindas',
        'description' => 'Enviada quando um cliente entra em contato pela primeira vez',
        'icon' => 'solar:hand-shake-bold',
        'color' => 'success',
        'default_message' => "Olá! 👋 Bem-vindo(a) à {loja}!\n\nComo posso ajudar você hoje?\n\nResponderemos o mais breve possível! 💚",
    ],
    'away' => [
        'title' => 'Mensagem de Ausência',
        'description' => 'Enviada fora do horário de atendimento',
        'icon' => 'solar:moon-bold',
        'color' => 'info',
        'default_message' => "Olá! 🌙\n\nObrigado por entrar em contato com a {loja}.\n\nNo momento estamos fora do horário de atendimento.\n\n⏰ Nosso horário: Seg a Sex, 9h às 18h\n\nResponderemos assim que possível!",
    ],
    'business_hours' => [
        'title' => 'Horário Comercial',
        'description' => 'Resposta automática durante horário comercial',
        'icon' => 'solar:clock-circle-bold',
        'color' => 'warning',
        'default_message' => "Olá! ⏰\n\nRecebemos sua mensagem!\n\nNosso tempo médio de resposta é de 15 minutos.\n\nEnquanto isso, confira nossos produtos em:\n{link_loja}\n\n{loja} 💚",
    ],
    'faq' => [
        'title' => 'Perguntas Frequentes',
        'description' => 'Informações automáticas sobre dúvidas comuns',
        'icon' => 'solar:question-circle-bold',
        'color' => 'primary',
        'default_message' => "📋 *Perguntas Frequentes*\n\n🚚 *Entrega:* 3 a 7 dias úteis\n💳 *Pagamento:* PIX, Cartão, Boleto\n🔄 *Trocas:* Até 7 dias após recebimento\n\nPrecisa de mais ajuda? Digite sua dúvida!",
    ],
    'feedback' => [
        'title' => 'Pesquisa de Satisfação',
        'description' => 'Solicitar avaliação após atendimento',
        'icon' => 'solar:star-bold',
        'color' => 'warning',
        'default_message' => "⭐ *Como foi seu atendimento?*\n\nOlá {cliente}!\n\nSua opinião é muito importante para nós.\n\nDe 1 a 5, como você avalia nosso atendimento?\n\n1️⃣ 2️⃣ 3️⃣ 4️⃣ 5️⃣\n\nObrigado! 💚\n{loja}",
    ],
];

$pageTitle = 'Mensagens Automáticas';
include __DIR__ . '/../../../includes/dashboard-header.php';
?>
<?php include __DIR__ . '/../../../includes/dashboard-styles.php'; ?>
<style>
.page-wrapper{max-width:1000px;margin:0 auto;padding:0 1rem}
.page-header{margin-bottom:2rem}
.page-header .back-link{display:inline-flex;align-items:center;gap:.5rem;color:var(--text-muted);text-decoration:none;font-size:.875rem;margin-bottom:1rem;transition:color .2s}
.page-header .back-link:hover{color:var(--primary)}
.page-header h1{display:flex;align-items:center;gap:.75rem;font-size:1.5rem;font-weight:700;margin-bottom:.5rem}
.page-header h1 iconify-icon{color:#25D366}
.page-header p{color:var(--text-secondary);font-size:.9rem}
.alert{display:flex;align-items:center;gap:.75rem;padding:1rem;border-radius:var(--radius-md);margin-bottom:1.5rem;font-weight:500}
.alert-success{background:rgba(34,197,94,.1);color:var(--success);border:1px solid rgba(34,197,94,.2)}
.alert-error{background:rgba(239,68,68,.1);color:var(--error);border:1px solid rgba(239,68,68,.2)}
.variables-card{background:var(--bg-card);border:1px solid var(--border);border-radius:var(--radius-lg);padding:1rem 1.25rem;margin-bottom:1.5rem}
.variables-card h3{display:flex;align-items:center;gap:.5rem;font-size:.9rem;font-weight:600;margin-bottom:.75rem;color:var(--text-primary)}
.variables-card h3 iconify-icon{color:var(--primary)}
.variables-list{display:flex;flex-wrap:wrap;gap:.5rem}
.var-tag{display:inline-flex;align-items:center;gap:.25rem;padding:.35rem .65rem;background:var(--bg-dark);border:1px solid var(--border);border-radius:var(--radius-sm);font-size:.8rem;font-family:Monaco,Consolas,monospace;color:var(--primary);cursor:pointer;transition:all .2s}
.var-tag:hover{background:var(--primary);color:#fff;border-color:var(--primary)}
.message-card{background:var(--bg-card);border:1px solid var(--border);border-radius:var(--radius-lg);margin-bottom:1rem;overflow:hidden;transition:all .2s}
.message-card:hover{border-color:var(--primary)}
.message-card.disabled{opacity:.5}
.message-header{display:flex;align-items:center;justify-content:space-between;padding:1rem 1.25rem;border-bottom:1px solid var(--border);cursor:pointer}
.message-info{display:flex;align-items:center;gap:.75rem}
.message-icon{width:40px;height:40px;border-radius:var(--radius-md);display:flex;align-items:center;justify-content:center}
.message-icon iconify-icon{font-size:1.25rem}
.message-icon.info{background:rgba(59,130,246,.15)}.message-icon.info iconify-icon{color:var(--info)}
.message-icon.success{background:rgba(34,197,94,.15)}.message-icon.success iconify-icon{color:var(--success)}
.message-icon.warning{background:rgba(249,115,22,.15)}.message-icon.warning iconify-icon{color:var(--warning)}
.message-icon.primary{background:var(--primary-light)}.message-icon.primary iconify-icon{color:var(--primary)}
.message-icon.error{background:rgba(239,68,68,.15)}.message-icon.error iconify-icon{color:var(--error)}
.message-text h4{font-size:.95rem;font-weight:600;margin-bottom:.15rem}
.message-text span{font-size:.8rem;color:var(--text-muted)}
.toggle-wrap{display:flex;align-items:center;gap:.75rem}
.toggle-label{font-size:.75rem;font-weight:500;text-transform:uppercase;color:var(--text-muted)}
.toggle{position:relative;width:44px;height:24px}
.toggle input{opacity:0;width:0;height:0}
.toggle-slider{position:absolute;cursor:pointer;top:0;left:0;right:0;bottom:0;background-color:var(--border);border-radius:24px;transition:.2s}
.toggle-slider:before{position:absolute;content:"";height:18px;width:18px;left:3px;bottom:3px;background-color:#fff;border-radius:50%;transition:.2s;box-shadow:0 2px 4px rgba(0,0,0,.2)}
.toggle input:checked+.toggle-slider{background:var(--success)}
.toggle input:checked+.toggle-slider:before{transform:translateX(20px)}
.message-body{padding:1.25rem;display:none}
.message-card.open .message-body{display:block}
.expand-icon{color:var(--text-muted);transition:transform .2s}
.message-card.open .expand-icon{transform:rotate(180deg)}
.form-grid{display:grid;grid-template-columns:1fr 160px;gap:1.25rem;align-items:start}
.form-group label{display:flex;align-items:center;gap:.35rem;font-size:.85rem;font-weight:600;margin-bottom:.5rem;color:var(--text-secondary)}
.form-group label iconify-icon{font-size:1rem}
.message-textarea{width:100%;min-height:140px;padding:.75rem;background:var(--bg-dark);border:1px solid var(--border);border-radius:var(--radius-md);color:var(--text-primary);font-size:.85rem;font-family:inherit;line-height:1.5;resize:vertical;transition:border-color .2s}
.message-textarea:focus{outline:none;border-color:var(--primary)}
.delay-group{display:flex;flex-direction:column}
.delay-input-wrap{display:flex;align-items:center;background:var(--bg-dark);border:1px solid var(--border);border-radius:var(--radius-md);overflow:hidden}
.delay-input-wrap input{width:70px;padding:.75rem;border:none;background:transparent;color:var(--text-primary);font-size:1rem;font-weight:600;text-align:center}
.delay-input-wrap input:focus{outline:none}
.delay-unit{padding:.75rem;background:var(--border);color:var(--text-muted);font-size:.8rem;font-weight:500}
.preview-box{margin-top:.75rem;padding:.6rem .75rem;background:#DCF8C6;border-radius:var(--radius-md);font-size:.8rem;line-height:1.4;white-space:pre-wrap;color:#111;max-height:100px;overflow-y:auto}
.form-actions{display:flex;justify-content:flex-end;padding-top:1.5rem;margin-top:.5rem}
.btn-save{display:inline-flex;align-items:center;gap:.5rem;padding:.75rem 2rem;background:linear-gradient(135deg,#25D366,#128C7E);color:#fff;border:none;border-radius:var(--radius-md);font-size:.95rem;font-weight:600;cursor:pointer;transition:all .2s}
.btn-save:hover{transform:translateY(-2px);box-shadow:0 4px 15px rgba(37,211,102,.4)}
@media(max-width:768px){.form-grid{grid-template-columns:1fr}.message-header{flex-wrap:wrap;gap:1rem}.toggle-wrap{width:100%;justify-content:space-between;padding-top:.75rem;border-top:1px solid var(--border)}}
</style>
<main class="main-content">
<div class="page-wrapper">
<div class="page-header">
<a href="/pages/dashboard/whatsapp/" class="back-link"><iconify-icon icon="solar:arrow-left-linear"></iconify-icon>Voltar</a>
<h1><iconify-icon icon="solar:chat-round-dots-bold"></iconify-icon>Mensagens Automáticas</h1>
<p>Configure respostas automáticas para seu atendimento via WhatsApp</p>
</div>
<?php if ($success): ?><div class="alert alert-success"><iconify-icon icon="solar:check-circle-bold"></iconify-icon><?= htmlspecialchars($success) ?></div><?php endif; ?>
<?php if ($error): ?><div class="alert alert-error"><iconify-icon icon="solar:danger-triangle-bold"></iconify-icon><?= htmlspecialchars($error) ?></div><?php endif; ?>
<div class="variables-card">
<h3><iconify-icon icon="solar:code-bold"></iconify-icon>Variáveis disponíveis</h3>
<div class="variables-list">
<span class="var-tag" onclick="copyVar('{cliente}')">{cliente}</span>
<span class="var-tag" onclick="copyVar('{loja}')">{loja}</span>
<span class="var-tag" onclick="copyVar('{link_loja}')">{link_loja}</span>
<span class="var-tag" onclick="copyVar('{telefone}')">{telefone}</span>
</div>
</div>
<form method="POST">
<?php foreach ($autoMessages as $type => $config):
$saved = $messages[$type] ?? null;
$isEnabled = $saved ? (bool)$saved['enabled'] : ($type === 'welcome');
$messageText = $saved['message_text'] ?? $config['default_message'];
$delay = $saved['delay_minutes'] ?? 0;
?>
<div class="message-card <?= !$isEnabled ? 'disabled' : '' ?> <?= $type === 'welcome' ? 'open' : '' ?>" data-type="<?= $type ?>">
<div class="message-header" onclick="toggleCard('<?= $type ?>')">
<div class="message-info">
<div class="message-icon <?= $config['color'] ?>"><iconify-icon icon="<?= $config['icon'] ?>"></iconify-icon></div>
<div class="message-text"><h4><?= $config['title'] ?></h4><span><?= $config['description'] ?></span></div>
</div>
<div class="toggle-wrap" onclick="event.stopPropagation()">
<span class="toggle-label"><?= $isEnabled ? 'Ativo' : 'Inativo' ?></span>
<label class="toggle"><input type="checkbox" name="enabled_<?= $type ?>" <?= $isEnabled ? 'checked' : '' ?> onchange="updateToggle(this, '<?= $type ?>')"><span class="toggle-slider"></span></label>
<iconify-icon icon="solar:alt-arrow-down-linear" class="expand-icon"></iconify-icon>
</div>
</div>
<div class="message-body">
<div class="form-grid">
<div class="form-group">
<label><iconify-icon icon="solar:chat-line-bold"></iconify-icon>Mensagem</label>
<textarea class="message-textarea" name="message_<?= $type ?>" oninput="updatePreview(this, '<?= $type ?>')"><?= htmlspecialchars($messageText) ?></textarea>
<div class="preview-box" id="preview-<?= $type ?>"></div>
</div>
<div class="form-group delay-group">
<label><iconify-icon icon="solar:clock-circle-bold"></iconify-icon>Atraso</label>
<div class="delay-input-wrap">
<input type="number" name="delay_<?= $type ?>" value="<?= $delay ?>" min="0" max="1440">
<span class="delay-unit">min</span>
</div>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
<div class="form-actions"><button type="submit" class="btn-save"><iconify-icon icon="solar:diskette-bold"></iconify-icon>Salvar Configurações</button></div>
</form>
</div>
</main>
<?php include __DIR__ . '/../../../includes/dashboard-footer.php'; ?>
<script>
const storeName = '<?= htmlspecialchars($store['name'] ?? 'Minha Loja') ?>';
function toggleCard(type){document.querySelector('[data-type="'+type+'"]').classList.toggle('open')}
function updateToggle(input,type){const card=document.querySelector('[data-type="'+type+'"]'),label=card.querySelector('.toggle-label');input.checked?(card.classList.remove('disabled'),label.textContent='Ativo'):(card.classList.add('disabled'),label.textContent='Inativo')}
function updatePreview(textarea,type){const preview=document.getElementById('preview-'+type);let text=textarea.value.replace(/{cliente}/g,'João Silva').replace(/{loja}/g,storeName).replace(/{link_loja}/g,'minha-loja.duolead.com.br').replace(/{telefone}/g,'(27) 99999-9999');preview.innerHTML=text.replace(/\n/g,'<br>')}
function copyVar(variable){navigator.clipboard.writeText(variable);event.target.style.background='var(--success)';event.target.style.color='#fff';setTimeout(()=>{event.target.style.background='';event.target.style.color=''},300)}
document.addEventListener('DOMContentLoaded',()=>{document.querySelectorAll('.message-textarea').forEach(textarea=>{const name=textarea.name.replace('message_','');updatePreview(textarea,name)})});
</script>
