<?php
// fichas.php - Pasta: saude/
require_once('../config.php'); 
require_once('../header.php');

$ver_paciente = isset($_GET['paciente_id']) ? (int)$_GET['paciente_id'] : 0;
$ver_atendimento = isset($_GET['atendimento_id']) ? (int)$_GET['atendimento_id'] : 0;

// --- LÓGICA DE EXCLUSÃO ---
if (isset($_GET['excluir_id'])) {
    $id_del = (int)$_GET['excluir_id'];
    $pac_id = (int)$_GET['paciente_id'];
    $conn->query("DELETE FROM saude_atendimentos WHERE id = $id_del");
    echo "<script>alert('Atendimento excluído com sucesso!'); window.location.href='fichas.php?paciente_id=$pac_id';</script>";
    exit;
}

// --- LÓGICA AJAX PARA SALVAMENTO DIRETO (MANTIDA) ---
if (isset($_POST['ajax_save'])) {
    $id = (int)$_POST['id'];
    $campo = $_POST['campo'];
    $valor = $_POST['valor'];

    $campos_diretos = ['especialidade', 'atividade', 'local', 'tipo_pagamento', 'data_atendimento', 'hora_atendimento', 'profissional_id'];
    
    if (in_array($campo, $campos_diretos)) {
        $stmt = $conn->prepare("UPDATE saude_atendimentos SET $campo = ? WHERE id = ?");
        $stmt->bind_param("si", $valor, $id);
        $stmt->execute();
    } else {
        $res = $conn->query("SELECT observacoes FROM saude_atendimentos WHERE id = $id");
        $row = $res->fetch_assoc();
        $partes = explode(' | ', $row['observacoes']);

        $mapa = ['pa' => 0, 'alt' => 1, 'peso' => 2, 'temp' => 3, 'queixa' => 4, 'diag' => 5, 'prescr' => 6];
        $prefixos = ['PA: ', 'ALT: ', 'PESO: ', 'TEMP: ', 'QUEIXA: ', 'DIAG: ', 'PRESCR: '];
        
        if (isset($mapa[$campo])) {
            $pos = $mapa[$campo];
            $partes[$pos] = $prefixos[$pos] . $valor;
            $nova_obs = implode(' | ', $partes);
            $stmt = $conn->prepare("UPDATE saude_atendimentos SET observacoes = ? WHERE id = ?");
            $stmt->bind_param("si", $nova_obs, $id);
            $stmt->execute();
        }
    }
    exit;
}
?>

