<?php
/**
 * BarberFlow SaaS - Dashboard Dinâmico
 * Painel principal adaptado ao tipo de negócio (service/retail)
 * Versão Responsiva com Filtros
 */
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/business-config.php';

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Expires: Sat, 01 Jan 2000 00:00:00 GMT");

$host = $_SERVER['HTTP_HOST'] ?? '';
$baseDomain = 'tiuoficial.com.br';
$subdomain = null;
if (strpos($host, '.' . $baseDomain) !== false) {
    $subdomain = str_replace('.' . $baseDomain, '', $host);
    $subdomain = strtolower(trim($subdomain));
    if (in_array($subdomain, ['www', 'app', 'api', 'admin', 'dev', ''])) {
        $subdomain = null;
    }
}

if ($subdomain) {
    include __DIR__ . '/router.php';
    exit;
}

if (!isset($_SESSION['user_id'])) {
    header('Location: /pages/login.php');
    exit;
}

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

$userStmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$userStmt->execute([$userId]);
$user = $userStmt->fetch(PDO::FETCH_ASSOC);

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

$storeStmt = $pdo->prepare("SELECT s.*, p.name as plan_name, p.features FROM stores s LEFT JOIN plans p ON s.plan_id = p.id WHERE s.id = ?");
$storeStmt->execute([$storeId]);
$store = $storeStmt->fetch(PDO::FETCH_ASSOC);

if (!$store) {
    session_destroy();
    header('Location: /pages/login.php');
    exit;
}

$businessType = $store['business_type'] ?? 'service';
$_SESSION['business_type'] = $businessType;

$businessConfig = function_exists('getBusinessConfig') ? getBusinessConfig($businessType) : ['label' => $businessType === 'service' ? 'Serviços' : 'Varejo', 'icon' => 'solar:shop-bold'];
$kpiConfig = function_exists('getDashboardKPIs') ? getDashboardKPIs($businessType) : [];
$primaryAction = function_exists('getPrimaryAction') ? getPrimaryAction($businessType) : [];

// FILTRO DE PERÍODO & SERVICE LAYER
require_once __DIR__ . '/includes/services/DashboardService.php';

$dashboardService = new DashboardService($pdo, $storeId);
$period = $_GET['period'] ?? 'today';
$dateRange = $dashboardService->getDateRange($period, $_GET['from'] ?? null, $_GET['to'] ?? null);

$dateFrom = $dateRange['from'];
$dateTo = $dateRange['to'];
$periodLabel = $dateRange['label'];

// Fetch Data
if ($businessType === 'service') {
    $kpis = $dashboardService->getServiceKPIs($dateFrom, $dateTo);
    $appointmentsToday = $kpis['appointments_today'];
    $revenueToday = $kpis['revenue_today'];
    $totalClients = $kpis['clients_active'];
    $pendingAppointments = $kpis['pending_appointments'];
    
    $nextAppointments = $dashboardService->getNextAppointments(3);

    $kpiValues = [
        'appointments_today' => $appointmentsToday,
        'revenue_today' => 'R$ ' . number_format($revenueToday, 0, ',', '.'),
        'clients_active' => $totalClients,
        'next_appointment' => $pendingAppointments
    ];
} else {
    $kpis = $dashboardService->getRetailKPIs($dateFrom, $dateTo);
    $ordersPending = $kpis['orders_pending'];
    $revenueToday = $kpis['revenue_today']; // Note: revenue key matches service for simplicity in vars
    $lowStock = $kpis['products_low_stock'];
    $visitorsToday = $kpis['visitors_today'];

    $recentOrders = $dashboardService->getRecentOrders(3);

    $kpiValues = [
        'orders_pending' => $ordersPending,
        'revenue_today' => 'R$ ' . number_format($revenueToday, 0, ',', '.'),
        'products_low_stock' => $lowStock,
        'visitors_today' => $visitorsToday
    ];
}

$totalItems = $dashboardService->getTotalItems($businessType);
$trialDaysLeft = $dashboardService->getTrialDaysLeft($store);


