<?php
session_start();
require_once '../config/db.php';

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

$user_id = $_SESSION['user_id'];
$edit_mode = false;
$cliente_para_editar = null;
$success_message = '';
$error_message = '';

// --- LÓGICA DE EXCLUSÃO ---
if (isset($_GET['delete'])) {
    $cliente_id_para_deletar = $_GET['delete'];

    // Antes de deletar, verifica se o cliente não tem fiados associados
    $stmt_check = $pdo->prepare("SELECT COUNT(*) FROM fiados WHERE customer_id = ? AND user_id = ?");
    $stmt_check->execute([$cliente_id_para_deletar, $user_id]);
    $fiados_count = $stmt_check->fetchColumn();

    if ($fiados_count > 0) {
        // Se houver fiados, impede a exclusão e define uma mensagem de erro
        $_SESSION['error_message'] = 'Não é possível excluir este cliente, pois ele possui contas (fiados) associadas. Remova as contas primeiro.';
    } else {
        // Se não houver fiados, prossegue com a exclusão
        $stmt = $pdo->prepare("DELETE FROM client_customers WHERE id = ? AND user_id = ?");
        $stmt->execute([$cliente_id_para_deletar, $user_id]);
        $_SESSION['success_message'] = 'Cliente excluído com sucesso!';
    }

    header("Location: clientes.php");
    exit;
}
// --- FIM DA LÓGICA DE EXCLUSÃO ---


// --- LÓGICA DE EDIÇÃO ---
if (isset($_GET['edit'])) {
    $edit_mode = true;
    $cliente_id = $_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM client_customers WHERE id = ? AND user_id = ?");
    $stmt->execute([$cliente_id, $user_id]);
    $cliente_para_editar = $stmt->fetch();
    if (!$cliente_para_editar) {
        $edit_mode = false;
    }
}

// --- LÓGICA DE CADASTRO E ATUALIZAÇÃO (POST) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);
    $phone = trim($_POST['phone']);
    $cpf = trim($_POST['cpf']);

    if (isset($_POST['customer_id']) && !empty($_POST['customer_id'])) {
        $customer_id = $_POST['customer_id'];
        $sql = "UPDATE client_customers SET name = ?, phone = ?, cpf = ? WHERE id = ? AND user_id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$name, $phone, $cpf, $customer_id, $user_id]);
        $_SESSION['success_message'] = 'Cliente atualizado com sucesso!';
    } else {
        $sql = "INSERT INTO client_customers (user_id, name, phone, cpf) VALUES (?, ?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$user_id, $name, $phone, $cpf]);
        $_SESSION['success_message'] = 'Cliente cadastrado com sucesso!';
    }
    
    header("Location: clientes.php");
    exit;
}

// Pega as mensagens da sessão e depois as limpa
if (isset($_SESSION['success_message'])) {
    $success_message = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}
if (isset($_SESSION['error_message'])) {
    $error_message = $_SESSION['error_message'];
    unset($_SESSION['error_message']);
}

