<?php
$u=current_user();$uid=(int)$u['id'];$patientId=(int)request('id',0);$q=db()->prepare("SELECT p.*,c.name company_name,c.owner_user_id,c.logo company_logo,pu.public_id platform_public_id FROM clinic_patients p JOIN companies c ON c.id=p.company_id LEFT JOIN users pu ON pu.id=p.platform_user_id WHERE p.id=? LIMIT 1");$q->execute([$patientId]);$patient=$q->fetch();if(!$patient){?><section class="panel"><div class="empty-state"><strong>Paciente não encontrado</strong></div></section><?php return;}
$companyId=(int)$patient['company_id'];$isOwner=can_manage_clinic_company($companyId);$isPatient=(int)($patient['platform_user_id']??0)===$uid;$pq=db()->prepare("SELECT id,name FROM clinic_professionals WHERE company_id=? AND user_id=? AND status='active' AND COALESCE(link_state,'active')='active' ORDER BY id LIMIT 1");$pq->execute([$companyId,$uid]);$professional=$pq->fetch();$isProfessional=(bool)$professional;$canClinicalEdit=$isOwner||$isProfessional;if(!$isOwner&&!$isPatient&&!$isProfessional){http_response_code(403);exit('Sem permissão para este prontuário.');}
$appointments=[];$records=[];$diagnoses=[];$prescriptions=[];$prescriptionItems=[];$exams=[];$documents=[];
try{$q=db()->prepare("SELECT a.*,pr.name professional_name,s.name specialty_name FROM clinic_appointments a LEFT JOIN clinic_professionals pr ON pr.id=a.professional_id LEFT JOIN clinic_specialties s ON s.id=a.specialty_id WHERE a.patient_id=? ORDER BY a.appointment_date DESC,a.appointment_time DESC");$q->execute([$patientId]);$appointments=$q->fetchAll();}catch(Throwable $e){}
try{$q=db()->prepare("SELECT r.*,pr.name professional_name,ps.name professional_specialty FROM clinic_patient_records r LEFT JOIN clinic_professionals pr ON pr.id=r.professional_id LEFT JOIN clinic_specialties ps ON ps.id=pr.specialty_id WHERE r.patient_id=? ORDER BY r.id DESC");$q->execute([$patientId]);$records=$q->fetchAll();}catch(Throwable $e){}
try{$q=db()->prepare("SELECT d.*,pr.name professional_name,ps.name professional_specialty FROM clinic_diagnoses d LEFT JOIN clinic_professionals pr ON pr.id=d.professional_id LEFT JOIN clinic_specialties ps ON ps.id=pr.specialty_id WHERE d.patient_id=? ORDER BY d.diagnosed_at DESC,d.id DESC");$q->execute([$patientId]);$diagnoses=$q->fetchAll();}catch(Throwable $e){}
try{$q=db()->prepare("SELECT p.*,pr.name professional_name,ps.name professional_specialty FROM clinic_prescriptions p LEFT JOIN clinic_professionals pr ON pr.id=p.professional_id LEFT JOIN clinic_specialties ps ON ps.id=pr.specialty_id WHERE p.patient_id=? ORDER BY p.prescribed_at DESC,p.id DESC");$q->execute([$patientId]);$prescriptions=$q->fetchAll();if($prescriptions){$ids=array_column($prescriptions,'id');$marks=implode(',',array_fill(0,count($ids),'?'));$iq=db()->prepare("SELECT * FROM clinic_prescription_items WHERE prescription_id IN ($marks) ORDER BY id");$iq->execute($ids);foreach($iq->fetchAll() as $it)$prescriptionItems[(int)$it['prescription_id']][]=$it;}}catch(Throwable $e){$prescriptions=[];$prescriptionItems=[];}
try{$q=db()->prepare("SELECT e.*,s.name exam_name,pr.name professional_name FROM clinic_exam_requests e LEFT JOIN clinic_specialties s ON s.id=e.specialty_id LEFT JOIN clinic_professionals pr ON pr.id=e.professional_id WHERE e.patient_id=? ORDER BY e.id DESC");$q->execute([$patientId]);$exams=$q->fetchAll();}catch(Throwable $e){}
try{$q=db()->prepare("SELECT * FROM clinic_patient_documents WHERE patient_id=? ORDER BY id DESC");$q->execute([$patientId]);$documents=$q->fetchAll();}catch(Throwable $e){}
$age='';if(!empty($patient['birth_date'])){$b=new DateTime($patient['birth_date']);$age=$b->diff(new DateTime())->y.' anos';}
?>
<section class="page-intro"><div><span class="mini-label">🩺 PRONTUÁRIO</span><h2><?=e($patient['name'])?></h2><p><?=e($patient['company_name'])?> • <?=e($patient['platform_public_id']?:'Paciente sem ID vinculado')?><?= $age?' • '.e($age):'' ?></p></div><div class="actions"><a class="btn btn-secondary" href="dashboard.php?page=<?= $isPatient?'clinic_patient':($isProfessional?'clinic_professional':'clinic') ?>">← Voltar</a></div></section>
<section class="stats-grid"><div class="stat-card"><div class="stat-top"><span>Consultas</span><span class="stat-icon">📅</span></div><strong><?=count($appointments)?></strong><small>histórico</small></div><div class="stat-card"><div class="stat-top"><span>Diagnósticos</span><span class="stat-icon">🩺</span></div><strong><?=count($diagnoses)?></strong><small>registrados</small></div><div class="stat-card"><div class="stat-top"><span>Receitas</span><span class="stat-icon">💊</span></div><strong><?=count($prescriptions)?></strong><small>eletrônicas</small></div><div class="stat-card"><div class="stat-top"><span>Exames</span><span class="stat-icon">🧪</span></div><strong><?=count($exams)?></strong><small>solicitações/resultados</small></div></section>

