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

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

$mensagem = "";

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

// 2. SALVAR / ATUALIZAR
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $nome  = strtoupper($conn->real_escape_string($_POST['nome']));
    $valor = str_replace(',', '.', str_replace('.', '', $_POST['valor']));

    if (isset($_POST['btn_salvar'])) {
        $sql = "INSERT INTO servicos (nome, valor) VALUES ('$nome', '$valor')";
        if ($conn->query($sql)) {
            echo "<script>window.location.href='servicos.php?msg=SALVO';</script>";
            exit();
        } else { $mensagem = "ERRO: " . $conn->error; }
    }
}

if(isset($_GET['msg'])){
    if($_GET['msg'] == 'SALVO') $mensagem = "SERVIÇO CADASTRADO COM SUCESSO!";
    if($_GET['msg'] == 'EXCLUIDO') $mensagem = "SERVIÇO 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: 2fr 1fr 1fr; 
        gap: 10px; 
        align-items: flex-end;
    }
    
    .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: 10px; 
        border: 1px solid #999; 
        font-size: 12px; 
        background-color: #fff8e1; 
        width: 100%; 
        box-sizing: border-box; 
    }
    
    .btn-acao { 
        background-color: #00569e; 
        color: white; 
        border: none; 
        padding: 12px; 
        cursor: pointer; 
        font-weight: bold; 
        font-size: 11px; 
        border-radius: 3px;
    }

    .table-container { width: 100%; overflow-x: auto; margin-top: 15px; border: 1px solid #ccc; }
    .datagrid-table { width: 100%; border-collapse: collapse; font-size: 11px; min-width: 400px; }
    .datagrid-table th { background-color: #333; color: white; padding: 10px; border: 1px solid #ccc; text-align: left; }
    .datagrid-table td { padding: 10px; border: 1px solid #eee; background: #fff; font-weight: bold; }
    .datagrid-table tr:nth-child(even) td { background-color: #f9f9f9; }

    /* AJUSTES PARA CELULAR */
    @media (max-width: 600px) {
        .form-section { grid-template-columns: 1fr; }
        .btn-acao { width: 100%; font-size: 13px; }
        .module-wrapper { padding: 5px; }
    }
</style>

<div class="module-wrapper">
    <div style="font-weight: bold; margin-bottom: 10px; color: #00569e; border-left: 5px solid #00569e; padding-left: 10px;">
        🛠️ CADASTRO DE SERVIÇOS / MÃO DE OBRA
    </div>

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

    <form method="POST">
        <div class="form-section">
            <div class="form-group">
                <label>NOME DO SERVIÇO</label>
                <input type="text" name="nome" placeholder="EX: FORMATAÇÃO, LIMPEZA..." required>
            </div>

            <div class="form-group">
                <label>VALOR (R$)</label>
                <input type="text" name="valor" id="valor_servico" placeholder="0,00" oninput="mascaraMoeda(this)" required>
            </div>

            <button type="submit" name="btn_salvar" class="btn-acao">💾 SALVAR SERVIÇO</button>
        </div>
    </form>

    <div class="table-container">
        <table class="datagrid-table">
            <thead>
                <tr>
                    <th width="50">ID</th>
                    <th>DESCRIÇÃO DO SERVIÇO</th>
                    <th width="120">VALOR</th>
                    <th width="60" style="text-align: center;">AÇÕES</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $res = $conn->query("SELECT * FROM servicos ORDER BY nome ASC");
                if($res && $res->num_rows > 0):
                    while($s = $res->fetch_assoc()): ?>
                    <tr>
                        <td>#<?php echo $s['id']; ?></td>
                        <td><?php echo $s['nome']; ?></td>
                        <td style="color: #28a745;">R$ <?php echo number_format($s['valor'], 2, ',', '.'); ?></td>
                        <td style="text-align: center;">
                            <a href="?excluir=<?php echo $s['id']; ?>" onclick="return confirm('EXCLUIR SERVIÇO?')" style="text-decoration:none;">🗑️</a>
                        </td>
                    </tr>
                    <?php endwhile;
                else: ?>
                    <tr><td colspan="4" style="text-align:center; padding:20px;">NENHUM SERVIÇO CADASTRADO.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
function mascaraMoeda(i) {
    let v = i.value.replace(/\D/g,'');
    if(v === "") { i.value = ""; return; }
    v = (v/100).toFixed(2) + '';
    v = v.replace(".", ",");
    v = v.replace(/(\d)(\d{3})(\d{3}),/g, "$1.$2.$3,");
    v = v.replace(/(\d)(\d{3}),/g, "$1.$2,");
    i.value = v;
}
</script>
</body>
</html>