<?php
/**
 * Página de Clientes - MontaLoja SaaS
 * Versão Responsiva (funciona para Loja e Barbearia)
 */
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);

// Processar ações
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add') {
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $cpf = trim($_POST['cpf'] ?? '');
        $birthdate = $_POST['birthdate'] ?? null;
        $address = trim($_POST['address'] ?? '');
        $notes = trim($_POST['notes'] ?? '');
        
        if ($name) {
            $stmt = $pdo->prepare("INSERT INTO customers (store_id, name, email, phone, cpf, birthdate, address, notes, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())");
            $stmt->execute([$storeId, $name, $email, $phone, $cpf, $birthdate ?: null, $address, $notes]);
            $message = 'Cliente adicionado com sucesso!';
            $messageType = 'success';
        }
    } elseif ($action === 'edit') {
        $id = intval($_POST['id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $cpf = trim($_POST['cpf'] ?? '');
        $birthdate = $_POST['birthdate'] ?? null;
        $address = trim($_POST['address'] ?? '');
        $notes = trim($_POST['notes'] ?? '');
        
        if ($id && $name) {
            $stmt = $pdo->prepare("UPDATE customers SET name = ?, email = ?, phone = ?, cpf = ?, birthdate = ?, address = ?, notes = ? WHERE id = ? AND store_id = ?");
            $stmt->execute([$name, $email, $phone, $cpf, $birthdate ?: null, $address, $notes, $id, $storeId]);
            $message = 'Cliente atualizado com sucesso!';
            $messageType = 'success';
        }
    } elseif ($action === 'delete' && isset($_POST['id'])) {
        $stmt = $pdo->prepare("DELETE FROM customers WHERE id = ? AND store_id = ?");
        $stmt->execute([$_POST['id'], $storeId]);
        $message = 'Cliente removido!';
        $messageType = 'success';
    }
}

// Filtro de busca
$search = trim($_GET['search'] ?? '');

// Buscar clientes
$sql = "SELECT * FROM customers WHERE store_id = ?";
$params = [$storeId];

if ($search) {
    $sql .= " AND (name LIKE ? OR email LIKE ? OR phone LIKE ?)";
    $searchTerm = "%$search%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

$sql .= " ORDER BY name ASC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$customers = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

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


<style>
/* ========================================
   ESTILOS ESPECÍFICOS - PÁGINA CLIENTES
   (Estilos reutilizáveis movidos para dashboard-components.css)
   ======================================== */

/* Customer Info */
.customer-name {
    font-weight: 600;
    color: var(--text-primary);
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 0.25rem;
}

.customer-meta {
    font-size: 0.85rem;
    color: var(--text-muted);
    margin-top: 0.25rem;
}

.customer-contact {
    font-size: 0.9rem;
}

.customer-contact > div {
    margin-bottom: 0.25rem;
}

.customer-contact > div:last-child {
    margin-bottom: 0;
}

.customer-contact iconify-icon {
    color: var(--primary);
    margin-right: 0.35rem;
}

.customer-contact a {
    color: var(--primary);
    text-decoration: none;
    transition: opacity 0.2s;
}

.customer-contact a:hover {
    opacity: 0.8;
}

/* Customer Notes */
.customer-notes {
    padding: 0 1rem;
    margin-bottom: 1rem;
}

.customer-notes-text {
    font-size: 0.85rem;
    color: var(--text-muted);
    font-style: italic;
}

/* WhatsApp Button */
.btn-whatsapp {
    color: #25D366 !important;
}

.btn-whatsapp:hover {
    background: rgba(37, 211, 102, 0.1) !important;
}

/* Tabela - Melhorias */
.data-table .customer-cell {
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.data-table .customer-info {
    flex: 1;
    min-width: 0;
}

/* Mobile Card - Ajustes específicos clientes */
.mobile-card .customer-header-info {
    flex: 1;
    min-width: 0;
}

.mobile-card-title {
    font-weight: 600;
    font-size: 1rem;
    color: var(--text-primary);
    display: flex;
    align-items: center;
    gap: 0.25rem;
}

.mobile-card-subtitle {
    font-size: 0.85rem;
    color: var(--text-muted);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* Empty state */
.empty-state .btn {
    margin-top: 1rem;
}
</style>

    <main class="main-content">
        <div class="page-header page-header-flex">
            <div>
                <h1><iconify-icon icon="solar:users-group-rounded-bold"></iconify-icon> Clientes</h1>
                <p>Gerencie sua base de clientes</p>
            </div>
            <button class="btn btn-primary" onclick="openAddModal()">
                <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                <span>Novo Cliente</span>
            </button>
        </div>
        
        <?php if ($message): ?>
        <div class="alert alert-<?php echo $messageType; ?>">
            <iconify-icon icon="<?php echo $messageType === 'success' ? 'solar:check-circle-bold' : 'solar:danger-circle-bold'; ?>"></iconify-icon>
            <?php echo $message; ?>
        </div>
        <?php endif; ?>
        
        <!-- Filtro de busca -->
        <form method="GET" class="filter-bar">
            <div class="search-box">
                <input type="text" name="search" class="form-input" placeholder="Buscar por nome, email ou telefone..." value="<?php echo htmlspecialchars($search); ?>">
            </div>
            <button type="submit" class="btn btn-primary">
                <iconify-icon icon="solar:magnifer-bold"></iconify-icon>
                Buscar
            </button>
            <?php if ($search): ?>
            <a href="clientes.php" class="btn btn-secondary">Limpar</a>
            <?php endif; ?>
        </form>
        
        <!-- Stats -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon">
                    <iconify-icon icon="solar:users-group-rounded-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?php echo count($customers); ?></span>
                    <span class="stat-label">Total de Clientes</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon stat-success">
                    <iconify-icon icon="solar:calendar-add-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <?php
                    $thisMonth = count(array_filter($customers, function($c) {
                        return date('Y-m', strtotime($c['created_at'])) === date('Y-m');
                    }));
                    ?>
                    <span class="stat-value"><?php echo $thisMonth; ?></span>
                    <span class="stat-label">Novos Este Mês</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon stat-purple">
                    <iconify-icon icon="solar:user-check-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <?php $withAccount = count(array_filter($customers, fn($c) => !empty($c['password']))); ?>
                    <span class="stat-value"><?php echo $withAccount; ?></span>
                    <span class="stat-label">Com Conta Online</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon stat-blue">
                    <iconify-icon icon="solar:phone-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <?php $withPhone = count(array_filter($customers, fn($c) => !empty($c['phone']))); ?>
                    <span class="stat-value"><?php echo $withPhone; ?></span>
                    <span class="stat-label">Com Telefone</span>
                </div>
            </div>
        </div>
        
        <?php if (empty($customers)): ?>
        <div class="empty-state">
            <iconify-icon icon="solar:users-group-rounded-bold"></iconify-icon>
            <h3>Nenhum cliente cadastrado</h3>
            <p>Adicione seu primeiro cliente para começar.</p>
            <button class="btn btn-primary" onclick="openAddModal()">
                <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                Adicionar Cliente
            </button>
        </div>
        <?php else: ?>
        
        <!-- Versão Cards (Mobile) -->
        <div class="mobile-cards">
            <?php foreach ($customers as $customer): ?>
            <div class="mobile-card">
                <div class="mobile-card-header">
                    <div class="customer-avatar">
                        <?php echo strtoupper(substr($customer['name'], 0, 2)); ?>
                        <?php if (!empty($customer['password'])): ?>
                        <span class="online-badge">
                            <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                        </span>
                        <?php endif; ?>
                    </div>
                    <div class="customer-header-info">
                        <div class="mobile-card-title">
                            <?php echo htmlspecialchars($customer['name']); ?>
                            <?php if (!empty($customer['password'])): ?>
                            <iconify-icon icon="solar:verified-check-bold" style="color: #22C55E; font-size: 1rem; margin-left: 4px;" title="Conta Online"></iconify-icon>
                            <?php endif; ?>
                        </div>
                        <?php if ($customer['email']): ?>
                        <div class="mobile-card-subtitle">
                            <?php echo htmlspecialchars($customer['email']); ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="mobile-card-info">
                    <div class="mobile-card-info-item">
                        <div class="mobile-card-info-label">Telefone</div>
                        <div class="mobile-card-info-value">
                            <?php if ($customer['phone']): ?>
                            <a href="tel:<?php echo $customer['phone']; ?>">
                                <?php echo htmlspecialchars($customer['phone']); ?>
                            </a>
                            <?php else: ?>
                            -
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="mobile-card-info-item">
                        <div class="mobile-card-info-label">Cadastro</div>
                        <div class="mobile-card-info-value"><?php echo date('d/m/Y', strtotime($customer['created_at'])); ?></div>
                    </div>
                </div>
                
                <?php if ($customer['notes']): ?>
                <div class="customer-notes">
                    <div class="customer-notes-text">
                        <em><?php echo htmlspecialchars($customer['notes']); ?></em>
                    </div>
                </div>
                <?php endif; ?>
                
                <div class="mobile-card-actions">
                    <?php if ($customer['phone']): ?>
                    <a href="https://wa.me/55<?php echo preg_replace('/\D/', '', $customer['phone']); ?>" target="_blank" class="btn btn-secondary btn-sm btn-whatsapp">
                        <iconify-icon icon="mdi:whatsapp"></iconify-icon>
                    </a>
                    <?php endif; ?>
                    <button type="button" class="btn btn-secondary btn-sm" style="flex: 1;" onclick='openEditModal(<?php echo json_encode($customer); ?>)'>
                        <iconify-icon icon="solar:pen-bold"></iconify-icon>
                        Editar
                    </button>
                    <form method="POST" onsubmit="return confirm('Remover este cliente?');">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" value="<?php echo $customer['id']; ?>">
                        <button type="submit" class="btn btn-secondary btn-sm" style="color: var(--error);">
                            <iconify-icon icon="solar:trash-bin-2-bold"></iconify-icon>
                        </button>
                    </form>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        
        <!-- Versão Tabela (Desktop) -->
        <div class="card desktop-table">
            <div>
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>Cliente</th>
                            <th>Contato</th>
                            <th class="hide-tablet">CPF</th>
                            <th class="hide-tablet">Cadastrado em</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($customers as $customer): ?>
                        <tr>
                            <td>
                                <div class="customer-cell">
                                    <div class="customer-avatar customer-avatar-sm">
                                        <?php echo strtoupper(substr($customer['name'], 0, 2)); ?>
                                        <?php if (!empty($customer['password'])): ?>
                                        <span class="online-badge online-badge-sm">
                                            <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                                        </span>
                                        <?php endif; ?>
                                    </div>
                                    <div>
                                        <div class="customer-name">
                                            <?php echo htmlspecialchars($customer['name']); ?>
                                            <?php if (!empty($customer['password'])): ?>
                                            <span class="inline-badge">
                                                <iconify-icon icon="solar:user-check-bold"></iconify-icon>
                                                Conta Online
                                            </span>
                                            <?php endif; ?>
                                        </div>
                                        <?php if (!empty($customer['last_login'])): ?>
                                        <div class="customer-meta">Último login: <?php echo date('d/m/Y H:i', strtotime($customer['last_login'])); ?></div>
                                        <?php elseif ($customer['notes']): ?>
                                        <div class="customer-notes-text"><?php echo htmlspecialchars($customer['notes']); ?></div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div class="customer-contact">
                                    <?php if ($customer['email']): ?>
                                    <div><iconify-icon icon="solar:letter-bold"></iconify-icon> <?php echo htmlspecialchars($customer['email']); ?></div>
                                    <?php endif; ?>
                                    <?php if ($customer['phone']): ?>
                                    <div><iconify-icon icon="solar:phone-bold"></iconify-icon> <?php echo htmlspecialchars($customer['phone']); ?></div>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td class="hide-tablet"><?php echo htmlspecialchars($customer['cpf'] ?? '-'); ?></td>
                            <td class="hide-tablet"><?php echo date('d/m/Y', strtotime($customer['created_at'])); ?></td>
                            <td>
                                <div class="actions-cell">
                                    <?php if ($customer['phone']): ?>
                                    <a href="https://wa.me/55<?php echo preg_replace('/\D/', '', $customer['phone']); ?>" target="_blank" class="btn btn-secondary btn-sm" title="WhatsApp" style="color: #25D366;">
                                        <iconify-icon icon="mdi:whatsapp"></iconify-icon>
                                    </a>
                                    <?php endif; ?>
                                    <button type="button" class="btn btn-secondary btn-sm" title="Editar" onclick='openEditModal(<?php echo json_encode($customer); ?>)'>
                                        <iconify-icon icon="solar:pen-bold"></iconify-icon>
                                    </button>
                                    <form method="POST" style="display: inline;" onsubmit="return confirm('Remover este cliente?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?php echo $customer['id']; ?>">
                                        <button type="submit" class="btn btn-secondary btn-sm" style="color: var(--error);">
                                            <iconify-icon icon="solar:trash-bin-2-bold"></iconify-icon>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>
    </main>
    
    <!-- Modal Adicionar/Editar -->
    <div id="customerModal" class="modal-overlay">
        <div class="modal-content card">
            <div class="modal-header">
                <h2 id="modalTitle" class="modal-title">Novo Cliente</h2>
                <button onclick="closeModal()" class="modal-close-btn">
                    <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
                </button>
            </div>
            <form method="POST" id="customerForm">
                <input type="hidden" name="action" id="formAction" value="add">
                <input type="hidden" name="id" id="customerId" value="">
                
                <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="form-grid-2">
                    <div class="form-group">
                        <label class="form-label">CPF</label>
                        <input type="text" name="cpf" id="customerCpf" class="form-input" placeholder="000.000.000-00">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Data de Nascimento</label>
                        <input type="date" name="birthdate" id="customerBirthdate" class="form-input">
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Endereço</label>
                    <input type="text" name="address" id="customerAddress" class="form-input" placeholder="Endereço completo">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Observações</label>
                    <textarea name="notes" id="customerNotes" class="form-input" rows="2" placeholder="Observações sobre o cliente..."></textarea>
                </div>
                
                <div class="modal-actions">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancelar</button>
                    <button type="submit" class="btn btn-primary">
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                        <span id="submitBtnText">Salvar</span>
                    </button>
                </div>
            </form>
        </div>
    </div>

<script>
function openAddModal() {
    document.getElementById('modalTitle').textContent = 'Novo Cliente';
    document.getElementById('formAction').value = 'add';
    document.getElementById('customerId').value = '';
    document.getElementById('customerName').value = '';
    document.getElementById('customerEmail').value = '';
    document.getElementById('customerPhone').value = '';
    document.getElementById('customerCpf').value = '';
    document.getElementById('customerBirthdate').value = '';
    document.getElementById('customerAddress').value = '';
    document.getElementById('customerNotes').value = '';
    document.getElementById('submitBtnText').textContent = 'Salvar';
    document.getElementById('customerModal').style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

function openEditModal(customer) {
    document.getElementById('modalTitle').textContent = 'Editar Cliente';
    document.getElementById('formAction').value = 'edit';
    document.getElementById('customerId').value = customer.id;
    document.getElementById('customerName').value = customer.name;
    document.getElementById('customerEmail').value = customer.email || '';
    document.getElementById('customerPhone').value = customer.phone || '';
    document.getElementById('customerCpf').value = customer.cpf || '';
    document.getElementById('customerBirthdate').value = customer.birthdate || '';
    document.getElementById('customerAddress').value = customer.address || '';
    document.getElementById('customerNotes').value = customer.notes || '';
    document.getElementById('submitBtnText').textContent = 'Atualizar';
    document.getElementById('customerModal').style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

// Função closeModal e listeners de evento removidos. 
// Agora controlados globalmente por dashboard-utils.js
</script>

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