<section class="panel"><div class="panel-header"><div><h3>👤 Dados pessoais e contato</h3><p>Identificação, endereço e contato de emergência.</p></div></div>
<?php if($isOwner):?><form method="post" action="actions.php" enctype="multipart/form-data"><?=csrf_field()?><input type="hidden" name="action" value="save_clinic_patient_details"><input type="hidden" name="return_page" value="clinic_record"><input type="hidden" name="patient_id" value="<?=$patientId?>"><div class="form-grid"><div class="form-group"><label>Foto</label><input class="input" type="file" name="photo_file" accept="image/jpeg,image/png,image/webp"></div><div class="form-group"><label>Nome completo</label><input class="input" name="name" value="<?=e($patient['name'])?>" required></div><div class="form-group"><label>CPF</label><input class="input" name="document" value="<?=e($patient['document'])?>"></div><div class="form-group"><label>RG</label><input class="input" name="rg" value="<?=e($patient['rg'])?>"></div><div class="form-group"><label>Sexo</label><input class="input" name="sex" value="<?=e($patient['sex'])?>"></div><div class="form-group"><label>Estado civil</label><input class="input" name="marital_status" value="<?=e($patient['marital_status'])?>"></div><div class="form-group"><label>Profissão</label><input class="input" name="occupation" value="<?=e($patient['occupation'])?>"></div><div class="form-group"><label>Cartão SUS</label><input class="input" name="sus_card" value="<?=e($patient['sus_card'])?>"></div><div class="form-group"><label>Nascimento</label><input class="input" type="date" name="birth_date" value="<?=e($patient['birth_date'])?>"></div><div class="form-group"><label>Celular</label><input class="input" name="phone" data-phone-mask value="<?=e($patient['phone'])?>"></div><div class="form-group"><label>WhatsApp</label><input class="input" name="whatsapp" data-phone-mask value="<?=e($patient['whatsapp']?:$patient['phone'])?>"></div><div class="form-group"><label>Telefone residencial</label><input class="input" name="residential_phone" value="<?=e($patient['residential_phone'])?>"></div><div class="form-group"><label>E-mail</label><input class="input" type="email" name="email" value="<?=e($patient['email'])?>"></div><div class="form-group"><label>CEP</label><input class="input" name="cep" value="<?=e($patient['cep'])?>"></div><div class="form-group full"><label>Rua / endereço</label><input class="input" name="address" value="<?=e($patient['address'])?>"></div><div class="form-group"><label>Número</label><input class="input" name="address_number" value="<?=e($patient['address_number'])?>"></div><div class="form-group"><label>Bairro</label><input class="input" name="neighborhood" value="<?=e($patient['neighborhood'])?>"></div><div class="form-group"><label>Cidade</label><input class="input" name="city" value="<?=e($patient['city'])?>"></div><div class="form-group"><label>Estado</label><input class="input" name="state" value="<?=e($patient['state'])?>" maxlength="2"></div><div class="form-group"><label>Complemento</label><input class="input" name="complement" value="<?=e($patient['complement'])?>"></div><div class="form-group"><label>Ponto de referência</label><input class="input" name="reference_point" value="<?=e($patient['reference_point'])?>"></div><div class="form-group"><label>Contato de emergência</label><input class="input" name="emergency_name" value="<?=e($patient['emergency_name'])?>"></div><div class="form-group"><label>Parentesco</label><input class="input" name="emergency_relation" value="<?=e($patient['emergency_relation'])?>"></div><div class="form-group"><label>Telefone emergência</label><input class="input" name="emergency_phone" data-phone-mask value="<?=e($patient['emergency_phone'])?>"></div><div class="form-group"><label>WhatsApp emergência</label><input class="input" name="emergency_whatsapp" data-phone-mask value="<?=e($patient['emergency_whatsapp'])?>"></div><div class="form-group full"><label>Observações de emergência</label><textarea name="emergency_notes"><?=e($patient['emergency_notes'])?></textarea></div><div class="form-group full"><label>Observações gerais</label><textarea name="notes"><?=e($patient['notes'])?></textarea></div></div><button class="btn btn-primary">Salvar dados do paciente</button></form>
<?php else:?><div class="profile-hero"><?=avatar_html(['avatar'=>$patient['photo'],'name'=>$patient['name']])?><div><h3><?=e($patient['name'])?></h3><p><?=e($patient['document']?:'CPF não informado')?> • <?=e($patient['rg']?:'RG não informado')?></p><p><?=e(format_phone($patient['whatsapp']?:$patient['phone']))?> • <?=e($patient['email'])?></p><p><?=e(trim(($patient['address']?:'').' '.($patient['address_number']?:'').' '.($patient['neighborhood']?:'').' '.($patient['city']?:'').'/'.($patient['state']?:'')))?></p><?php if($patient['emergency_name']):?><p><strong>Emergência:</strong> <?=e($patient['emergency_name'].' • '.format_phone($patient['emergency_phone']))?></p><?php endif;?></div></div><?php endif;?></section>

