<?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);

// Status de pedido com descrições
$orderStatuses = [
    'pending' => [
        'title' => 'Novo Pedido',
        'description' => 'Quando um novo pedido é criado',
        'icon' => 'solar:bag-4-bold',
        'color' => 'info',
        'default_message' => "🛒 *Novo Pedido #{pedido}*\n\nOlá {cliente}!\n\nRecebemos seu pedido com sucesso!\n\n📦 Itens: {itens}\n💰 Total: R$ {valor}\n\nAguarde a confirmação. Obrigado por comprar na {loja}! 💚",
        'default_owner_message' => "🔔 *NOVO PEDIDO RECEBIDO!*\n\n📦 *Pedido #{pedido}*\n\n👤 *Cliente:* {cliente}\n📱 *Telefone:* {telefone}\n📍 *Endereço:* {endereco}\n\n*Itens:*\n{itens}\n\n💰 *Total:* R$ {valor}",
    ],
    'confirmed' => [
        'title' => 'Pedido Confirmado',
        'description' => 'Quando o pedido é confirmado pela loja',
        'icon' => 'solar:check-circle-bold',
        'color' => 'success',
        'default_message' => "✅ *Pedido Confirmado!*\n\nOlá {cliente}!\n\nSeu pedido #{pedido} foi confirmado!\n\n💰 Total: R$ {valor}\n\nEstamos preparando tudo com carinho. 💚\n\n{loja}",
        'default_owner_message' => "✅ *PEDIDO CONFIRMADO*\n\n📦 Pedido #{pedido}\n👤 Cliente: {cliente}\n💰 Total: R$ {valor}",
    ],
    'preparing' => [
        'title' => 'Em Preparação',
        'description' => 'Quando o pedido está sendo preparado',
        'icon' => 'solar:chef-hat-bold',
        'color' => 'warning',
        'default_message' => "👨‍🍳 *Preparando seu Pedido!*\n\nOlá {cliente}!\n\nSeu pedido #{pedido} está sendo preparado.\n\nEm breve você receberá mais atualizações!\n\n{loja}",
        'default_owner_message' => "👨‍🍳 *PEDIDO EM PREPARAÇÃO*\n\n📦 Pedido #{pedido}\n👤 Cliente: {cliente}",
    ],
    'shipped' => [
        'title' => 'Pedido Enviado',
        'description' => 'Quando o pedido é despachado para entrega',
        'icon' => 'solar:delivery-bold',
        'color' => 'primary',
        'default_message' => "🚚 *Pedido a Caminho!*\n\nOlá {cliente}!\n\nSeu pedido #{pedido} saiu para entrega!\n\n📍 Endereço: {endereco}\n\nFique atento! Logo logo chega. 💚\n\n{loja}",
        'default_owner_message' => "🚚 *PEDIDO ENVIADO*\n\n📦 Pedido #{pedido}\n👤 Cliente: {cliente}\n📍 Endereço: {endereco}",
    ],
    'delivered' => [
        'title' => 'Pedido Entregue',
        'description' => 'Quando o pedido é entregue ao cliente',
        'icon' => 'solar:verified-check-bold',
        'color' => 'success',
        'default_message' => "🎉 *Pedido Entregue!*\n\nOlá {cliente}!\n\nSeu pedido #{pedido} foi entregue com sucesso!\n\nEsperamos que goste! 💚\n\nQualquer dúvida, estamos aqui.\n\nObrigado por comprar na {loja}! ⭐",
        'default_owner_message' => "🎉 *PEDIDO ENTREGUE*\n\n📦 Pedido #{pedido}\n👤 Cliente: {cliente}\n💰 Total: R$ {valor}",
    ],
    'cancelled' => [
        'title' => 'Pedido Cancelado',
        'description' => 'Quando o pedido é cancelado',
        'icon' => 'solar:close-circle-bold',
        'color' => 'error',
        'default_message' => "❌ *Pedido Cancelado*\n\nOlá {cliente}.\n\nInfelizmente seu pedido #{pedido} foi cancelado.\n\nSe tiver dúvidas, entre em contato conosco.\n\n{loja}",
        'default_owner_message' => "❌ *PEDIDO CANCELADO*\n\n📦 Pedido #{pedido}\n👤 Cliente: {cliente}\n💰 Total: R$ {valor}",
    ],
];

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        foreach (array_keys($orderStatuses) as $status) {
            $enabled = isset($_POST['enabled_' . $status]) ? 1 : 0;
            $message = trim($_POST['message_' . $status] ?? '');
            $ownerMessage = trim($_POST['owner_message_' . $status] ?? '');
            $sendToCustomer = isset($_POST['send_customer_' . $status]) ? 1 : 0;
            $sendToOwner = isset($_POST['send_owner_' . $status]) ? 1 : 0;

            $stmt = $pdo->prepare("INSERT INTO whatsapp_order_notifications
                (store_id, status_trigger, enabled, message_template, owner_message_template, send_to_customer, send_to_owner)
                VALUES (?, ?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE
                    enabled = VALUES(enabled),
                    message_template = VALUES(message_template),
                    owner_message_template = VALUES(owner_message_template),
                    send_to_customer = VALUES(send_to_customer),
                    send_to_owner = VALUES(send_to_owner)");
            $stmt->execute([$storeId, $status, $enabled, $message, $ownerMessage, $sendToCustomer, $sendToOwner]);
        }
        $success = 'Configurações salvas com sucesso!';
    } catch (Exception $e) {
        $error = 'Erro ao salvar: ' . $e->getMessage();
    }
}

