<?php
// --- BLOCO DE SALVAMENTO (DEVE VIR ANTES DE TUDO) ---
include_once('../config.php');

// 1. Lógica para salvar o VALOR HORA no banco de dados
if (isset($_POST['atualizar_vH'])) {
    $id_f = $_POST['id_func'];
    $vH = str_replace(',', '.', str_replace('.', '', $_POST['valor_hora']));
    $sql_vh = "UPDATE funcionarios SET valor_hora = ? WHERE id = ?";
    $stmt_vh = $conn->prepare($sql_vh);
    $stmt_vh->bind_param("di", $vH, $id_f);
    if($stmt_vh->execute()) die("VH_GRAVADO");
    else die("ERRO_VH");
}

// 2. Lógica para salvar as batidas do dia (Existente)
if (isset($_POST['salvar_dia'])) {
    $id_func = $_POST['id_func'];
    $data_ponto = $_POST['data_ponto'];
    $e_m = !empty($_POST['e_m']) ? $_POST['e_m'] : null;
    $s_m = !empty($_POST['s_m']) ? $_POST['s_m'] : null;
    $e_t = !empty($_POST['e_t']) ? $_POST['e_t'] : null;
    $s_t = !empty($_POST['s_t']) ? $_POST['s_t'] : null;
    $e_i = !empty($_POST['e_i']) ? $_POST['e_i'] : null;
    $s_i = !empty($_POST['s_i']) ? $_POST['s_i'] : null;
    
    $vale = str_replace(',', '.', str_replace('.', '', $_POST['vale'])) ?: 0;
    $lanche = str_replace(',', '.', str_replace('.', '', $_POST['lanche'])) ?: 0;

    $sql = "INSERT INTO registro_ponto (funcionario_id, data, entrada_manha, saida_manha, entrada_tarde, saida_tarde, entrada_intervalo, saida_intervalo, vale, lanche) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) 
            ON DUPLICATE KEY UPDATE 
            entrada_manha=VALUES(entrada_manha), saida_manha=VALUES(saida_manha), 
            entrada_tarde=VALUES(entrada_tarde), saida_tarde=VALUES(saida_tarde), 
            entrada_intervalo=VALUES(entrada_intervalo), saida_intervalo=VALUES(saida_intervalo),
            vale=VALUES(vale), lanche=VALUES(lanche)";
            
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("isssssssdd", $id_func, $data_ponto, $e_m, $s_m, $e_t, $s_t, $e_i, $s_i, $vale, $lanche);
    
    if($stmt->execute()) die("GRAVADO");
    else die("ERRO: " . $stmt->error);
}