// $trialDaysLeft is now calculated by DashboardService

$pageTitle = 'Dashboard';
include __DIR__ . '/includes/dashboard-header.php';
?>

<?php include __DIR__ . '/includes/responsive-styles.php'; ?>

<link rel="stylesheet" href="/assets/css/pages/dashboard-generic.css">

<main class="main-content">
    <div class="page-header page-header-flex">
        <div>
            <h1><iconify-icon icon="solar:home-2-bold"></iconify-icon> Dashboard</h1>
            <p>Bem-vindo de volta, <?php echo htmlspecialchars(explode(' ', $user['name'])[0]); ?>!</p>
        </div>
    </div>

    <?php if (($store['status'] ?? '') === 'trial' && $trialDaysLeft > 0): ?>
    <div class="alert" style="background:linear-gradient(135deg,rgba(245,158,11,.2) 0%,rgba(217,119,6,.1) 100%);border:1px solid rgba(245,158,11,.3)">
        <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:1rem">
            <div style="display:flex;align-items:center;gap:.75rem">
                <iconify-icon icon="solar:clock-circle-bold" style="font-size:1.5rem;color:#F59E0B"></iconify-icon>
                <div><strong>Período de teste</strong> - Restam <?php echo $trialDaysLeft; ?> dias do seu trial gratuito</div>
            </div>
            <a href="/pages/assinatura.php" class="btn btn-primary">Assinar agora</a>
        </div>
    </div>
    <?php endif; ?>

    <!-- FILTRO DE PERÍODO - RESPONSIVO -->
    <?php 
    // Variáveis esperadas pelo componente: $period, $periodLabel, $dateFrom, $dateTo
    include __DIR__ . '/includes/components/filter-period.php'; 
    ?>

    <!-- KPIs Dinâmicos -->
    <div class="stats-grid">
        <?php if (!empty($kpiConfig)): ?>
            <?php foreach ($kpiConfig as $kpi): 
                $kpi_icon = $kpi['icon'];
                $kpi_value = $kpiValues[$kpi['key']] ?? 0;
                $kpi_label = $kpi['label'];
                $kpi_color = $kpi['color'];
                include __DIR__ . '/includes/components/stat-card.php';
            endforeach; ?>
        <?php else: ?>
            <?php if ($businessType === 'service'): ?>
                <?php
                // Agendamentos
                $kpi_icon = 'solar:calendar-bold';
                $kpi_value = $appointmentsToday;
                $kpi_label = 'Agendamentos';
                $kpi_color = ''; // default
                $kpi_bg_color = ''; 
                $kpi_text_color = '';
                include __DIR__ . '/includes/components/stat-card.php';

                // Receita
                $kpi_icon = 'solar:wallet-money-bold';
                $kpi_value = 'R$ ' . number_format($revenueToday, 0, ',', '.');
                $kpi_label = 'Receita';
                $kpi_bg_color = 'rgba(34,197,94,.1)';
                $kpi_text_color = '#22C55E';
                include __DIR__ . '/includes/components/stat-card.php';

                // Clientes
                $kpi_icon = 'solar:users-group-rounded-bold';
                $kpi_value = $totalClients;
                $kpi_label = 'Clientes';
                $kpi_bg_color = 'rgba(59,130,246,.1)';
                $kpi_text_color = '#3B82F6';
                include __DIR__ . '/includes/components/stat-card.php';

                // Pendentes
                $kpi_icon = 'solar:clock-circle-bold';
                $kpi_value = $pendingAppointments;
                $kpi_label = 'Pendentes';
                $kpi_bg_color = 'rgba(168,85,247,.1)';
                $kpi_text_color = '#A855F7';
                include __DIR__ . '/includes/components/stat-card.php';
                ?>
            <?php else: ?>
                <?php
                // Pedidos Pendentes
                $kpi_icon = 'solar:bag-4-bold';
                $kpi_value = $ordersPending;
                $kpi_label = 'Pedidos Pendentes';
                $kpi_color = '';
                $kpi_bg_color = '';
                $kpi_text_color = '';
                include __DIR__ . '/includes/components/stat-card.php';

                // Receita
                $kpi_icon = 'solar:wallet-money-bold';
                $kpi_value = 'R$ ' . number_format($revenueToday, 0, ',', '.');
                $kpi_label = 'Receita';
                $kpi_bg_color = 'rgba(34,197,94,.1)';
                $kpi_text_color = '#22C55E';
                include __DIR__ . '/includes/components/stat-card.php';

                // Estoque Baixo (Link)
                $kpi_icon = 'solar:box-bold';
                $kpi_value = $lowStock;
                $kpi_label = 'Estoque Baixo';
                $kpi_bg_color = 'rgba(245,158,11,.1)';
                $kpi_text_color = '#F59E0B';
                $kpi_link = '/pages/estoque.php?search=&category=&filter=low';
                include __DIR__ . '/includes/components/stat-card.php';
                // Reset link for next includes
                $kpi_link = null;

                // Visitantes
                $kpi_icon = 'solar:eye-bold';
                $kpi_value = $visitorsToday;
                $kpi_label = 'Visitantes';
                $kpi_bg_color = 'rgba(59,130,246,.1)';
                $kpi_text_color = '#3B82F6';
                include __DIR__ . '/includes/components/stat-card.php';
                ?>
            <?php endif; ?>
        <?php endif; ?>
    </div>

    <!-- Cards Grid -->
    <div class="dashboard-grid">
        <?php if ($businessType === 'service'): ?>
        <div class="card">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1.5rem;flex-wrap:wrap;gap:.5rem">
                <h3 style="font-size:1.1rem;display:flex;align-items:center;gap:.5rem">
                    <iconify-icon icon="solar:calendar-bold" style="color:var(--primary)"></iconify-icon>
                    Próximos Agendamentos
                </h3>
                <a href="/pages/agendamentos.php" style="color:var(--primary);text-decoration:none;font-size:.85rem">Ver todos</a>
            </div>
            <?php if (empty($nextAppointments)): ?>
            <?php 
            $empty_icon = 'solar:calendar-minimalistic-bold';
            $empty_message = 'Nenhum agendamento próximo';
            include __DIR__ . '/includes/components/empty-state.php'; 
            ?>
            <?php else: ?>
            <div style="display:flex;flex-direction:column;gap:.75rem">
                <?php foreach ($nextAppointments as $apt): ?>
                <div class="appointment-item">
                    <div class="appointment-time">
                        <div class="time"><?php echo date('H:i', strtotime($apt['appointment_date'])); ?></div>
                        <div class="date"><?php echo date('d/m', strtotime($apt['appointment_date'])); ?></div>
                    </div>
                    <div class="appointment-info">
                        <div class="name"><?php echo htmlspecialchars($apt['client_name'] ?? 'Cliente'); ?></div>
                        <div class="service"><?php echo htmlspecialchars($apt['service_name'] ?? 'Serviço'); ?></div>
                    </div>
                    <?php
                    $statusColors = ['pending' => 'badge-warning', 'confirmed' => 'badge-success', 'completed' => 'badge-info', 'cancelled' => 'badge-secondary'];
                    $statusLabels = ['pending' => 'Pendente', 'confirmed' => 'Confirmado', 'completed' => 'Concluído', 'cancelled' => 'Cancelado'];
                    $status = $apt['status'] ?? 'pending';
                    ?>
                    <span class="badge <?php echo $statusColors[$status] ?? 'badge-secondary'; ?>"><?php echo $statusLabels[$status] ?? 'Pendente'; ?></span>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
        <?php else: ?>
        <div class="card">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1.5rem;flex-wrap:wrap;gap:.5rem">
                <h3 style="font-size:1.1rem;display:flex;align-items:center;gap:.5rem">
                    <iconify-icon icon="solar:clipboard-list-bold" style="color:var(--primary)"></iconify-icon>
                    Últimos Pedidos
                </h3>
                <a href="/pages/pedidos.php" style="color:var(--primary);text-decoration:none;font-size:.85rem">Ver todos</a>
            </div>
            <?php if (empty($recentOrders)): ?>
            <?php 
            $empty_icon = 'solar:clipboard-list-bold';
            $empty_message = 'Nenhum pedido no período';
            include __DIR__ . '/includes/components/empty-state.php'; 
            ?>
            <?php else: ?>
            <div style="display:flex;flex-direction:column;gap:.75rem">
                <?php foreach ($recentOrders as $order): ?>
                <a href="/pages/pedidos/ver.php?id=<?php echo $order['id']; ?>" class="order-item" style="text-decoration:none;color:inherit;display:flex;">
                    <div class="order-id">
                        <div class="id">#<?php echo $order['id']; ?></div>
                        <div class="date"><?php echo date('d/m', strtotime($order['created_at'])); ?></div>
                    </div>
                    <div class="order-info">
                        <div class="name"><?php echo htmlspecialchars($order['client_name'] ?? $order['customer_name'] ?? 'Cliente'); ?></div>
                        <div class="total">R$ <?php echo number_format($order['total_amount'] ?? $order['total'] ?? 0, 2, ',', '.'); ?></div>
                    </div>
                    <?php
                    $statusColors = ['pending' => 'badge-warning', 'awaiting_payment' => 'badge-warning', 'sent_whatsapp' => 'badge-info', 'confirmed' => 'badge-primary', 'paid' => 'badge-success', 'preparing' => 'badge-info', 'shipped' => 'badge-primary', 'delivered' => 'badge-success', 'completed' => 'badge-success', 'cancelled' => 'badge-secondary', 'canceled' => 'badge-secondary', 'expired' => 'badge-secondary'];
                    $statusLabels = ['pending' => 'Pendente', 'awaiting_payment' => 'Aguard. Pagto', 'sent_whatsapp' => 'WhatsApp', 'confirmed' => 'Confirmado', 'paid' => 'Pago', 'preparing' => 'Preparando', 'shipped' => 'Enviado', 'delivered' => 'Entregue', 'completed' => 'Concluído', 'cancelled' => 'Cancelado', 'canceled' => 'Cancelado', 'expired' => 'Expirado'];
                    $status = $order['status'] ?? 'pending';
                    ?>
                    <span class="badge <?php echo $statusColors[$status] ?? 'badge-secondary'; ?>"><?php echo $statusLabels[$status] ?? 'Pendente'; ?></span>
                </a>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <div class="card">
            <div style="margin-bottom:1.5rem">
                <h3 style="font-size:1.1rem;display:flex;align-items:center;gap:.5rem">
                    <iconify-icon icon="solar:bolt-bold" style="color:var(--primary)"></iconify-icon>
                    Ações Rápidas
                </h3>
            </div>
            <div class="quick-actions-grid">
                <?php if ($businessType === 'service'): ?>
                <a href="/pages/agendamentos.php?action=new" class="quick-action">
                    <iconify-icon icon="solar:calendar-add-bold"></iconify-icon>
                    <span>Novo Agendamento</span>
                </a>
                <a href="#" onclick="openClientModal();return false" class="quick-action">
                    <iconify-icon icon="solar:user-plus-bold"></iconify-icon>
                    <span>Novo Cliente</span>
                </a>
                <a href="/pages/servicos.php" class="quick-action">
                    <iconify-icon icon="solar:scissors-bold"></iconify-icon>
                    <span>Novo Serviço</span>
                </a>
                <?php else: ?>
                <a href="/pages/produtos/novo.php" class="quick-action">
                    <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                    <span>Novo Produto</span>
                </a>
                <a href="/pages/pedidos.php?action=new" class="quick-action">
                    <iconify-icon icon="solar:clipboard-add-bold"></iconify-icon>
                    <span>Novo Pedido</span>
                </a>
                <a href="#" onclick="openClientModal();return false" class="quick-action">
                    <iconify-icon icon="solar:user-plus-bold"></iconify-icon>
                    <span>Novo Cliente</span>
                </a>
                <?php endif; ?>
                <a href="<?php echo get_store_url($store); ?>" target="_blank" class="quick-action">
                    <iconify-icon icon="solar:eye-bold"></iconify-icon>
                    <span>Ver Loja</span>
                </a>
            </div>
        </div>
    </div>

    <div class="card" style="margin-top:1.5rem">
        <div style="margin-bottom:1.5rem">
            <h3 style="font-size:1.1rem;display:flex;align-items:center;gap:.5rem">
                <iconify-icon icon="solar:shop-bold" style="color:var(--primary)"></iconify-icon>
                Resumo da Loja
            </h3>
        </div>
        <div class="store-summary-grid">
            <div class="summary-item">
                <div class="label"><iconify-icon icon="solar:shop-2-bold"></iconify-icon> Nome da Loja</div>
                <div class="value"><?php echo htmlspecialchars($store['name']); ?></div>
            </div>
            <div class="summary-item">
                <div class="label"><iconify-icon icon="<?php echo $businessConfig['icon']; ?>"></iconify-icon> Tipo de Negócio</div>
                <div class="value"><?php echo $businessConfig['label']; ?></div>
            </div>
            <div class="summary-item">
                <div class="label"><iconify-icon icon="<?php echo $businessType === 'service' ? 'solar:scissors-bold' : 'solar:bag-bold'; ?>"></iconify-icon> <?php echo $businessType === 'service' ? 'Serviços Ativos' : 'Produtos Ativos'; ?></div>
                <div class="value"><?php echo $totalItems; ?> <?php echo $businessType === 'service' ? 'serviços' : 'produtos'; ?></div>
            </div>
            <div class="summary-item">
                <div class="label"><iconify-icon icon="solar:card-bold"></iconify-icon> Plano</div>
                <div class="value"><span class="badge badge-primary"><?php echo htmlspecialchars($store['plan_name'] ?? 'Gratuito'); ?></span></div>
            </div>
        </div>
    </div>