<style>
    body { background-color: #e6e6e6; font-family: 'Segoe UI', Tahoma, sans-serif; text-transform: uppercase; }
    .excel-window { background: #fff; border: 1px solid #bbb; margin-top: 10px; box-shadow: 2px 2px 5px rgba(0,0,0,0.1); min-height: 500px; }
    .excel-ribbon { background: #217346; color: white; padding: 5px 15px; font-size: 12px; font-weight: bold; display: flex; justify-content: space-between; align-items: center; }
    
    .folder-grid { display: flex; flex-wrap: wrap; padding: 20px; gap: 20px; background: #fff; }
    .folder-box { width: 120px; text-align: center; cursor: pointer; text-decoration: none !important; color: #333; padding: 10px; border: 1px solid transparent; transition: 0.2s; }
    .folder-box:hover { background: #e9f5ee; border: 1px solid #217346; }
    .folder-box i { font-size: 40px; color: #ffc107; display: block; margin-bottom: 5px; }
    .folder-label { font-size: 9px; font-weight: bold; line-height: 1.1; display: block; word-break: break-all; }

    .excel-table { width: 100%; border-collapse: collapse; background: white; font-size: 10px; margin-bottom: 0; }
    .excel-table th, .excel-table td { border: 1px solid #bbb; padding: 4px 8px; }
    .row-header { background: #f3f3f3; font-weight: bold; color: #217346; }

    .input-inline { font-size: 10px; border: 1px solid transparent; background: transparent; width: 100%; text-transform: uppercase; outline: none; cursor: cell; }
    .input-inline:hover { background: #ffffd5; border: 1px dashed #217346; }

    .editavel-txt { cursor: text; outline: none; text-transform: none; font-family: 'Segoe UI', sans-serif; min-height: 40px; padding: 5px; }
    .editavel-txt:hover { background: #ffffd5; }

    .label-secao { font-size: 8px; color: #217346; font-weight: bold; display: block; margin-bottom: 3px; }
    .vital-val { font-size: 13px; font-weight: bold; color: #d32f2f; min-height: 20px; }
    .status-salvando { font-size: 10px; font-weight: normal; font-style: italic; display: none; margin-left: 10px; }

    @media print {
        body * { visibility: hidden; }
        #areaImpressao, #areaImpressao * { visibility: visible; }
        #areaImpressao { position: absolute; left: 0; top: 0; width: 100%; }
        body { background-color: #fff !important; }
        .excel-window { border: none !important; box-shadow: none !important; }
        .excel-table th { background: #f3f3f3 !important; -webkit-print-color-adjust: exact; }
        .input-inline { border: none !important; }
        select { appearance: none; -webkit-appearance: none; border: none !important; }
    }
</style>

<div class="container-fluid">
    <div class="excel-window">
        <div class="excel-ribbon no-print">
            <div>
                <i class="fas fa-file-excel mr-2"></i> PRONTUÁRIO INDIVIDUAL
                <span id="msg_salvando" class="status-salvando">Gravando...</span>
            </div>
            <div>
                <?php if($ver_atendimento > 0): ?>
                    <a href="?excluir_id=<?php echo $ver_atendimento; ?>&paciente_id=<?php echo $ver_paciente; ?>" 
                       class="btn btn-sm btn-danger py-0 mr-2" 
                       style="font-size: 9px; font-weight:bold; background:#d32f2f; border:none;"
                       onclick="return confirm('TEM CERTEZA QUE DESEJA EXCLUIR ESTE ATENDIMENTO PERMANENTEMENTE?')">
                        <i class="fas fa-trash-alt mr-1"></i> EXCLUIR
                    </a>

                    <button onclick="window.print()" class="btn btn-sm btn-primary py-0 mr-2" style="font-size: 9px; font-weight:bold; background:#00569e; border:none;">
                        <i class="fas fa-print mr-1"></i> IMPRIMIR
                    </button>
                <?php endif; ?>
                
                <?php if($ver_paciente > 0): ?>
                    <a href="<?php echo ($ver_atendimento > 0) ? '?paciente_id='.$ver_paciente : 'fichas.php'; ?>" class="btn btn-sm btn-light py-0" style="font-size: 9px; font-weight:bold;">VOLTAR</a>
                <?php endif; ?>
            </div>
        </div>

        <?php if($ver_paciente == 0): ?>
            <div class="folder-grid">
                <?php
                $sql_pastas = "SELECT DISTINCT p.id, p.nome FROM saude_cadastros p JOIN saude_atendimentos h ON p.id = h.paciente_id ORDER BY p.nome ASC";
                $res_pastas = $conn->query($sql_pastas);
                while($f = $res_pastas->fetch_assoc()): ?>
                    <a href="?paciente_id=<?php echo $f['id']; ?>" class="folder-box">
                        <i class="fas fa-folder fa-3x"></i>
                        <span class="folder-label"><?php echo $f['nome']; ?></span>
                    </a>
                <?php endwhile; ?>
            </div>

        <?php elseif($ver_atendimento == 0): ?>
            <div class="folder-grid">
                <?php
                $sql_ats = "SELECT h.*, m.nome as medico FROM saude_atendimentos h JOIN saude_cadastros m ON h.profissional_id = m.id WHERE h.paciente_id = $ver_paciente ORDER BY h.data_atendimento DESC";
                $res_ats = $conn->query($sql_ats);
                while($at = $res_ats->fetch_assoc()): ?>
                    <a href="?paciente_id=<?php echo $ver_paciente; ?>&atendimento_id=<?php echo $at['id']; ?>" class="folder-box">
                        <i class="fas fa-folder-open fa-3x" style="color:#217346"></i>
                        <span class="folder-label">
                            <?php echo date('d/m/Y', strtotime($at['data_atendimento'])); ?> - <?php echo $at['hora_atendimento']; ?><br>
                            <?php echo $at['medico']; ?>
                        </span>
                    </a>
                <?php endwhile; ?>
            </div>

        <?php else: ?>
            <div class="p-3" id="areaImpressao">
                <?php
                $sql_f = "SELECT h.*, p.nome as nome_paciente, m.nome as medico 
                          FROM saude_atendimentos h 
                          JOIN saude_cadastros p ON h.paciente_id = p.id 
                          JOIN saude_cadastros m ON h.profissional_id = m.id 
                          WHERE h.id = $ver_atendimento";
                $res_f = $conn->query($sql_f);
                while($f = $res_f->fetch_assoc()):
                    $partes = explode(' | ', $f['observacoes']);
                    $pa = str_replace('PA: ', '', $partes[0] ?? '');
                    $alt = str_replace('ALT: ', '', $partes[1] ?? '');
                    $peso = str_replace('PESO: ', '', $partes[2] ?? '');
                    $temp = str_replace('TEMP: ', '', $partes[3] ?? '');
                    $queixa = str_replace('QUEIXA: ', '', $partes[4] ?? '');
                    $diag = str_replace('DIAG: ', '', $partes[5] ?? '');
                    $prescr = str_replace('PRESCR: ', '', $partes[6] ?? '');
                ?>
                <table class="excel-table">
                    <tr>
                        <th width="150" class="row-header" style="background:#217346 !important; color:#fff !important; -webkit-print-color-adjust: exact;">PACIENTE</th>
                        <th width="100">DATA</th>
                        <th width="80">HORA</th>
                        <th width="200">PROFISSIONAL</th>
                        <th>PROFISSÃO</th>
                        <th>ATIVIDADE</th>
                        <th>LOCAL</th>
                        <th>PAGAMENTO</th>
                    </tr>
                    <tr>
                        <td style="background:#e9f5ee !important; font-weight:bold; color:#217346 !important; -webkit-print-color-adjust: exact;"><?php echo $f['nome_paciente']; ?></td>
                        <td><input type="date" class="input-inline font-weight-bold" value="<?php echo $f['data_atendimento']; ?>" onchange="salvarDireto(<?php echo $f['id']; ?>, 'data_atendimento', this.value)"></td>
                        <td><input type="time" class="input-inline font-weight-bold" value="<?php echo $f['hora_atendimento']; ?>" onchange="salvarDireto(<?php echo $f['id']; ?>, 'hora_atendimento', this.value)"></td>
                        <td>
                            <select class="input-inline" onchange="salvarDireto(<?php echo $f['id']; ?>, 'profissional_id', this.value)">
                                <?php
                                $medicos = $conn->query("SELECT id, nome FROM saude_cadastros WHERE tipo NOT IN ('paciente','atividades','locais','profissao') ORDER BY nome ASC");
                                while($m = $medicos->fetch_assoc()){
                                    $sel = ($f['profissional_id'] == $m['id']) ? 'selected' : '';
                                    echo "<option value='{$m['id']}' $sel>{$m['nome']}</option>";
                                }
                                ?>
                            </select>
                        </td>
                        <td>
                            <select class="input-inline" onchange="salvarDireto(<?php echo $f['id']; ?>, 'especialidade', this.value)">
                                <?php
                                $profs = $conn->query("SELECT nome FROM saude_cadastros WHERE tipo = 'profissao' ORDER BY nome ASC");
                                while($p = $profs->fetch_assoc()){
                                    $sel = ($f['especialidade'] == $p['nome']) ? 'selected' : '';
                                    echo "<option value='{$p['nome']}' $sel>{$p['nome']}</option>";
                                }
                                ?>
                            </select>
                        </td>
                        <td>
                            <select class="input-inline" onchange="salvarDireto(<?php echo $f['id']; ?>, 'atividade', this.value)">
                                <?php
                                $atvs = $conn->query("SELECT nome FROM saude_cadastros WHERE tipo = 'atividades' ORDER BY nome ASC");
                                while($a = $atvs->fetch_assoc()){
                                    $sel = ($f['atividade'] == $a['nome']) ? 'selected' : '';
                                    echo "<option value='{$a['nome']}' $sel>{$a['nome']}</option>";
                                }
                                ?>
                            </select>
                        </td>
                        <td>
                            <select class="input-inline" onchange="salvarDireto(<?php echo $f['id']; ?>, 'local', this.value)">
                                <?php
                                $locs = $conn->query("SELECT nome FROM saude_cadastros WHERE tipo = 'locais' ORDER BY nome ASC");
                                while($l = $locs->fetch_assoc()){
                                    $sel = ($f['local'] == $l['nome']) ? 'selected' : '';
                                    echo "<option value='{$l['nome']}' $sel>{$l['nome']}</option>";
                                }
                                ?>
                            </select>
                        </td>
                        <td>
                            <select class="input-inline" onchange="salvarDireto(<?php echo $f['id']; ?>, 'tipo_pagamento', this.value)">
                                <option value="PLANO" <?php if($f['tipo_pagamento'] == 'PLANO') echo 'selected'; ?>>PLANO</option>
                                <option value="PAGO" <?php if($f['tipo_pagamento'] == 'PAGO') echo 'selected'; ?>>PAGO</option>
                            </select>
                        </td>
                    </tr>
                </table>

                <table class="excel-table" style="border-top:none; margin-bottom: 25px;">
                    <tr>
                        <td width="25%"><span class="label-secao">P.A.</span><div class="editavel-txt vital-val" contenteditable="true" onblur="salvarDireto(<?php echo $f['id']; ?>, 'pa', this.innerText)"><?php echo $pa; ?></div></td>
                        <td width="25%"><span class="label-secao">ALTURA</span><div class="editavel-txt vital-val" contenteditable="true" onblur="salvarDireto(<?php echo $f['id']; ?>, 'alt', this.innerText)"><?php echo $alt; ?></div></td>
                        <td width="25%"><span class="label-secao">PESO</span><div class="editavel-txt vital-val" contenteditable="true" onblur="salvarDireto(<?php echo $f['id']; ?>, 'peso', this.innerText)"><?php echo $peso; ?></div></td>
                        <td width="25%"><span class="label-secao">TEMP.</span><div class="editavel-txt vital-val" contenteditable="true" onblur="salvarDireto(<?php echo $f['id']; ?>, 'temp', this.innerText)"><?php echo $temp; ?></div></td>
                    </tr>
                    <tr>
                        <td colspan="4">
                            <span class="label-secao">QUEIXA PRINCIPAL / HISTÓRICO</span>
                            <div class="editavel-txt" contenteditable="true" onblur="salvarDireto(<?php echo $f['id']; ?>, 'queixa', this.innerText)"><?php echo $queixa; ?></div>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <span class="label-secao">DIAGNÓSTICO / EXAME</span>
                            <div class="editavel-txt" contenteditable="true" onblur="salvarDireto(<?php echo $f['id']; ?>, 'diag', this.innerText)"><?php echo $diag; ?></div>
                        </td>
                        <td colspan="2">
                            <span class="label-secao">PRESCRIÇÃO / CONDUTA</span>
                            <div class="editavel-txt" contenteditable="true" onblur="salvarDireto(<?php echo $f['id']; ?>, 'prescr', this.innerText)"><?php echo $prescr; ?></div>
                        </td>
                    </tr>
                </table>
                <?php endwhile; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
function salvarDireto(id, campo, valor) {
    document.getElementById('msg_salvando').style.display = 'inline';
    const formData = new FormData();
    formData.append('ajax_save', '1');
    formData.append('id', id);
    formData.append('campo', campo);
    formData.append('valor', valor);

    fetch('fichas.php', { method: 'POST', body: formData })
    .then(() => { setTimeout(() => { document.getElementById('msg_salvando').style.display = 'none'; }, 800); });
}
</script>

<?php require_once('../footer.php'); ?>