<section class="panel"><div class="panel-header"><div><h3>📅 Histórico de consultas</h3></div></div><div class="table-wrap"><table><thead><tr><th>Data</th><th>Profissional</th><th>Especialidade</th><th>Motivo/observação</th><th>Status</th><th>Documento</th></tr></thead><tbody><?php if(!$appointments):?><tr><td colspan="6">Nenhuma consulta.</td></tr><?php endif;?><?php foreach($appointments as $a):?><tr><td><?=e(date('d/m/Y',strtotime($a['appointment_date'])).' '.substr($a['appointment_time'],0,5))?></td><td><?=e($a['professional_name']?:'A definir')?></td><td><?=e($a['specialty_name']?:'Consulta')?></td><td><?=e(short_text((string)$a['notes'],90))?></td><td><?=status_badge($a['status'])?></td><td><a class="btn btn-secondary btn-sm" target="_blank" href="clinic_receipt.php?id=<?=(int)$a['id']?>&download=1">PNG</a></td></tr><?php endforeach;?></tbody></table></div></section>

<section class="panel"><div class="panel-header"><div><h3>🧠 Histórico clínico</h3><p>Antecedentes, sintomas, avaliações, alergias, medicamentos, condutas e evolução.</p></div></div><div class="cards-list"><?php if(!$records):?><div class="empty-state"><strong>Sem registros clínicos</strong></div><?php endif;?><?php foreach($records as $r):?><article class="item-card"><div class="item-body"><h3><?=e($r['professional_name']?:'Profissional não informado')?><?php if(!empty($r['professional_specialty'])):?> • <?=e($r['professional_specialty'])?><?php endif;?></h3><small><?=e(date('d/m/Y H:i',strtotime($r['created_at'])))?></small><p><strong>Sintomas:</strong> <?=e($r['symptoms']?:'—')?></p><p><strong>Avaliação:</strong> <?=e($r['assessment']?:'—')?></p><p><strong>Diagnóstico:</strong> <?=e($r['diagnosis']?:'—')?></p><p><strong>Alergias:</strong> <?=e($r['allergies']?:'—')?></p><p><strong>Medicamentos:</strong> <?=e($r['medications']?:'—')?></p><p><strong>Conduta:</strong> <?=e($r['prescriptions']?:'—')?></p><p><strong>Exames solicitados:</strong> <?=e($r['exam_requests']?:'—')?></p><p><strong>Observações/evolução:</strong> <?=e($r['observations']?:'—')?></p><?php if($r['attachment_path']):?><a class="btn btn-secondary btn-sm" target="_blank" href="<?=e(media_url($r['attachment_path']))?>">Acessar Anexo</a><?php endif;?></div></article><?php endforeach;?></div></section>