// --- LÓGICA DE LISTAGEM COMPLETA (SEM PESQUISA AQUI) ---
$stmt = $pdo->prepare("SELECT * FROM client_customers WHERE user_id = ? ORDER BY name ASC");
$stmt->execute([$user_id]);
$clientes = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Meus Clientes - Fiado Fácil</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <style>
        :root {
            --primary-color: #1876F2; --primary-dark: #1356b3; --primary-light: #eaf4ff;
            --secondary-color: #1bbf5c; --success-color: #10b981; --warning-color: #f59e0b;
            --danger-color: #ef4444; --danger-light: #fef2f2;
            --background-color: #f8fafc; --surface-color: #ffffff; --text-primary: #1e293b;
            --text-secondary: #64748b; --border-color: #e2e8f0;
            --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05 );
            --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
            --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
            --shadow-xl: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1);
            --gradient-primary: linear-gradient(135deg, #1876F2 0%, #1356b3 100%);
            --gradient-success: linear-gradient(135deg, #10b981 0%, #059669 100%);
            --gradient-warning: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            --gradient-danger: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            --gradient-background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
        }
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Inter', sans-serif; background: var(--gradient-background); color: var(--text-primary); line-height: 1.6; min-height: 100vh; }
        .sidebar { position: fixed; left: 0; top: 0; bottom: 0; width: 280px; background: var(--surface-color); border-right: 1px solid var(--border-color); display: flex; flex-direction: column; z-index: 1000; box-shadow: var(--shadow-xl); transition: transform 0.3s ease; }
        .sidebar .logo { padding: 32px 24px; font-size: 1.75rem; font-weight: 800; color: var(--primary-color); display: flex; align-items: center; gap: 12px; border-bottom: 1px solid var(--border-color); }
        .sidebar .logo i { font-size: 2rem; background: var(--gradient-primary); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
        .sidebar nav { flex: 1; padding: 24px 16px; }
        .sidebar nav a { display: flex; align-items: center; gap: 16px; color: var(--text-secondary); text-decoration: none; font-size: 0.95rem; font-weight: 500; padding: 14px 20px; margin: 4px 0; border-radius: 12px; transition: all 0.3s ease; position: relative; overflow: hidden; }
        .sidebar nav a:hover, .sidebar nav a.active { color: white; transform: translateX(4px); box-shadow: var(--shadow-md); }
        .sidebar nav a::before { content: ''; position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: var(--gradient-primary); opacity: 0; transition: opacity 0.3s ease; border-radius: 12px; }
        .sidebar nav a:hover::before, .sidebar nav a.active::before { opacity: 1; }
        .sidebar nav a i, .sidebar nav a span { position: relative; z-index: 1; }
        .sidebar .bottom { padding: 24px; border-top: 1px solid var(--border-color); }
        .sidebar .logout-link { display: flex; align-items: center; gap: 12px; color: var(--danger-color); font-weight: 600; text-decoration: none; padding: 12px 16px; border-radius: 12px; transition: all 0.3s ease; }
        .sidebar .logout-link:hover { background: var(--danger-light); transform: translateX(4px); }
        .main-content { margin-left: 280px; padding: 32px; min-height: 100vh; animation: fadeIn 0.6s ease-out; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
        .page-header { display: flex; align-items: center; gap: 16px; margin-bottom: 32px; padding-bottom: 24px; border-bottom: 1px solid var(--border-color); }
        .page-header .icon-wrapper { width: 56px; height: 56px; border-radius: 16px; display: flex; align-items: center; justify-content: center; background: var(--primary-light); }
        .page-header i { font-size: 1.75rem; color: var(--primary-color); }
        .page-header h2 { font-size: 2rem; font-weight: 700; }
        .content-grid { display: grid; grid-template-columns: 1fr 2fr; gap: 32px; align-items: start; }
        .form-card { background: var(--surface-color); border-radius: 20px; box-shadow: var(--shadow-md); padding: 32px; border: 1px solid var(--border-color); position: relative; animation: slideUp 0.6s ease-out; animation-delay: 0.1s; animation-fill-mode: both; }
        @keyframes slideUp { from { opacity: 0; transform: translateY(30px); } to { opacity: 1; transform: translateY(0); } }
        .form-card::before { content: ''; position: absolute; top: 0; left: 0; right: 0; height: 4px; background: var(--gradient-primary); }
        .form-card.edit-mode::before { background: var(--gradient-warning); }
        .form-card h3 { font-size: 1.25rem; font-weight: 700; margin-bottom: 24px; display: flex; align-items: center; gap: 12px; }
        .form-card h3 i { color: var(--primary-color); }
        .form-card.edit-mode h3 i { color: var(--warning-color); }
        .form-group { margin-bottom: 20px; }
        .form-card label { font-weight: 600; font-size: 0.95rem; margin-bottom: 8px; display: block; }
        .form-card input[type="text"] { width: 100%; padding: 14px 16px; border-radius: 12px; border: 2px solid var(--border-color); font-size: 1rem; transition: all 0.3s ease; }
        .form-card input[type="text"]:focus { border-color: var(--primary-color); box-shadow: 0 0 0 3px rgba(24, 118, 242, 0.1); }
        .submit-btn { background: var(--gradient-primary); color: white; font-weight: 600; font-size: 1rem; border: none; border-radius: 12px; padding: 16px 24px; cursor: pointer; transition: all 0.3s ease; width: 100%; display: flex; align-items: center; justify-content: center; gap: 8px; }
        .submit-btn.edit-btn { background: var(--gradient-warning); }
        .submit-btn:hover { transform: translateY(-2px); box-shadow: var(--shadow-lg); }
        .message-box { color: white; padding: 16px 20px; border-radius: 12px; margin-bottom: 24px; font-weight: 600; display: flex; align-items: center; gap: 8px; animation: slideDown 0.5s ease-out; }
        .success-message { background: var(--gradient-success); }
        .error-message { background: var(--gradient-danger); }
        @keyframes slideDown { from { opacity: 0; transform: translateY(-20px); } to { opacity: 1; transform: translateY(0); } }
        .table-card { background: var(--surface-color); border-radius: 20px; box-shadow: var(--shadow-md); border: 1px solid var(--border-color); animation: slideUp 0.6s ease-out; animation-delay: 0.2s; animation-fill-mode: both; overflow: hidden; }
        .table-header { padding: 24px 32px; border-bottom: 1px solid var(--border-color); background: var(--primary-light); display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px; }
        .table-header h3 { font-size: 1.25rem; font-weight: 700; color: var(--primary-color); margin: 0; display: flex; align-items: center; gap: 12px; }
        
        /* Estilo para a barra de pesquisa */
        .search-form { display: flex; flex-grow: 1; max-width: 300px; }
        .search-input { width: 100%; padding: 10px 16px; border-radius: 12px; border: 2px solid var(--border-color); font-size: 0.95rem; transition: all 0.3s ease; }
        .search-input:focus { border-color: var(--primary-color); box-shadow: 0 0 0 3px rgba(24, 118, 242, 0.1); }

        .table-container { overflow-x: auto; }
        .clientes-table { width: 100%; border-collapse: collapse; }
        .clientes-table th, .clientes-table td { padding: 16px 24px; text-align: left; border-bottom: 1px solid var(--border-color); }
        .clientes-table th { font-size: 0.9rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }
        .clientes-table tr:last-child td { border-bottom: none; }
        .clientes-table tbody tr:hover { background: var(--primary-light); }
        .actions-cell { display: flex; gap: 10px; align-items: center; }
        .action-btn { display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px; border-radius: 50%; text-decoration: none; transition: all 0.3s ease; font-size: 1rem; color: white; border: none; cursor: pointer; }
        .action-btn:hover { transform: scale(1.1); box-shadow: var(--shadow-md); }
        .whatsapp-btn { background: #25D366; }
        .edit-btn-table { background: var(--warning-color); }
        .delete-btn-table { background: var(--danger-color); }
        .empty-state { text-align: center; padding: 48px 24px; color: var(--text-secondary); }
        .empty-state i { font-size: 3rem; color: var(--border-color); margin-bottom: 16px; }
        .menu-toggle { display: none; }
        .overlay { display: none; }
        @media (max-width: 1200px) { .content-grid { grid-template-columns: 1fr; } }
        @media (max-width: 768px) {
            .sidebar { transform: translateX(-100%); width: 90%; max-width: 320px; z-index: 1000; }
            .sidebar.open { transform: translateX(0); }
            .main-content { margin-left: 0; padding: 20px 16px; }
            .menu-toggle { display: block; position: fixed; top: 20px; left: 20px; z-index: 1001; background: var(--surface-color); border: 1px solid var(--border-color); border-radius: 12px; padding: 12px; cursor: pointer; box-shadow: var(--shadow-md); color: var(--primary-color); font-size: 1.2rem; }
            .overlay { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.4); z-index: 999; }
            .overlay.active { display: block; }
            .table-header { flex-direction: column; align-items: stretch; }
            .search-form { width: 100%; max-width: none; }
        }
    </style>
</head>
<body>
    <button class="menu-toggle" id="menuToggle"><i class="fa-solid fa-bars"></i></button>
    <div class="overlay" id="overlay"></div>
    
    <aside class="sidebar" id="sidebar">
        <div class="logo"><i class="fa-solid fa-wallet"></i><span>Fiado Fácil</span></div>
        <nav>
            <a href="dashboard.php"><i class="fa-solid fa-house"></i><span>Painel</span></a>
            <a href="clientes.php" class="active"><i class="fa-solid fa-users"></i><span>Clientes</span></a>
            <a href="fiados.php"><i class="fa-solid fa-file-invoice-dollar"></i><span>Fiados</span></a>
            <a href="carne.php"><i class="fa-solid fa-file-pdf"></i><span>Carnê PDF</span></a>
            <a href="relatorios.php"><i class="fa-solid fa-chart-line"></i><span>Relatórios</span></a>
            <a href="configuracao.php"><i class="fa-solid fa-cog"></i><span>Configuração</span></a>
        </nav>
        <div class="bottom"><a href="logout.php" class="logout-link"><i class="fa-solid fa-right-from-bracket"></i><span>Sair</span></a></div>
    </aside>
    
    <div class="main-content">
        <div class="page-header">
            <div class="icon-wrapper"><i class="fa-solid fa-users"></i></div>
            <h2>Meus Clientes</h2>
        </div>
        
        <?php if (!empty($success_message)): ?>
            <div class="message-box success-message"><i class="fa-solid fa-check-circle"></i><?= htmlspecialchars($success_message) ?></div>
        <?php endif; ?>
        <?php if (!empty($error_message)): ?>
            <div class="message-box error-message"><i class="fa-solid fa-exclamation-triangle"></i><?= htmlspecialchars($error_message) ?></div>
        <?php endif; ?>
        
        <div class="content-grid">
            <div class="form-card <?= $edit_mode ? 'edit-mode' : '' ?>">
                <h3>
                    <i class="fa-solid <?= $edit_mode ? 'fa-user-edit' : 'fa-user-plus' ?>"></i>
                    <?= $edit_mode ? 'Editar Cliente' : 'Adicionar Cliente' ?>
                </h3>
                
                <form method="post" autocomplete="off">
                    <input type="hidden" name="customer_id" value="<?= $edit_mode ? $cliente_para_editar['id'] : '' ?>">
                    <div class="form-group">
                        <label for="name">Nome Completo</label>
                        <input type="text" name="name" id="name" placeholder="Digite o nome completo" required value="<?= $edit_mode ? htmlspecialchars($cliente_para_editar['name']) : '' ?>">
                    </div>
                    <div class="form-group">
                        <label for="phone">Telefone</label>
                        <input type="text" name="phone" id="phone" placeholder="(99) 99999-9999" value="<?= $edit_mode ? htmlspecialchars($cliente_para_editar['phone']) : '' ?>">
                    </div>
                    <div class="form-group">
                        <label for="cpf">CPF</label>
                        <input type="text" name="cpf" id="cpf" placeholder="000.000.000-00" value="<?= $edit_mode ? htmlspecialchars($cliente_para_editar['cpf']) : '' ?>">
                    </div>
                    <button type="submit" class="submit-btn <?= $edit_mode ? 'edit-btn' : '' ?>">
                        <i class="fa-solid <?= $edit_mode ? 'fa-save' : 'fa-user-plus' ?>"></i>
                        <?= $edit_mode ? 'Salvar Alterações' : 'Adicionar Cliente' ?>
                    </button>
                    <?php if ($edit_mode): ?>
                        <a href="clientes.php" style="display: block; text-align: center; margin-top: 15px; color: var(--text-secondary);">Cancelar Edição</a>
                    <?php endif; ?>
                </form>
            </div>
            
            <div class="table-card">
                <div class="table-header">
                    <h3><i class="fa-solid fa-list"></i>Lista de Clientes</h3>
                    <!-- Ação do formulário removida para evitar recarregamento -->
                    <form class="search-form">
                        <input type="text" id="searchInput" placeholder="Buscar por nome, telefone ou CPF..." class="search-input">
                    </form>
                </div>
                <div class="table-container">
                    <?php if (count($clientes) > 0): ?>
                        <table class="clientes-table">
                            <thead>
                                <tr><th>Nome</th><th>Telefone</th><th>CPF</th><th>Ações</th></tr>
                            </thead>
                            <tbody id="clientTableBody">
                                <?php foreach ($clientes as $c): ?>
                                <tr>
                                    <td><?=htmlspecialchars($c['name'])?></td>
                                    <td><?=htmlspecialchars($c['phone'])?></td>
                                    <td><?=htmlspecialchars($c['cpf'])?></td>
                                    <td class="actions-cell">
                                        <a href="clientes.php?edit=<?= $c['id'] ?>" title="Editar Cliente" class="action-btn edit-btn-table"><i class="fa-solid fa-pencil-alt"></i></a>
                                        <a href="clientes.php?delete=<?= $c['id'] ?>" title="Excluir Cliente" class="action-btn delete-btn-table" onclick="return confirmarExclusao('<?= htmlspecialchars(addslashes($c['name'])) ?>')">
                                            <i class="fa-solid fa-trash"></i>
                                        </a>
                                        <?php if (!empty($c['phone'])): ?>
                                            <a href="https://wa.me/55<?=preg_replace('/\D/','',$c['phone'] )?>" target="_blank" title="Enviar WhatsApp" class="action-btn whatsapp-btn"><i class="fa-brands fa-whatsapp"></i></a>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php else: ?>
                        <div class="empty-state">
                            <i class="fa-solid fa-users"></i>
                            <h4 id="emptyMessage">Nenhum cliente cadastrado</h4>
                            <p>Adicione seu primeiro cliente usando o formulário.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        function confirmarExclusao(nomeCliente) {
            return confirm("Tem certeza que deseja excluir o cliente '" + nomeCliente + "'?\n\nEsta ação não pode ser desfeita.");
        }

        // Menu mobile
        const menuToggle = document.getElementById('menuToggle');
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('overlay');
        menuToggle.addEventListener('click', () => { sidebar.classList.toggle('open'); overlay.classList.toggle('active'); });
        overlay.addEventListener('click', () => { sidebar.classList.remove('open'); overlay.classList.remove('active'); });

        // Máscaras (nenhuma alteração aqui)
        document.getElementById('phone')?.addEventListener('input', e => { let v = e.target.value.replace(/\D/g,''); v = v.length > 10 ? v.replace(/^(\d\d)(\d{5})(\d{4}).*/,"($1) $2-$3") : v.replace(/^(\d\d)(\d{4})(\d{0,4}).*/,"($1) $2-$3"); e.target.value = v; });
        document.getElementById('cpf')?.addEventListener('input', e => { let v = e.target.value.replace(/\D/g,''); v = v.replace(/(\d{3})(\d)/, "$1.$2"); v = v.replace(/(\d{3})(\d)/, "$1.$2"); v = v.replace(/(\d{3})(\d{1,2})$/, "$1-$2"); e.target.value = v; });
        
        // --- Lógica de busca em tempo real com JavaScript ---
        const searchInput = document.getElementById('searchInput');
        const tableBody = document.getElementById('clientTableBody');
        const emptyState = document.querySelector('.empty-state');

        if (searchInput && tableBody) {
            searchInput.addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase();
                const rows = tableBody.getElementsByTagName('tr');
                let found = false;

                for (let i = 0; i < rows.length; i++) {
                    const row = rows[i];
                    const name = row.cells[0].textContent.toLowerCase();
                    const phone = row.cells[1].textContent.toLowerCase();
                    const cpf = row.cells[2].textContent.toLowerCase();

                    if (name.includes(searchTerm) || phone.includes(searchTerm) || cpf.includes(searchTerm)) {
                        row.style.display = '';
                        found = true;
                    } else {
                        row.style.display = 'none';
                    }
                }

                if (found) {
                    emptyState.style.display = 'none';
                } else {
                    emptyState.style.display = 'block';
                    document.getElementById('emptyMessage').textContent = 'Nenhum cliente encontrado';
                }
            });
        }
    </script>
</body>
</html>