ini_set('display_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set('America/Sao_Paulo');

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

$id_func = $_GET['id'] ?? null;
if (!$id_func) { echo "Funcionário não encontrado."; exit; }

$mes_alvo = $_GET['mes'] ?? date('m');
$ano_alvo = $_GET['ano'] ?? date('Y');

// Busca funcionário e o VALOR HORA salvo no banco
$f = $conn->query("SELECT * FROM funcionarios WHERE id = $id_func")->fetch_assoc();
$valor_hora_banco = number_format($f['valor_hora'] ?? 0, 2, ',', '.');

function getFeriados($ano) {
    return ["$ano-01-01", "$ano-02-16", "$ano-02-17", "$ano-04-03", "$ano-04-21", "$ano-05-01", "$ano-06-04", "$ano-09-07", "$ano-10-12", "$ano-11-02", "$ano-11-15", "$ano-11-20", "$ano-12-25"];
}
$feriados = getFeriados($ano_alvo);

$registros = [];
$busca = $conn->query("SELECT * FROM registro_ponto WHERE funcionario_id = $id_func AND MONTH(data) = '$mes_alvo' AND YEAR(data) = '$ano_alvo'");
if($busca) { while($row = $busca->fetch_assoc()) { $registros[$row['data']] = $row; } }

$qtd_dias = cal_days_in_month(CAL_GREGORIAN, (int)$mes_alvo, (int)$ano_alvo);
$meses_nome = ["01" => "JANEIRO", "02" => "FEVEREIRO", "03" => "MARÇO", "04" => "ABRIL", "05" => "MAIO", "06" => "JUNHO", "07" => "JULHO", "08" => "AGOSTO", "09" => "SETEMBRO", "10" => "OUTUBRO", "11" => "NOVEMBRO", "12" => "DEZEMBRO"];
$dias_pt = ["DOM", "SEG", "TER", "QUA", "QUI", "SEX", "SÁB"];
?>

<style>
    .excel-wrapper { background: #fff; padding: 5px; font-family: 'Segoe UI', sans-serif; text-transform: uppercase; }
    .header-info { display: flex; justify-content: space-between; align-items: center; background: #333; color: white; padding: 10px; margin-bottom: 5px; }
    .config-bar { background: #f4f4f4; border: 1px solid #ccc; padding: 10px; margin-bottom: 5px; display: flex; align-items: center; gap: 20px; }
    .resumo-topo { background: #e8f5e9; border: 1px solid #2e7d32; padding: 10px; margin-bottom: 10px; display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; text-align: center; }
    .resumo-valor { font-size: 14px; font-weight: bold; font-family: monospace; color: #1b5e20; }
    .tabela-excel { width: 100%; border-collapse: collapse; font-size: 9px; table-layout: fixed; }
    .tabela-excel th { background: #ebf1de; border: 1px solid #999; padding: 4px; color: #000; }
    .tabela-excel td { border: 1px solid #ccc; padding: 0; text-align: center; height: 30px; }
    .input-excel { width: 100%; border: none; background: transparent; text-align: center; font-family: monospace; font-size: 11px; outline: none; height: 100%; }
    .input-moeda { font-weight: bold; color: #2c3e50; }
    .linha-dom { background-color: #ffcccc !important; } 
    .linha-sab { background-color: #fff9c4 !important; } 
    .linha-feriado { background-color: #555 !important; color: #fff !important; }
    .linha-feriado input { color: #fff !important; }
    .col-total { background: rgba(217, 234, 211, 0.8); font-weight: bold; }
    .col-soma { background: #ffd966; font-weight: bold; color: #7f6000; width: 110px; }
</style>

<div class="excel-wrapper">
    <div class="header-info">
        <div>📋 FOLHA: <strong><?php echo $f['nome']; ?></strong></div>
        <a href="folha_ponto.php" style="color: #fff; font-size: 10px;">[ VOLTAR ]</a>
    </div>

    <div class="config-bar">
        <div>
            <label style="font-size: 10px; font-weight: bold;">MÊS:</label>
            <select style="padding:5px;" onchange="window.location.href='?id=<?php echo $id_func; ?>&mes='+this.value">
                <?php foreach($meses_nome as $num => $nome): ?>
                    <option value="<?php echo $num; ?>" <?php echo ($mes_alvo == $num) ? 'selected' : ''; ?>><?php echo $nome; ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label style="font-size: 10px; font-weight: bold;">VALOR HORA R$: <span id="status_vh"></span></label>
            <input type="text" id="valor_hora_global" class="input-excel input-moeda" style="width:100px; border:1px solid #000; background:#fff;" value="<?php echo $valor_hora_banco; ?>" oninput="mascaraMoeda(this); atualizarFolhaToda()" onchange="salvarValorHora()">
        </div>
    </div>

    <div class="resumo-topo">
        <div><span>SOMA BRUTA:</span> <br><span id="resumo_bruto" class="resumo-valor">R$ 0,00</span></div>
        <div><span>TOTAL VALES:</span> <br><span id="resumo_vales" class="resumo-valor">R$ 0,00</span></div>
        <div><span>TOTAL LANCHES:</span> <br><span id="resumo_lanches" class="resumo-valor">R$ 0,00</span></div>
        <div style="background: #c8e6c9; border: 1px solid #2e7d32;"><span>LÍQUIDO TOTAL:</span> <br><span id="resumo_liquido" class="resumo-valor" style="font-size:16px;">R$ 0,00</span></div>
    </div>

    <table class="tabela-excel">
        <thead>
            <tr>
                <th rowspan="2" style="width:75px;">DATA</th>
                <th colspan="2">MANHÃ</th><th colspan="2">TARDE</th><th colspan="2">INTERVALO</th>
                <th rowspan="2" style="width:45px;">HRS</th>
                <th rowspan="2">VALE (R$)</th><th rowspan="2">LANCHE (R$)</th>
                <th rowspan="2" class="col-soma">SOMA R$</th>
            </tr>
            <tr><th>ENT</th><th>SAÍ</th><th>ENT</th><th>SAÍ</th><th>ENT</th><th>SAÍ</th></tr>
        </thead>
        <tbody>
            <?php 
            for ($d = 1; $d <= $qtd_dias; $d++): 
                $dt = sprintf("%04d-%02d-%02d", $ano_alvo, $mes_alvo, $d);
                $wd = date('w', strtotime($dt));
                $isF = in_array($dt, $feriados);
                $cls = $isF ? "linha-feriado" : ($wd==0 ? "linha-dom" : ($wd==6 ? "linha-sab" : ""));
                $reg = $registros[$dt] ?? null;
                
                $exibir_vale = (isset($reg['vale']) && $reg['vale'] > 0) ? number_format($reg['vale'], 2, ',', '.') : '';
                $exibir_lanche = (isset($reg['lanche']) && $reg['lanche'] > 0) ? number_format($reg['lanche'], 2, ',', '.') : '';
            ?>
            <tr class="<?php echo $cls; ?>" id="linha-<?php echo $d; ?>">
                <td><?php echo date('d/m', strtotime($dt))." ".$dias_pt[$wd]; ?></td>
                <td><input type="time" class="input-excel" value="<?php echo $reg['entrada_manha'] ?? ''; ?>" onchange="salvarLinha(<?php echo $d; ?>, '<?php echo $dt; ?>')"></td>
                <td><input type="time" class="input-excel" value="<?php echo $reg['saida_manha'] ?? ''; ?>" onchange="salvarLinha(<?php echo $d; ?>, '<?php echo $dt; ?>')"></td>
                <td><input type="time" class="input-excel" value="<?php echo $reg['entrada_tarde'] ?? ''; ?>" onchange="salvarLinha(<?php echo $d; ?>, '<?php echo $dt; ?>')"></td>
                <td><input type="time" class="input-excel" value="<?php echo $reg['saida_tarde'] ?? ''; ?>" onchange="salvarLinha(<?php echo $d; ?>, '<?php echo $dt; ?>')"></td>
                <td><input type="time" class="input-excel" value="<?php echo $reg['entrada_intervalo'] ?? ''; ?>" onchange="salvarLinha(<?php echo $d; ?>, '<?php echo $dt; ?>')"></td>
                <td><input type="time" class="input-excel" value="<?php echo $reg['saida_intervalo'] ?? ''; ?>" onchange="salvarLinha(<?php echo $d; ?>, '<?php echo $dt; ?>')"></td>
                <td class="col-total" id="total-<?php echo $d; ?>"></td>
                <td><input type="text" class="input-excel v-vale input-moeda" value="<?php echo $exibir_vale; ?>" placeholder="0,00" oninput="mascaraMoeda(this)" onchange="salvarLinha(<?php echo $d; ?>, '<?php echo $dt; ?>')"></td>
                <td><input type="text" class="input-excel v-lanche input-moeda" value="<?php echo $exibir_lanche; ?>" placeholder="0,00" oninput="mascaraMoeda(this)" onchange="salvarLinha(<?php echo $d; ?>, '<?php echo $dt; ?>')"></td>
                <td class="col-soma"><span class="v-soma-dia" id="subtotal-<?php echo $d; ?>"></span> <span id="status-<?php echo $d; ?>" style="font-size:7px; margin-left:2px;">✅</span></td>
            </tr>
            <?php endfor; ?>
        </tbody>
    </table>
</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;
}

function toF(s) {
    if(!s || s === "R$ 0,00" || s === "0,00" || s === "") return 0;
    let n = String(s).replace(/[R$\s]/g, '').replace(/\./g, '').replace(',', '.');
    return parseFloat(n) || 0;
}

function diffM(i, f) {
    if (!i || !f) return 0;
    const [h1, m1] = i.split(':').map(Number);
    const [h2, m2] = f.split(':').map(Number);
    return (h2 * 60 + m2) - (h1 * 60 + m1);
}

function somarTudo() {
    let bruto_total = 0, vales_total = 0, lanches_total = 0;
    // Somamos os valores já arredondados para garantir que o topo bata com a coluna amarela
    document.querySelectorAll('.v-soma-dia').forEach(span => bruto_total += Math.round(toF(span.innerText) * 100) / 100);
    document.querySelectorAll('.v-vale').forEach(inp => vales_total += toF(inp.value));
    document.querySelectorAll('.v-lanche').forEach(inp => lanches_total += toF(inp.value));
    
    let liquido_total = bruto_total - vales_total - lanches_total;
    const fM = (n) => n.toLocaleString('pt-br', {style:'currency', currency:'BRL'});
    
    document.getElementById('resumo_bruto').innerText = fM(bruto_total);
    document.getElementById('resumo_vales').innerText = fM(vales_total);
    document.getElementById('resumo_lanches').innerText = fM(lanches_total);
    document.getElementById('resumo_liquido').innerText = fM(liquido_total);
}

function calcularHoras(d) {
    const l = document.getElementById('linha-' + d);
    const ins = l.querySelectorAll('input');
    const vH = toF(document.getElementById('valor_hora_global').value);
    
    let mTr = diffM(ins[0].value, ins[1].value) + diffM(ins[2].value, ins[3].value);
    let mIn = diffM(ins[4].value, ins[5].value);
    let tot = Math.max(0, mTr - mIn);
    
    const displayTotal = document.getElementById('total-' + d);
    const displaySoma = document.getElementById('subtotal-' + d);

    if (tot > 0) {
        displayTotal.innerText = String(Math.floor(tot/60)).padStart(2,'0')+":"+String(tot%60).padStart(2,'0');
        // MATEMÁTICA: (Minutos/60) * Valor Hora arredondado para 2 casas
        let valorBrutoDia = Math.round(((tot / 60) * vH) * 100) / 100;
        displaySoma.innerText = valorBrutoDia.toLocaleString('pt-br', {minimumFractionDigits: 2});
    } else {
        displayTotal.innerText = "";
        displaySoma.innerText = "";
    }
    somarTudo();
}

function salvarValorHora() {
    const vH = document.getElementById('valor_hora_global').value;
    const status = document.getElementById('status_vh');
    status.innerText = "⏳";
    
    const fd = new FormData();
    fd.append('atualizar_vH', '1');
    fd.append('id_func', '<?php echo $id_func; ?>');
    fd.append('valor_hora', vH);

    fetch(window.location.href, { method: 'POST', body: fd })
    .then(r => r.text())
    .then(t => { 
        if(t.trim() === "VH_GRAVADO") status.innerText = "✅";
        else status.innerText = "❌";
    });
}

function atualizarFolhaToda() {
    <?php for($i=1; $i<=$qtd_dias; $i++) echo "calcularHoras($i);"; ?>
}

function salvarLinha(d, dt) {
    calcularHoras(d);
    const status = document.getElementById('status-' + d);
    status.innerText = "⏳";
    const ins = document.getElementById('linha-' + d).querySelectorAll('input');
    const fd = new FormData();
    fd.append('salvar_dia', '1');
    fd.append('id_func', '<?php echo $id_func; ?>');
    fd.append('data_ponto', dt);
    fd.append('e_m', ins[0].value); fd.append('s_m', ins[1].value);
    fd.append('e_t', ins[2].value); fd.append('s_t', ins[3].value);
    fd.append('e_i', ins[4].value); fd.append('s_i', ins[5].value);
    fd.append('vale', ins[6].value); fd.append('lanche', ins[7].value);

    fetch(window.location.href, { method: 'POST', body: fd })
    .then(r => r.text())
    .then(t => { 
        if(t.trim() === "GRAVADO") status.innerText = "✅";
        else alert("ERRO: " + t);
    });
}

window.onload = function() {
    atualizarFolhaToda();
};
</script>