</main>

<link rel="stylesheet" href="/assets/css/pages/dashboard-generic.css">

<div id="customerModal" class="modal-overlay">
    <div class="modal-content card">
        <div class="modal-header">
            <h2 class="modal-title">Novo Cliente</h2>
            <button onclick="closeClientModal()" class="modal-close-btn"><iconify-icon icon="solar:close-circle-bold"></iconify-icon></button>
        </div>
        <form method="POST" action="/pages/clientes.php" id="customerForm">
            <input type="hidden" name="action" value="add">
            <div class="form-group">
                <label class="form-label">Nome Completo *</label>
                <input type="text" name="name" id="customerName" class="form-input" placeholder="Nome do cliente" required>
            </div>
            <div class="form-grid-2">
                <div class="form-group">
                    <label class="form-label">E-mail</label>
                    <input type="email" name="email" id="customerEmail" class="form-input" placeholder="email@exemplo.com">
                </div>
                <div class="form-group">
                    <label class="form-label">Telefone</label>
                    <input type="tel" name="phone" id="customerPhone" class="form-input" placeholder="(00) 00000-0000">
                </div>
            </div>
            <div class="modal-actions">
                <button type="button" class="btn btn-secondary" onclick="closeClientModal()">Cancelar</button>
                <button type="submit" class="btn btn-primary"><iconify-icon icon="solar:check-circle-bold"></iconify-icon><span>Salvar</span></button>
            </div>
        </form>
    </div>
</div>

<script>
function openClientModal(){document.getElementById('customerModal').style.display='flex';document.body.style.overflow='hidden'}
function closeClientModal(){document.getElementById('customerModal').style.display='none';document.body.style.overflow=''}
document.getElementById('customerModal')?.addEventListener('click',function(e){if(e.target===this)closeClientModal()});
document.addEventListener('keydown',function(e){if(e.key==='Escape')closeClientModal()});
</script>

<?php include __DIR__ . '/includes/dashboard-footer.php'; ?>