<section class="panel"><div class="panel-header"><div><h3>🩺 Diagnósticos</h3><p>Histórico organizado com CID, observações e evolução.</p></div></div><?php if($canClinicalEdit):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_clinic_diagnosis"><input type="hidden" name="return_page" value="clinic_record"><input type="hidden" name="patient_id" value="<?=$patientId?>"><div class="form-grid"><div class="form-group full"><label>Diagnóstico</label><input class="input" name="diagnosis" required></div><div class="form-group"><label>CID</label><input class="input" name="cid"></div><div class="form-group"><label>Data</label><input class="input" type="date" name="diagnosed_at" value="<?=date('Y-m-d')?>"></div><div class="form-group full"><label>Observações</label><textarea name="observations"></textarea></div><div class="form-group full"><label>Evolução</label><textarea name="evolution"></textarea></div></div><button class="btn btn-primary">Registrar diagnóstico</button></form><?php endif;?><div class="table-wrap" style="margin-top:14px"><table><thead><tr><th>Data</th><th>Diagnóstico</th><th>CID</th><th>Profissional</th><th>Evolução</th></tr></thead><tbody><?php foreach($diagnoses as $d):?><tr><td><?=e(date('d/m/Y',strtotime($d['diagnosed_at'])))?></td><td><?=e($d['diagnosis'])?></td><td><?=e($d['cid']?:'—')?></td><td><?=e($d['professional_name']?:'Profissional não informado')?><?php if(!empty($d['professional_specialty'])):?><small style="display:block"><?=e($d['professional_specialty'])?></small><?php endif;?></td><td><?=e(short_text((string)$d['evolution'],100))?></td></tr><?php endforeach;?></tbody></table></div></section>

<section class="panel"><div class="panel-header"><div><h3>💊 Receitas eletrônicas e medicamentos</h3><p>O profissional pode liberar a receita no painel do paciente e informar horários para lembretes automáticos.</p></div></div><?php if($isProfessional):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_clinic_prescription"><input type="hidden" name="return_page" value="clinic_record"><input type="hidden" name="patient_id" value="<?=$patientId?>"><div class="form-grid"><div class="form-group"><label>Medicamento</label><input class="input" name="medicine_name" required></div><div class="form-group"><label>Dosagem</label><input class="input" name="dosage"></div><div class="form-group"><label>Frequência</label><input class="input" name="frequency" placeholder="Ex.: 8/8 horas"></div><div class="form-group"><label>Duração</label><input class="input" name="duration_text" placeholder="Ex.: 7 dias"></div><div class="form-group"><label>Início</label><input class="input" type="date" name="start_date" value="<?=date('Y-m-d')?>"></div><div class="form-group"><label>Fim</label><input class="input" type="date" name="end_date"></div><div class="form-group full"><label>Horários dos lembretes</label><input class="input" name="times_csv" placeholder="08:00, 16:00, 23:00"><small>Separe os horários por vírgula.</small></div><div class="form-group full"><label>Orientações</label><textarea name="instructions"></textarea></div><label class="check-line full"><input type="checkbox" name="release_to_patient" value="1" checked> Liberar esta receita para o paciente</label></div><button class="btn btn-primary">Emitir receita eletrônica</button></form><?php endif;?><div class="cards-list" style="margin-top:14px"><?php if(!$prescriptions):?><div class="empty-state"><strong>Nenhuma receita emitida</strong></div><?php endif;?><?php foreach($prescriptions as $rx):if($isPatient&&!$rx['release_to_patient'])continue;?><article class="item-card"><div class="item-body"><div class="service-title-line"><h3><?=e($rx['title']?:'Receita eletrônica')?></h3><?=status_badge($rx['status'])?></div><p><strong>Médico:</strong> <?=e($rx['professional_name']?:'Profissional não informado')?><?php if(!empty($rx['professional_specialty'])):?> • <strong>Especialidade:</strong> <?=e($rx['professional_specialty'])?><?php endif;?> • <?=e(date('d/m/Y',strtotime($rx['prescribed_at'])))?></p><?php foreach($prescriptionItems[(int)$rx['id']]??[] as $it):?><div class="notice"><strong><?=e($it['medicine_name'])?></strong><br><?=e($it['dosage'])?> <?=e($it['frequency'])?> <?=e($it['duration_text'])?><br><?php if($it['times_csv']):?>⏰ <?=e($it['times_csv'])?><br><?php endif;?><?=e($it['observations'])?></div><?php endforeach;?><p><?=nl2br(e($rx['instructions']))?></p></div></article><?php endforeach;?></div></section>

