<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include_once('../config.php');
include_once('../header.php');

$mensagem = "";

// 1. EXCLUIR
if(isset($_GET['excluir'])){
    $id_excluir = $_GET['excluir'];
    if($conn->query("DELETE FROM clientes WHERE ID = '$id_excluir' OR id = '$id_excluir'")){
        echo "<script>window.location.href='clientes.php?msg=EXCLUIDO';</script>";
        exit();
    }
}

// 2. EDITAR
$edit_cli = null;
if(isset($_GET['editar'])){
    $id_editar = $_GET['editar'];
    $res_edit = $conn->query("SELECT * FROM clientes WHERE ID = '$id_editar' OR id = '$id_editar'");
    if($res_edit) $edit_cli = $res_edit->fetch_assoc();
}

// 3. SALVAR / ATUALIZAR
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $nome     = strtoupper($conn->real_escape_string($_POST['nome']));
    $telefone = $conn->real_escape_string($_POST['telefone']);
    $cpf      = $conn->real_escape_string($_POST['cpf']);
    $endereco = strtoupper($conn->real_escape_string($_POST['endereco']));

    if (isset($_POST['btn_salvar'])) {
        $sql = "INSERT INTO clientes (NOME, TELEFONE, CPF, ENDERECO) 
                VALUES ('$nome', '$telefone', '$cpf', '$endereco')";
        
        if ($conn->query($sql)) {
            echo "<script>window.location.href='clientes.php?msg=SALVO';</script>";
            exit();
        } else { $mensagem = "ERRO: " . $conn->error; }
    } 
    
    elseif (isset($_POST['btn_atualizar'])) {
        $id = $_POST['id'];
        $sql = "UPDATE clientes SET 
                NOME='$nome', 
                TELEFONE='$telefone', 
                CPF='$cpf', 
                ENDERECO='$endereco' 
                WHERE ID='$id' OR id='$id'";
        
        if ($conn->query($sql)) {
            echo "<script>window.location.href='clientes.php?msg=ATUALIZADO';</script>";
            exit();
        }
    }
}

if(isset($_GET['msg'])){
    if($_GET['msg'] == 'SALVO') $mensagem = "CLIENTE CADASTRADO COM SUCESSO!";
    if($_GET['msg'] == 'ATUALIZADO') $mensagem = "CADASTRO ATUALIZADO COM SUCESSO!";
    if($_GET['msg'] == 'EXCLUIDO') $mensagem = "REGISTRO REMOVIDO COM SUCESSO!";
}
?>

