<?php
/**
 * Super Admin - Notificações
 * Enviar notificações personalizadas para lojas
 */
require_once __DIR__ . '/../../../includes/config.php';

// Verifica se é Super Admin
if (!isSuperAdmin()) {
    header('Location: /pages/login.php');
    exit;
}

$superAdmin = getSuperAdmin();
$pdo = getDB();

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

// Processar envio de notificação
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $target = $_POST['target'] ?? '';
    $targetStore = $_POST['target_store'] ?? '';
    $type = $_POST['type'] ?? 'info';
    $title = trim($_POST['title'] ?? '');
    $message = trim($_POST['message'] ?? '');
    $link = trim($_POST['link'] ?? '');
    $icon = $_POST['icon'] ?? 'solar:bell-bold';
    
    if (empty($title) || empty($message)) {
        $error = 'Título e mensagem são obrigatórios.';
    } else {
        try {
            $storeIds = [];
            
            if ($target === 'all') {
                $stmt = $pdo->query("SELECT id FROM stores WHERE deleted_at IS NULL");
                $storeIds = $stmt->fetchAll(PDO::FETCH_COLUMN);
            } elseif ($target === 'service') {
                $stmt = $pdo->query("SELECT id FROM stores WHERE business_type = 'service' AND deleted_at IS NULL");
                $storeIds = $stmt->fetchAll(PDO::FETCH_COLUMN);
            } elseif ($target === 'retail') {
                $stmt = $pdo->query("SELECT id FROM stores WHERE business_type = 'retail' AND deleted_at IS NULL");
                $storeIds = $stmt->fetchAll(PDO::FETCH_COLUMN);
            } elseif ($target === 'single') {
                if ($targetStore) {
                    $storeIds = [$targetStore];
                }
            }
            
            if (empty($storeIds)) {
                $error = 'Nenhuma loja encontrada para o filtro selecionado.';
            } else {
                $insertStmt = $pdo->prepare("
                    INSERT INTO notifications (store_id, type, title, message, link, icon, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, NOW())
                ");
                
                $count = 0;
                foreach ($storeIds as $storeId) {
                    $insertStmt->execute([$storeId, $type, $title, $message, $link ?: null, $icon]);
                    $count++;
                }
                
                $success = "Notificação enviada com sucesso para {$count} loja(s)!";
            }
        } catch (Exception $e) {
            $error = 'Erro ao enviar notificação: ' . $e->getMessage();
        }
    }
}

// Buscar lojas para o select
$stores = $pdo->query("SELECT id, name FROM stores WHERE deleted_at IS NULL ORDER BY name")->fetchAll();