<section class="panel"><div class="panel-header"><div><h3>🧪 Exames</h3></div></div><div class="table-wrap"><table><thead><tr><th>Exame</th><th>Data</th><th>Status</th><th>Resultado</th></tr></thead><tbody><?php foreach($exams as $e):?><tr><td><?=e($e['exam_name']?:'Exame')?></td><td><?=e($e['scheduled_date']?date('d/m/Y',strtotime($e['scheduled_date'])):'A definir')?> <?=e(substr((string)$e['scheduled_time'],0,5))?></td><td><?=status_badge($e['status'])?></td><td><?php if($e['result_path']):?><a class="btn btn-secondary btn-sm" target="_blank" href="<?=e(media_url($e['result_path']))?>">Acessar Arquivo</a><?php endif;?> <?=e(short_text((string)$e['result_notes'],80))?></td></tr><?php endforeach;?></tbody></table></div></section>

<section class="panel"><div class="panel-header"><div><h3>📎 Documentos anexados</h3><p>Exames, laudos, receitas, atestados, relatórios, encaminhamentos e documentos pessoais.</p></div></div><?php if($canClinicalEdit||$isOwner):?><form method="post" action="actions.php" enctype="multipart/form-data"><?=csrf_field()?><input type="hidden" name="action" value="upload_clinic_patient_document"><input type="hidden" name="return_page" value="clinic_record"><input type="hidden" name="patient_id" value="<?=$patientId?>"><div class="form-grid"><div class="form-group"><label>Tipo</label><select name="document_type"><option value="exam">Exame</option><option value="report">Laudo/relatório</option><option value="prescription">Receita</option><option value="certificate">Atestado</option><option value="referral">Encaminhamento</option><option value="personal">Documento pessoal</option><option value="other">Outro</option></select></div><div class="form-group"><label>Título</label><input class="input" name="title" required></div><div class="form-group full"><label>Arquivo</label><input class="input" type="file" name="document_file" accept="application/pdf,image/jpeg,image/png,image/webp" required></div><div class="form-group full"><label>Observações</label><textarea name="notes"></textarea></div></div><button class="btn btn-primary">Anexar documento</button></form><?php endif;?><div class="table-wrap" style="margin-top:14px"><table><thead><tr><th>Documento</th><th>Tipo</th><th>Data</th><th>Acessar</th></tr></thead><tbody><?php foreach($documents as $d):?><tr><td><strong><?=e($d['title'])?></strong><small style="display:block"><?=e($d['notes'])?></small></td><td><?=e(status_label($d['document_type']))?></td><td><?=e(date('d/m/Y H:i',strtotime($d['created_at'])))?></td><td><a class="btn btn-secondary btn-sm" target="_blank" href="<?=e(media_url($d['file_path']))?>">Acessar</a></td></tr><?php endforeach;?></tbody></table></div></section>