<style>
    .module-wrapper { 
        display: flex; 
        flex-direction: column; 
        width: 100%; 
        padding: 10px; 
        box-sizing: border-box; 
        text-transform: uppercase; 
        font-family: sans-serif; 
    }
    .form-section { 
        background-color: #fff; 
        border: 1px solid #ccc; 
        padding: 15px; 
        display: grid; 
        grid-template-columns: repeat(4, 1fr); 
        gap: 10px; 
    }
    .form-group { display: flex; flex-direction: column; }
    .form-group label { font-size: 9px; font-weight: bold; color: #555; margin-bottom: 2px; }
    .form-group input { 
        padding: 8px; 
        border: 1px solid #999; 
        font-size: 11px; 
        background-color: #fff8e1; 
        width: 100%; 
        box-sizing: border-box; 
    }
    .btn-acao { 
        background-color: #e0e0e0; 
        border: 1px solid #999; 
        padding: 10px 20px; 
        cursor: pointer; 
        font-weight: bold; 
        font-size: 11px; 
    }
    .datagrid-table { 
        width: 100%; 
        border-collapse: collapse; 
        font-size: 11px; 
        margin-top: 10px; 
        min-width: 600px; 
    }
    .datagrid-table th { 
        background-color: #e0e0e0; 
        padding: 8px; 
        border: 1px solid #ccc; 
        text-align: left; 
        position: sticky; 
        top: 0; 
    }
    .datagrid-table td { padding: 8px; border: 1px solid #eee; background: #fff; }
    .datagrid-table tr:nth-child(even) td { background-color: #f9f9f9; }

    /* --- AJUSTES PARA CELULAR (RESPONSIVIDADE) --- */
    @media (max-width: 600px) {
        .form-section { 
            grid-template-columns: 1fr; /* Transforma as 4 colunas em 1 única */
        }
        .form-group { 
            grid-column: span 1 !important; /* Força os campos que eram largos a ficarem normais */
        }
        .btn-acao { 
            width: 100%; 
            padding: 12px; 
            font-size: 12px; 
        }
        /* Ajuste para o container do botão de salvar */
        div[style*="justify-content: flex-end"] { 
            justify-content: center !important; 
            margin-top: 10px; 
            width: 100%; 
        }
        /* Permite o scroll lateral na tabela sem quebrar o layout da página */
        div[style*="overflow: auto"] { 
            overflow-x: auto !important; 
            -webkit-overflow-scrolling: touch; 
        }
    }
</style>

<div class="module-wrapper">
    <div style="font-weight: bold; margin-bottom: 5px; color: #00569e;">👤 MANUTENÇÃO DE CLIENTES</div>

    <?php if($mensagem != ""): ?>
        <div style="background:#d4edda; color:#155724; padding:8px; margin-bottom:10px; font-size:10px; border:1px solid #c3e6cb; text-align:center; font-weight: bold;"><?php echo $mensagem; ?></div>
    <?php endif; ?>

    <form method="POST">
        <div class="form-section">
            <input type="hidden" name="id" value="<?php echo $edit_cli['ID'] ?? $edit_cli['id'] ?? ''; ?>">
            
            <div class="form-group" style="grid-column: span 2;">
                <label>NOME COMPLETO</label>
                <input type="text" name="nome" value="<?php echo $edit_cli['NOME'] ?? $edit_cli['nome'] ?? ''; ?>" required>
            </div>

            <div class="form-group">
                <label>TELEFONE</label>
                <input type="text" name="telefone" value="<?php echo $edit_cli['TELEFONE'] ?? $edit_cli['telefone'] ?? ''; ?>">
            </div>

            <div class="form-group">
                <label>CPF (OPCIONAL)</label>
                <input type="text" name="cpf" value="<?php echo $edit_cli['CPF'] ?? $edit_cli['cpf'] ?? ''; ?>">
            </div>

            <div class="form-group" style="grid-column: span 3;">
                <label>ENDEREÇO COMPLETO</label>
                <input type="text" name="endereco" value="<?php echo $edit_cli['ENDERECO'] ?? $edit_cli['endereco'] ?? ''; ?>">
            </div>

            <div style="display: flex; align-items: flex-end; justify-content: flex-end;">
                <button type="submit" name="<?php echo $edit_cli ? 'btn_atualizar' : 'btn_salvar'; ?>" class="btn-acao">💾 SALVAR</button>
                <?php if($edit_cli): ?>
                    <a href="clientes.php" class="btn-acao" style="text-decoration:none; margin-left: 5px; background: #f8d7da; color: #721c24;">❌</a>
                <?php endif; ?>
            </div>
        </div>
    </form>

    <div style="overflow: auto; margin-top: 10px; border: 1px solid #ccc; max-height: 400px;">
        <table class="datagrid-table">
            <thead>
                <tr>
                    <th width="60">ID</th>
                    <th>NOME</th>
                    <th width="120">TELEFONE</th>
                    <th width="150">CPF</th>
                    <th>ENDERECO</th>
                    <th width="80" style="text-align: center;">AÇÕES</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $res = $conn->query("SELECT * FROM clientes ORDER BY id DESC, ID DESC");
                if($res && $res->num_rows > 0):
                    while($l = $res->fetch_assoc()): ?>
                    <tr>
                        <td><?php echo $l['id'] ?? $l['ID']; ?></td>
                        <td><?php echo $l['nome'] ?? $l['NOME']; ?></td>
                        <td><?php echo $l['telefone'] ?? $l['TELEFONE']; ?></td>
                        <td><?php echo $l['cpf'] ?? $l['CPF']; ?></td>
                        <td><?php echo $l['endereco'] ?? $l['ENDERECO']; ?></td>
                        <td style="text-align: center;">
                            <a href="?editar=<?php echo $l['id'] ?? $l['ID']; ?>" style="text-decoration:none;">📝</a>
                            <a href="?excluir=<?php echo $l['id'] ?? $l['ID']; ?>" onclick="return confirm('EXCLUIR CLIENTE?')" style="text-decoration:none; margin-left:10px;">🗑️</a>
                        </td>
                    </tr>
                    <?php endwhile;
                else: ?>
                    <tr><td colspan="6" style="text-align:center; padding:10px;">NENHUM CLIENTE ENCONTRADO.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
</body>
</html>