// Buscar últimas notificações enviadas
$recentNotifications = $pdo->query("
    SELECT n.*, s.name as store_name
    FROM notifications n
    LEFT JOIN stores s ON n.store_id = s.id
    ORDER BY n.created_at DESC
    LIMIT 20
")->fetchAll();

$pageTitle = 'Notificações';
$currentPage = 'notifications';

include __DIR__ . '/../includes/header.php';
?>
    <div class="app-container">
        <?php include __DIR__ . '/../includes/sidebar.php'; ?>

        <!-- Main Content -->
        <main class="main-content">
            <?php include __DIR__ . '/../includes/topbar.php'; ?>

            <div class="content-area">
                <div class="page-header">
                    <div>
                        <h1>
                            <iconify-icon icon="solar:bell-bold" class="text-gold"></iconify-icon>
                            Enviar Notificações
                        </h1>
                        <p>Envie notificações personalizadas para lojas</p>
                    </div>
                </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-danger">
                    <iconify-icon icon="solar:danger-triangle-bold"></iconify-icon>
                    <?= htmlspecialchars($error) ?>
                </div>
                <?php endif; ?>

                <div class="notifications-grid">
                    <!-- Formulário de Envio -->
                    <div class="panel">
                        <div class="section-header">
                            <h3 class="section-title">
                                <iconify-icon icon="solar:pen-new-square-bold" class="text-gold"></iconify-icon>
                                Nova Notificação
                            </h3>
                        </div>
                        
                        <form method="POST">
                            <div class="form-group">
                                <label class="form-label">Destinatários</label>
                                <select name="target" id="target" class="form-select" required>
                                    <option value="all">Todas as Lojas</option>
                                    <option value="service">Apenas Serviços (Barbearias, Salões...)</option>
                                    <option value="retail">Apenas Varejo (Lojas, E-commerce...)</option>
                                    <option value="single">Loja Específica</option>
                                </select>
                            </div>

                            <div class="form-group" id="store-select-group" style="display: none;">
                                <label class="form-label">Selecionar Loja</label>
                                <select name="target_store" id="target_store" class="form-select">
                                    <option value="">Selecione uma loja</option>
                                    <?php foreach ($stores as $store): ?>
                                    <option value="<?= $store['id'] ?>"><?= htmlspecialchars($store['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="form-group">
                                <label class="form-label">Tipo de Notificação</label>
                                <select name="type" class="form-select" required>
                                    <option value="info">Informação</option>
                                    <option value="system">Sistema</option>
                                    <option value="order">Pedidos</option>
                                    <option value="payment">Pagamentos</option>
                                    <option value="stock">Estoque</option>
                                </select>
                            </div>

                            <div class="form-group">
                                <label class="form-label">Ícone</label>
                                <select name="icon" class="form-select">
                                    <option value="solar:bell-bold">🔔 Sino (padrão)</option>
                                    <option value="solar:info-circle-bold">ℹ️ Informação</option>
                                    <option value="solar:danger-triangle-bold">⚠️ Alerta</option>
                                    <option value="solar:check-circle-bold">✅ Sucesso</option>
                                    <option value="solar:gift-bold">🎁 Presente/Promoção</option>
                                    <option value="solar:star-bold">⭐ Destaque</option>
                                    <option value="solar:rocket-bold">🚀 Novidade</option>
                                    <option value="solar:wallet-money-bold">💰 Financeiro</option>
                                </select>
                            </div>

                            <div class="form-group">
                                <label class="form-label">Título</label>
                                <input type="text" name="title" class="form-input" placeholder="Ex: Nova funcionalidade disponível!" required maxlength="100">
                            </div>

                            <div class="form-group">
                                <label class="form-label">Mensagem</label>
                                <textarea name="message" class="form-input" rows="4" placeholder="Digite a mensagem da notificação..." required maxlength="500" style="resize: vertical; min-height: 100px;"></textarea>
                            </div>

                            <div class="form-group">
                                <label class="form-label">Link (opcional)</label>
                                <input type="text" name="link" class="form-input" placeholder="Ex: /pages/dashboard/nova-funcionalidade.php">
                                <small class="text-muted text-sm mt-1" style="display: block;">Link para onde o usuário será direcionado ao clicar</small>
                            </div>

                            <button type="submit" class="btn btn-primary" style="width: 100%;">
                                <iconify-icon icon="solar:plain-bold"></iconify-icon>
                                Enviar Notificação
                            </button>
                        </form>
                    </div>

                    <!-- Histórico -->
                    <div class="panel">
                        <div class="section-header">
                            <h3 class="section-title">
                                <iconify-icon icon="solar:history-bold" class="text-gold"></iconify-icon>
                                Últimas Notificações Enviadas
                            </h3>
                        </div>
                        
                        <?php if (empty($recentNotifications)): ?>
                        <div class="empty-state">
                            <iconify-icon icon="solar:bell-off-bold"></iconify-icon>
                            <p>Nenhuma notificação enviada ainda</p>
                        </div>
                        <?php else: ?>
                        <div class="notifications-list">
                            <?php foreach ($recentNotifications as $notif): ?>
                            <div class="notification-item">
                                <div class="notification-icon">
                                    <iconify-icon icon="<?= htmlspecialchars($notif['icon'] ?? 'solar:bell-bold') ?>"></iconify-icon>
                                </div>
                                <div class="notification-content">
                                    <div class="notification-title"><?= htmlspecialchars($notif['title']) ?></div>
                                    <div class="notification-message"><?= htmlspecialchars($notif['message']) ?></div>
                                    <div class="notification-meta">
                                        <span>
                                            <iconify-icon icon="solar:shop-bold"></iconify-icon>
                                            <?= htmlspecialchars($notif['store_name'] ?? 'N/A') ?>
                                        </span>
                                        <span>
                                            <iconify-icon icon="solar:clock-circle-bold"></iconify-icon>
                                            <?= date('d/m/Y H:i', strtotime($notif['created_at'])) ?>
                                        </span>
                                        <?php if ($notif['is_read']): ?>
                                        <span class="status-badge status-active">Lida</span>
                                        <?php else: ?>
                                        <span class="status-badge status-trial">Não lida</span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <?php include __DIR__ . '/../includes/footer.php'; ?>
        </main>
    </div>

    <style>
        /* Estilos para Select e Options */
        .form-select {
            appearance: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath fill='%239CA3AF' d='M7 10l5 5 5-5H7z'%3E%3C/path%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 0.75rem center;
            background-size: 1.25rem;
            padding-right: 2.5rem;
            cursor: pointer;
        }

        .form-select:hover {
            border-color: var(--gold);
        }

        .form-select option {
            background-color: #252525;
            color: #FFFFFF;
            padding: 12px 16px;
            font-size: 0.95rem;
            border: none;
        }

        .form-select option:hover,
        .form-select option:focus,
        .form-select option:checked {
            background: linear-gradient(135deg, rgba(204, 164, 59, 0.3), rgba(204, 164, 59, 0.1));
            color: #CCA43B;
        }

        .form-select option:disabled {
            color: #6B7280;
            background-color: #1A1A1A;
        }

        /* Textarea */
        textarea.form-input {
            resize: vertical;
            min-height: 100px;
            line-height: 1.5;
        }


        /* Grid responsivo para as notificações */
        .notifications-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1.5rem;
        }

        @media (max-width: 1024px) {
            .notifications-grid {
                grid-template-columns: 1fr;
            }
        }

        /* Alertas */
        .alert {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            padding: 1rem 1.25rem;
            border-radius: var(--radius-md);
            margin-bottom: 1.5rem;
            font-weight: 500;
        }

        .alert iconify-icon {
            font-size: 1.25rem;
            flex-shrink: 0;
        }

        .alert-success {
            background: rgba(34, 197, 94, 0.1);
            border: 1px solid rgba(34, 197, 94, 0.3);
            color: var(--success);
        }

        .alert-danger {
            background: rgba(239, 68, 68, 0.1);
            border: 1px solid rgba(239, 68, 68, 0.3);
            color: var(--danger);
        }

        /* Lista de notificações */
        .notifications-list {
            max-height: 500px;
            overflow-y: auto;
        }

        .notification-item {
            display: flex;
            gap: 1rem;
            padding: 1rem 0;
            border-bottom: 1px solid var(--border-light);
        }

        .notification-item:last-child {
            border-bottom: none;
        }

        .notification-icon {
            width: 40px;
            height: 40px;
            min-width: 40px;
            border-radius: var(--radius-md);
            background: rgba(204, 164, 59, 0.1);
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .notification-icon iconify-icon {
            font-size: 1.25rem;
            color: var(--gold);
        }

        .notification-content {
            flex: 1;
            min-width: 0;
        }

        .notification-title {
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 0.25rem;
        }

        .notification-message {
            font-size: 0.875rem;
            color: var(--text-muted);
            margin-bottom: 0.5rem;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .notification-meta {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            gap: 0.75rem;
            font-size: 0.75rem;
            color: var(--text-muted);
        }

        .notification-meta span {
            display: flex;
            align-items: center;
            gap: 0.25rem;
        }

        .notification-meta iconify-icon {
            font-size: 0.875rem;
        }

        /* Estado vazio */
        .empty-state {
            padding: 3rem;
            text-align: center;
            color: var(--text-muted);
        }

        .empty-state iconify-icon {
            font-size: 3rem;
            margin-bottom: 1rem;
            opacity: 0.5;
            display: block;
        }

        /* Ajuste no section-title para incluir ícone */
        .section-title {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .section-title iconify-icon {
            font-size: 1.25rem;
        }

        /* Mobile adjustments */
        @media (max-width: 768px) {
            .notification-item {
                padding: 0.875rem 0;
            }

            .notification-icon {
                width: 36px;
                height: 36px;
                min-width: 36px;
            }

            .notification-icon iconify-icon {
                font-size: 1rem;
            }

            .notification-title {
                font-size: 0.9rem;
            }

            .notification-message {
                font-size: 0.8rem;
            }

            .notification-meta {
                font-size: 0.7rem;
                gap: 0.5rem;
            }

            .notifications-list {
                max-height: 400px;
            }
        }

        @media (max-width: 480px) {
            .notification-meta {
                flex-direction: column;
                align-items: flex-start;
                gap: 0.25rem;
            }
        }
    </style>

    <script>
        document.getElementById('target').addEventListener('change', function() {
            const storeGroup = document.getElementById('store-select-group');
            const storeSelect = document.getElementById('target_store');
            
            if (this.value === 'single') {
                storeGroup.style.display = 'block';
                storeSelect.required = true;
            } else {
                storeGroup.style.display = 'none';
                storeSelect.required = false;
            }
        });
    </script>