$notificationsStmt = $pdo->prepare("SELECT * FROM whatsapp_order_notifications WHERE store_id = ?");
$notificationsStmt->execute([$storeId]);
$notifications = [];
while ($row = $notificationsStmt->fetch(PDO::FETCH_ASSOC)) {
    $notifications[$row['status_trigger']] = $row;
}

$pageTitle = 'Notificações de Pedidos';
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:var(--primary)}
.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)}
.status-card{background:var(--bg-card);border:1px solid var(--border);border-radius:var(--radius-lg);margin-bottom:1rem;overflow:hidden;transition:all .2s}
.status-card:hover{border-color:var(--primary)}
.status-card.disabled{opacity:.5}
.status-header{display:flex;align-items:center;justify-content:space-between;padding:1rem 1.25rem;border-bottom:1px solid var(--border);cursor:pointer}
.status-info{display:flex;align-items:center;gap:.75rem}
.status-icon{width:40px;height:40px;border-radius:var(--radius-md);display:flex;align-items:center;justify-content:center}
.status-icon iconify-icon{font-size:1.25rem}
.status-icon.info{background:rgba(59,130,246,.15)}.status-icon.info iconify-icon{color:var(--info)}
.status-icon.success{background:rgba(34,197,94,.15)}.status-icon.success iconify-icon{color:var(--success)}
.status-icon.warning{background:rgba(249,115,22,.15)}.status-icon.warning iconify-icon{color:var(--warning)}
.status-icon.primary{background:var(--primary-light)}.status-icon.primary iconify-icon{color:var(--primary)}
.status-icon.error{background:rgba(239,68,68,.15)}.status-icon.error iconify-icon{color:var(--error)}
.status-text h4{font-size:.95rem;font-weight:600;margin-bottom:.15rem}
.status-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)}
.status-body{padding:1.25rem;display:none}
.status-card.open .status-body{display:block}
.send-options{display:flex;gap:1.5rem;margin-bottom:1.25rem;padding-bottom:1rem;border-bottom:1px solid var(--border)}
.send-option{display:flex;align-items:center;gap:.5rem;cursor:pointer}
.send-option input[type=checkbox]{width:18px;height:18px;accent-color:var(--primary)}
.send-option span{display:flex;align-items:center;gap:.35rem;font-size:.875rem}
.send-option iconify-icon{color:var(--text-muted)}
.templates-row{display:grid;grid-template-columns:1fr 1fr;gap:1.25rem}
.template-col h5{display:flex;align-items:center;gap:.5rem;font-size:.85rem;font-weight:600;margin-bottom:.5rem;color:var(--text-secondary)}
.template-col h5 iconify-icon{font-size:1rem}
.template-col.customer h5 iconify-icon{color:var(--info)}
.template-col.owner h5 iconify-icon{color:var(--warning)}
.template-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}
.template-textarea:focus{outline:none;border-color:var(--primary)}
.preview-box{margin-top:.5rem;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}
.expand-icon{color:var(--text-muted);transition:transform .2s}
.status-card.open .expand-icon{transform:rotate(180deg)}
.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,var(--primary),#FFD700);color:#000;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:var(--shadow-primary)}
@media(max-width:768px){.templates-row{grid-template-columns:1fr}.send-options{flex-direction:column;gap:.75rem}.status-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:bell-bing-bold"></iconify-icon>Notificações de Pedidos</h1>
<p>Configure mensagens automáticas para cada etapa do pedido</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('{pedido}')">{pedido}</span>
<span class="var-tag" onclick="copyVar('{valor}')">{valor}</span>
<span class="var-tag" onclick="copyVar('{itens}')">{itens}</span>
<span class="var-tag" onclick="copyVar('{endereco}')">{endereco}</span>
<span class="var-tag" onclick="copyVar('{loja}')">{loja}</span>
<span class="var-tag" onclick="copyVar('{telefone}')">{telefone}</span>
</div>
</div>
<form method="POST">
<?php foreach ($orderStatuses as $status => $config):
$saved = $notifications[$status] ?? null;
$isEnabled = $saved ? (bool)$saved['enabled'] : true;
$messageText = $saved['message_template'] ?? $config['default_message'];
$ownerMessageText = $saved['owner_message_template'] ?? $config['default_owner_message'];
$sendToCustomer = $saved ? (bool)$saved['send_to_customer'] : true;
$sendToOwner = $saved ? (bool)$saved['send_to_owner'] : ($status === 'pending');
?>
<div class="status-card <?= !$isEnabled ? 'disabled' : '' ?> <?= $status === 'pending' ? 'open' : '' ?>" data-status="<?= $status ?>">
<div class="status-header" onclick="toggleCard('<?= $status ?>')">
<div class="status-info">
<div class="status-icon <?= $config['color'] ?>"><iconify-icon icon="<?= $config['icon'] ?>"></iconify-icon></div>
<div class="status-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_<?= $status ?>" <?= $isEnabled ? 'checked' : '' ?> onchange="updateToggle(this, '<?= $status ?>')"><span class="toggle-slider"></span></label>
<iconify-icon icon="solar:alt-arrow-down-linear" class="expand-icon"></iconify-icon>
</div>
</div>
<div class="status-body">
<div class="send-options">
<label class="send-option"><input type="checkbox" name="send_customer_<?= $status ?>" <?= $sendToCustomer ? 'checked' : '' ?>><span><iconify-icon icon="solar:user-linear"></iconify-icon>Enviar para Cliente</span></label>
<label class="send-option"><input type="checkbox" name="send_owner_<?= $status ?>" <?= $sendToOwner ? 'checked' : '' ?>><span><iconify-icon icon="solar:shop-linear"></iconify-icon>Notificar Dono da Loja</span></label>
</div>
<div class="templates-row">
<div class="template-col customer">
<h5><iconify-icon icon="solar:user-bold"></iconify-icon>Mensagem para Cliente</h5>
<textarea class="template-textarea" name="message_<?= $status ?>" oninput="updatePreview(this, 'customer-<?= $status ?>')"><?= htmlspecialchars($messageText) ?></textarea>
<div class="preview-box" id="preview-customer-<?= $status ?>"></div>
</div>
<div class="template-col owner">
<h5><iconify-icon icon="solar:shop-bold"></iconify-icon>Mensagem para Dono</h5>
<textarea class="template-textarea" name="owner_message_<?= $status ?>" oninput="updatePreview(this, 'owner-<?= $status ?>')"><?= htmlspecialchars($ownerMessageText) ?></textarea>
<div class="preview-box" id="preview-owner-<?= $status ?>"></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(status){document.querySelector('[data-status="'+status+'"]').classList.toggle('open')}
function updateToggle(input,status){const card=document.querySelector('[data-status="'+status+'"]'),label=card.querySelector('.toggle-label');input.checked?(card.classList.remove('disabled'),label.textContent='Ativo'):(card.classList.add('disabled'),label.textContent='Inativo')}
function updatePreview(textarea,previewId){const preview=document.getElementById('preview-'+previewId);let text=textarea.value.replace(/{cliente}/g,'João Silva').replace(/{pedido}/g,'1234').replace(/{valor}/g,'150,00').replace(/{itens}/g,'2x Produto A, 1x Produto B').replace(/{endereco}/g,'Rua das Flores, 123 - Centro').replace(/{loja}/g,storeName).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('.template-textarea').forEach(textarea=>{const name=textarea.name;let previewId=name.startsWith('owner_message_')?'owner-'+name.replace('owner_message_',''):'customer-'+name.replace('message_','');updatePreview(textarea,previewId)})});
</script>
