<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
require 'verifica_cookie.php';
require 'conexao.php';

$pdo   = Conexao::getInstance();
$termo = (isset($_POST['termo'])) ? trim($_POST['termo']) : '';

if (strlen($termo) < 2) :
    echo '';
    exit;
endif;

$sql  = "SELECT cli_001, cli_002, cli_013, cli_004 FROM clientes ";
$sql .= "WHERE sit_001 = 4 AND (UPPER(cli_002) LIKE UPPER(:termo) OR cli_013 LIKE :termo_tel) ";
$sql .= "ORDER BY cli_002 LIMIT 20";
$stm  = $pdo->prepare($sql);
$stm->bindValue(':termo', '%' . $termo . '%');
$stm->bindValue(':termo_tel', '%' . $termo . '%');
$stm->execute();
$clientes = $stm->fetchAll(PDO::FETCH_OBJ);

if (empty($clientes)) :
    echo '<div class="text-center" style="padding: 20px;"><p class="text-gray">Nenhum cliente encontrado</p></div>';
else :
    echo '<div class="lista-clientes">';
    foreach ($clientes as $cliente) :
        $telefone = (!empty($cliente->cli_013)) ? $cliente->cli_013 : '';
        $cpf = (!empty($cliente->cli_004)) ? $cliente->cli_004 : '';
?>
        <div class="card-cliente btn-cliente-resultado"
            data-id="<?= $cliente->cli_001 ?>"
            data-nome="<?= htmlspecialchars($cliente->cli_002, ENT_QUOTES, 'UTF-8') ?>"
            data-telefone="<?= htmlspecialchars($cliente->cli_013, ENT_QUOTES, 'UTF-8') ?>">
            <div class="card-cliente-icon">
                <i class="material-icons">person</i>
            </div>
            <div class="card-cliente-info">
                <span class="card-cliente-nome"><?= htmlspecialchars($cliente->cli_002, ENT_QUOTES, 'UTF-8') ?></span>
                <?php if ($telefone) : ?>
                    <span class="card-cliente-detalhe"><i class="material-icons" style="font-size:14px;vertical-align:middle;">phone</i> <?= htmlspecialchars($telefone, ENT_QUOTES, 'UTF-8') ?></span>
                <?php endif; ?>
                <?php if ($cpf) : ?>
                    <span class="card-cliente-detalhe"><i class="material-icons" style="font-size:14px;vertical-align:middle;">badge</i> <?= htmlspecialchars($cpf, ENT_QUOTES, 'UTF-8') ?></span>
                <?php endif; ?>
            </div>
            <div class="card-cliente-check">
                <i class="material-icons">chevron_right</i>
            </div>
        </div>
<?php endforeach;
    echo '</div>';
endif;
