<?php
$petPage=!empty($petTutorMode)?'pet_tutor':'petcare';
$u=current_user();
$uid=(int)($u['id']??0);
$role=(string)($u['role']??'');
$linked=resolve_company_id_for_user($u);
$adminView=is_super_admin();
$petcareCompanies=[];
if($adminView){
    try{foreach(db()->query("SELECT id,name,type,sector FROM companies WHERE status<>'deleted' ORDER BY name")->fetchAll() as $cc)if(company_is_petcare((int)$cc['id']))$petcareCompanies[]=$cc;}catch(Throwable $e){}
}
$manage=$adminView||(in_array($role,['company','employee'],true)&&$linked>0&&company_is_petcare($linked));
$memberships=$manage?[]:pet_clients_for_user($uid);
$companyId=$adminView?(int)request('pet_company',($petcareCompanies[0]['id']??0)):($manage?$linked:(int)request('pet_company',($memberships[0]['company_id']??0)));
if(!$manage){
    $allowed=array_map('intval',array_column($memberships,'company_id'));
    if(!in_array($companyId,$allowed,true))$companyId=(int)($allowed[0]??0);
}
if($adminView&&$companyId>0&&!company_is_petcare($companyId))$companyId=(int)($petcareCompanies[0]['id']??0);
if($companyId<1){
    ?>
    <section class="page-intro"><div><span class="mini-label">🐶 ÁREA DO TUTOR</span><h2>Meus pets e agendamentos</h2><p>Aqui você acompanha os atendimentos veterinários dos seus pets.</p></div><div class="actions"><a class="btn btn-secondary" href="dashboard.php?page=home">← Início</a></div></section>
    <section class="panel"><div class="empty-state"><strong>Nenhuma clínica veterinária vinculada</strong>Assim que uma clínica vincular sua conta e cadastrar seu pet, os horários e agendamentos aparecerão nesta área.</div></section>
    <?php return;
}
$cq=db()->prepare('SELECT * FROM companies WHERE id=?');
$cq->execute([$companyId]);
$company=$cq->fetch();
if(!$company)return;
$canToggleBooking=$adminView||($role==='company'&&$linked===$companyId)||($role==='employee'&&$linked===$companyId&&company_member_access_level($u)==='admin');
$q=db()->prepare("SELECT pc.*,u.public_id platform_public_id,u.name platform_user_name FROM pet_clients pc LEFT JOIN users u ON u.id=pc.platform_user_id WHERE pc.company_id=? AND pc.status='active' ORDER BY COALESCE(NULLIF(u.name,''),pc.name)");
$q->execute([$companyId]);
$clients=$q->fetchAll();
foreach($clients as &$client){if(trim((string)($client['platform_user_name']??''))!=='')$client['name']=(string)$client['platform_user_name'];}
unset($client);
if($manage){$clientIds=array_map('intval',array_column($clients,'id'));}
else{$clientIds=[];foreach($memberships as $m)if((int)$m['company_id']===$companyId)$clientIds[]=(int)$m['id'];}
$clientWhere=$clientIds?implode(',',array_fill(0,count($clientIds),'?')):'0';
$petParams=$manage?[$companyId]:$clientIds;
if($manage){
    $q=db()->prepare("SELECT p.*,COALESCE(NULLIF(u.name,''),pc.name) tutor_name,pc.phone tutor_phone,pc.whatsapp tutor_whatsapp FROM pets p JOIN pet_clients pc ON pc.id=p.client_id LEFT JOIN users u ON u.id=pc.platform_user_id WHERE p.company_id=? AND p.status='active' ORDER BY p.name");
    $q->execute([$companyId]);
}else{
    $q=db()->prepare("SELECT p.*,COALESCE(NULLIF(u.name,''),pc.name) tutor_name,pc.phone tutor_phone,pc.whatsapp tutor_whatsapp FROM pets p JOIN pet_clients pc ON pc.id=p.client_id LEFT JOIN users u ON u.id=pc.platform_user_id WHERE p.client_id IN ($clientWhere) AND p.status='active' ORDER BY p.name");
    $q->execute($petParams);
}
$pets=$q->fetchAll();
$petIds=array_map('intval',array_column($pets,'id'));
$petById=[];foreach($pets as $p)$petById[(int)$p['id']]=$p;
$petWhere=$petIds?implode(',',array_fill(0,count($petIds),'?')):'0';
if(!function_exists('pet_rows')){function pet_rows(string $table,string $order,array $ids): array {if(!$ids)return [];try{$marks=implode(',',array_fill(0,count($ids),'?'));$q=db()->prepare("SELECT * FROM $table WHERE pet_id IN ($marks) ORDER BY $order");$q->execute($ids);return $q->fetchAll();}catch(Throwable $e){return [];}}}
$appointments=pet_rows('pet_appointments','appointment_date DESC, appointment_time DESC',$petIds);
$records=pet_rows('pet_medical_records','id DESC',$petIds);
$vaccines=pet_rows('pet_vaccines','COALESCE(next_dose_at,expires_at,applied_at) DESC',$petIds);
$exams=pet_rows('pet_exams','id DESC',$petIds);
$prescriptions=pet_rows('pet_prescriptions','prescribed_at DESC',$petIds);
$hospitalizations=pet_rows('pet_hospitalizations','admitted_at DESC',$petIds);
$today=0;$servicesToday=0;$lowStock=[];$expiring=[];$products=[];$stockMovements=[];$suppliers=[];$revenueToday=0;$vaccinesDue=0;
if($manage){
    foreach($appointments as $a){if(($a['appointment_date']??'')===date('Y-m-d')&&!in_array($a['status'],['cancelled','completed'],true))$today++;if(($a['appointment_date']??'')===date('Y-m-d')){$servicesToday++;if(($a['status']??'')==='completed')$revenueToday+=(float)($a['amount']??0);}}
    foreach($vaccines as $v){$due=$v['next_dose_at']?:$v['expires_at'];if($due&&$due<=date('Y-m-d',strtotime('+7 days'))&&$due>=date('Y-m-d'))$vaccinesDue++;}
    $pq=db()->prepare("SELECT * FROM products WHERE company_id=? AND deleted_at IS NULL ORDER BY name");$pq->execute([$companyId]);$products=$pq->fetchAll();
    foreach($products as $pr){if((float)$pr['stock_min']>0&&(float)$pr['stock']<=(float)$pr['stock_min'])$lowStock[]=$pr;if(!empty($pr['expires_at'])&&$pr['expires_at']<=date('Y-m-d',strtotime('+30 days')))$expiring[]=$pr;}
    $mq=db()->prepare("SELECT m.*,p.name product_name,u.name user_name FROM pet_stock_movements m JOIN products p ON p.id=m.product_id LEFT JOIN users u ON u.id=m.created_by WHERE m.company_id=? ORDER BY m.id DESC LIMIT 100");$mq->execute([$companyId]);$stockMovements=$mq->fetchAll();
    $sq=db()->prepare("SELECT * FROM pet_suppliers WHERE company_id=? AND status='active' ORDER BY name");$sq->execute([$companyId]);$suppliers=$sq->fetchAll();
}
$petName=function($id)use($petById){return $petById[(int)$id]['name']??'Pet';};
$weekdayNames=['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado'];
$selectedPetDate=trim((string)request('pet_date',date('Y-m-d')));
if(!preg_match('/^\d{4}-\d{2}-\d{2}$/',$selectedPetDate)||strtotime($selectedPetDate)<strtotime(date('Y-m-d')))$selectedPetDate=date('Y-m-d');
$petBookingDays=[];
for($i=0;$i<14;$i++){$d=date('Y-m-d',strtotime('+'.$i.' day'));$petBookingDays[]=['date'=>$d,'weekday'=>(int)date('w',strtotime($d)),'open'=>pet_booking_open_count($companyId,$d)];}
$selectedSlots=pet_booking_availability_rows($companyId,$selectedPetDate);
$managerSlots=[];
if($canToggleBooking){try{$sq=db()->prepare("SELECT s.*,(SELECT COUNT(*) FROM pet_appointments a WHERE a.slot_id=s.id AND a.status<>'cancelled') booked FROM pet_booking_slots s WHERE s.company_id=? AND s.slot_date>=? AND s.status='active' ORDER BY s.slot_date,s.slot_time LIMIT 120");$sq->execute([$companyId,date('Y-m-d')]);$managerSlots=$sq->fetchAll();}catch(Throwable $e){$managerSlots=[];}}
?>
<section class="page-intro"><div><span class="mini-label"><?=$manage?'🐾 VETERINÁRIA / PET SHOP':'🐶 ÁREA DO TUTOR'?></span><h2><?=e($company['name'])?></h2><p><?=$manage?'Gestão de tutores, pets, consultas, banho e tosa, vacinas, exames, internação e estoque.':'Veja os horários liberados pela clínica, agende seu pet e acompanhe seus atendimentos.'?></p></div><div class="actions"><a class="btn btn-secondary" href="dashboard.php?page=home">← Início</a></div></section>
<?php if($adminView&&count($petcareCompanies)>1):?><section class="panel"><form method="get" action="dashboard.php" class="module-toolbar"><input type="hidden" name="page" value="petcare"><div class="form-group"><label>Veterinária / Pet Shop</label><select name="pet_company"><?php foreach($petcareCompanies as $cc):?><option value="<?=(int)$cc['id']?>"<?=selected($companyId,$cc['id'])?>><?=e($cc['name'])?></option><?php endforeach;?></select></div><button class="btn btn-primary">Acessar Empresa</button></form></section><?php endif;?>
<?php if(!$manage&&count($memberships)>1):?><section class="panel"><form method="get" action="dashboard.php" class="module-toolbar"><input type="hidden" name="page" value="<?=e($petPage)?>"><div class="form-group"><label>Instituição</label><select name="pet_company"><?php foreach($memberships as $m):?><option value="<?=(int)$m['company_id']?>"<?=selected($companyId,$m['company_id'])?>><?=e($m['company_name'])?></option><?php endforeach;?></select></div><button class="btn btn-secondary">Trocar</button></form></section><?php endif;?>
<?php if(!$manage):?><section class="panel"><div class="notice"><strong>🕒 Horário de funcionamento da clínica</strong><br><?=e(substr((string)($company['pet_opening_time']??'08:00'),0,5))?> às <?=e(substr((string)($company['pet_closing_time']??'18:00'),0,5))?></div></section><?php endif;?>
<?php if($canToggleBooking):?>
<section class="panel" id="agenda-settings">
  <div class="panel-header"><div><h3>📅 Agendamento online da clínica veterinária</h3><p>Defina o horário de funcionamento e ative a agenda para os tutores.</p></div><?=status_badge(!empty($company['pet_booking_enabled'])?'active':'inactive')?></div>
  <form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_pet_booking_setting"><input type="hidden" name="company_id" value="<?=$companyId?>"><input type="hidden" name="return_anchor" value="agenda-settings">
    <div class="form-grid"><div class="form-group"><label>Início do funcionamento</label><input type="time" name="pet_opening_time" value="<?=e(substr((string)($company['pet_opening_time']??'08:00'),0,5))?>" required></div><div class="form-group"><label>Encerramento</label><input type="time" name="pet_closing_time" value="<?=e(substr((string)($company['pet_closing_time']??'18:00'),0,5))?>" required></div><label class="check-line full"><input type="checkbox" name="pet_booking_enabled" value="1" <?=!empty($company['pet_booking_enabled'])?'checked':''?>> Permitir que tutores agendem pelos horários liberados</label></div>
    <button class="btn btn-primary">Salvar funcionamento e agenda</button>
  </form>
</section>
<section class="panel" id="booking-slots">
  <div class="panel-header"><div><h3>🗓️ Liberar agendamentos</h3><p>Libere um horário específico ou gere vários horários de uma só vez.</p></div></div>
  <details open><summary class="btn btn-secondary btn-sm">+ Liberar um horário</summary><form method="post" action="actions.php" style="margin-top:14px"><?=csrf_field()?><input type="hidden" name="action" value="save_pet_booking_slot"><input type="hidden" name="company_id" value="<?=$companyId?>"><input type="hidden" name="return_page" value="petcare"><input type="hidden" name="return_anchor" value="booking-slots">
    <div class="form-grid"><div class="form-group"><label>Data</label><input type="date" name="slot_date" min="<?=date('Y-m-d')?>" required></div><div class="form-group"><label>Hora</label><input type="time" name="slot_time" min="<?=e(substr((string)($company['pet_opening_time']??'08:00'),0,5))?>" max="<?=e(substr((string)($company['pet_closing_time']??'18:00'),0,5))?>" required></div><div class="form-group"><label>Tipo</label><select name="service_type"><option value="consultation">Consulta veterinária</option><option value="return">Retorno</option><option value="vaccine">Vacinação</option><option value="bath">Banho</option><option value="grooming">Tosa</option><option value="hygienic_grooming">Tosa higiênica</option><option value="boarding">Hospedagem</option><option value="exam">Exame</option><option value="surgery">Cirurgia</option><option value="other">Outro</option></select></div><div class="form-group"><label>Nome do serviço</label><input name="service_name" placeholder="Opcional"></div><div class="form-group"><label>Valor</label><input name="amount" inputmode="decimal" value="0"></div><div class="form-group"><label>Vagas nesse horário</label><input type="number" min="1" max="50" name="capacity" value="1" required></div></div>
    <button class="btn btn-primary">+ Liberar horário</button>
  </form></details>
  <details style="margin-top:14px"><summary class="btn btn-primary btn-sm">⚡ Liberar vários horários</summary><form method="post" action="actions.php" style="margin-top:14px"><?=csrf_field()?><input type="hidden" name="action" value="bulk_save_pet_booking_slots"><input type="hidden" name="company_id" value="<?=$companyId?>"><input type="hidden" name="return_page" value="petcare"><input type="hidden" name="return_anchor" value="booking-slots">
    <div class="form-grid"><div class="form-group"><label>Data inicial</label><input type="date" name="date_start" min="<?=date('Y-m-d')?>" value="<?=date('Y-m-d')?>" required></div><div class="form-group"><label>Data final</label><input type="date" name="date_end" min="<?=date('Y-m-d')?>" value="<?=date('Y-m-d')?>" required></div><div class="form-group"><label>Das</label><input type="time" name="start_time" value="<?=e(substr((string)($company['pet_opening_time']??'08:00'),0,5))?>" required></div><div class="form-group"><label>Até</label><input type="time" name="end_time" value="<?=e(substr((string)($company['pet_closing_time']??'18:00'),0,5))?>" required></div><div class="form-group"><label>Intervalo entre horários</label><select name="interval_minutes"><option value="15">15 minutos</option><option value="20">20 minutos</option><option value="30" selected>30 minutos</option><option value="45">45 minutos</option><option value="60">1 hora</option><option value="90">1h30</option><option value="120">2 horas</option></select></div><div class="form-group"><label>Vagas por horário</label><input type="number" min="1" max="50" name="capacity" value="1" required></div><div class="form-group"><label>Tipo</label><select name="service_type"><option value="consultation">Consulta veterinária</option><option value="return">Retorno</option><option value="vaccine">Vacinação</option><option value="bath">Banho</option><option value="grooming">Tosa</option><option value="hygienic_grooming">Tosa higiênica</option><option value="boarding">Hospedagem</option><option value="exam">Exame</option><option value="surgery">Cirurgia</option><option value="other">Outro</option></select></div><div class="form-group"><label>Nome do serviço</label><input name="service_name" placeholder="Opcional"></div><div class="form-group"><label>Valor</label><input name="amount" inputmode="decimal" value="0"></div><div class="form-group full"><label>Dias da semana</label><div class="actions"><?php foreach($weekdayNames as $wi=>$wn):?><label class="check-line"><input type="checkbox" name="weekdays[]" value="<?=$wi?>" <?=in_array($wi,[1,2,3,4,5],true)?'checked':''?>> <?=e($wn)?></label><?php endforeach;?></div><small>O sistema cria automaticamente todos os horários do período, respeitando o intervalo escolhido.</small></div></div>
    <button class="btn btn-primary">⚡ Liberar vários agendamentos</button>
  </form></details>
  <?php if(!$managerSlots):?><div class="empty-state" style="margin-top:16px"><strong>Nenhum horário futuro liberado</strong>Cadastre acima a primeira data e hora.</div><?php else:?><div class="slot-list" style="margin-top:16px"><?php foreach($managerSlots as $slot):$rem=max(0,(int)$slot['capacity']-(int)$slot['booked']);?><span class="slot-pill <?=$rem<1?'full':''?>"><strong><?=e(date('d/m',strtotime($slot['slot_date'])))?> <?=e(substr($slot['slot_time'],0,5))?></strong> • <?=e($slot['service_name']?:pet_service_label($slot['service_type']))?> • <?=$rem?>/<?=e($slot['capacity'])?> livre(s) <form method="post" action="actions.php" style="display:inline"><?=csrf_field()?><input type="hidden" name="action" value="delete_pet_booking_slot"><input type="hidden" name="company_id" value="<?=$companyId?>"><input type="hidden" name="id" value="<?=(int)$slot['id']?>"><input type="hidden" name="return_page" value="petcare"><input type="hidden" name="return_anchor" value="booking-slots"><button class="btn btn-danger btn-sm" data-confirm="Remover este horário?">×</button></form></span><?php endforeach;?></div><?php endif;?>
</section>
<?php elseif(!$manage&&!empty($company['pet_booking_enabled'])):?>
<section class="panel"><div class="panel-header"><div><h3>Próximas datas com vagas</h3><p>Toque em uma data para acessar os horários disponíveis. A lista vai direto para a primeira vaga.</p></div></div><div class="available-date-strip" data-auto-scroll-available><?php foreach($petBookingDays as $d):?><a class="date-chip<?=$d['open']>0?' available':' busy'?><?=$selectedPetDate===$d['date']?' active':''?>" data-available="<?=$d['open']>0?'1':'0'?>" href="dashboard.php?page=<?=e($petPage)?>&pet_company=<?=$companyId?>&pet_date=<?=e($d['date'])?>#pet-available"><b><?=e($weekdayNames[$d['weekday']])?></b><span><?=e(date('d/m',strtotime($d['date'])))?></span><small><?=$d['open']>0?($d['open'].' vaga(s)'):'Sem vaga'?></small></a><?php endforeach;?></div></section>
<section class="panel" id="pet-available"><div class="panel-header"><div><h2>Disponíveis em <?=e(date('d/m/Y',strtotime($selectedPetDate)))?></h2><p><?=e($weekdayNames[(int)date('w',strtotime($selectedPetDate))])?> • horários liberados pela clínica.</p></div></div>
<?php $openSlots=array_values(array_filter($selectedSlots,static fn($s)=>(int)$s['remaining']>0));if(!$openSlots):?><div class="empty-state"><strong>Sem horários disponíveis</strong>A clínica ainda não liberou vagas para esta data.</div><?php else:?><div class="availability-grid"><?php foreach($openSlots as $slot):?><article class="availability-card"><h3><?=e($slot['service_name']?:pet_service_label($slot['service_type']))?></h3><p><strong><?=e(substr($slot['slot_time'],0,5))?></strong> • <?=e((string)$slot['remaining'])?> vaga(s)<?=((float)$slot['amount']>0)?' • '.money($slot['amount']):''?></p><?php if($pets):?><form method="post" action="actions.php" style="margin-top:12px"><?=csrf_field()?><input type="hidden" name="action" value="save_pet_appointment"><input type="hidden" name="company_id" value="<?=$companyId?>"><input type="hidden" name="slot_id" value="<?=(int)$slot['id']?>"><input type="hidden" name="return_page" value="<?=$petPage?>"><input type="hidden" name="return_anchor" value="agenda"><div class="form-group"><label>Pet</label><select name="pet_id" required><?php foreach($pets as $p):?><option value="<?=(int)$p['id']?>"><?=e($p['name'])?></option><?php endforeach;?></select></div><div class="form-group"><label>Observação (opcional)</label><input name="notes" placeholder="Algo que a clínica precisa saber?"></div><button class="btn btn-primary btn-sm">Agendar <?=e(substr($slot['slot_time'],0,5))?></button></form><?php else:?><div class="notice">Peça para a clínica cadastrar ou vincular um pet à sua conta antes de agendar.</div><?php endif;?></article><?php endforeach;?></div><?php endif;?>
</section>
<?php elseif(!$manage):?><div class="alert alert-warning">A clínica ainda não liberou o agendamento online para os pets.</div><?php endif;?>
<section class="stats-grid"><a class="stat-card stat-card-link" href="#pets"><div class="stat-top"><span>Pets</span><span class="stat-icon">🐶</span></div><strong><?=count($pets)?></strong><small>cadastrados</small></a><?php if($manage):?><a class="stat-card stat-card-link" href="#clients"><div class="stat-top"><span>Clientes</span><span class="stat-icon">👤</span></div><strong><?=count($clients)?></strong><small>tutores</small></a><a class="stat-card stat-card-link" href="#agenda"><div class="stat-top"><span>Hoje</span><span class="stat-icon">📅</span></div><strong><?=$today?></strong><small>agendamentos</small></a><a class="stat-card stat-card-link" href="#stock"><div class="stat-top"><span>Estoque baixo</span><span class="stat-icon">📦</span></div><strong><?=count($lowStock)?></strong><small>produtos</small></a><a class="stat-card stat-card-link" href="#agenda"><div class="stat-top"><span>Faturamento hoje</span><span class="stat-icon">💰</span></div><strong><?=money($revenueToday)?></strong><small>serviços concluídos</small></a><a class="stat-card stat-card-link" href="#vaccines"><div class="stat-top"><span>Vacinas próximas</span><span class="stat-icon">💉</span></div><strong><?=$vaccinesDue?></strong><small>até 7 dias</small></a><?php else:?><a class="stat-card stat-card-link" href="#vaccines"><div class="stat-top"><span>Vacinas</span><span class="stat-icon">💉</span></div><strong><?=count($vaccines)?></strong><small>registros</small></a><a class="stat-card stat-card-link" href="#agenda"><div class="stat-top"><span>Agendamentos</span><span class="stat-icon">📅</span></div><strong><?=count($appointments)?></strong><small>histórico</small></a><?php endif;?></section>

<?php if($manage):?><section class="panel" id="clients"><div class="panel-header"><div><h2>👤 Clientes / tutores</h2><p>Digite o ID do cliente para preencher automaticamente ou cadastre manualmente. Tutores existentes podem ser editados ou removidos.</p></div><span class="status status-active"><?=count($clients)?> cliente(s)</span></div><details><summary class="btn btn-primary btn-sm">+ Novo tutor</summary><form method="post" action="actions.php" enctype="multipart/form-data" style="margin-top:14px" data-pet-tutor-form><?=csrf_field()?><input type="hidden" name="action" value="save_pet_client"><input type="hidden" name="return_anchor" value="clients"><input type="hidden" name="company_id" value="<?=$companyId?>"><div class="form-grid"><div class="form-group full"><label>ID do cliente na plataforma</label><div class="actions"><input class="input" name="platform_public_id" placeholder="LXU-XXXX-XXXX" data-tutor-id style="flex:1"><button class="btn btn-secondary btn-sm" type="button" data-tutor-lookup>Buscar ID</button></div><small data-tutor-lookup-status>Ao localizar o ID, nome, telefone, e-mail e endereço disponíveis serão preenchidos.</small></div><div class="form-group"><label>Nome</label><input class="input" name="name" required></div><div class="form-group"><label>CPF</label><input class="input" name="document"></div><div class="form-group"><label>Telefone</label><input class="input" name="phone" data-phone-mask></div><div class="form-group"><label>WhatsApp</label><input class="input" name="whatsapp" data-phone-mask></div><div class="form-group"><label>E-mail</label><input class="input" type="email" name="email"></div><div class="form-group"><label>Foto</label><input type="file" name="photo" accept="image/*"></div><div class="form-group full"><label>Endereço</label><input class="input" name="address"></div><div class="form-group"><label>Cidade</label><input class="input" name="city"></div><div class="form-group"><label>Estado</label><input class="input" name="state" maxlength="2"></div><div class="form-group full"><label>Observações</label><textarea name="notes"></textarea></div></div><button class="btn btn-primary">Salvar tutor</button></form></details><div class="cards-list" style="margin-top:14px"><?php foreach($clients as $c):?><article class="item-card"><div class="item-body"><h3><?=e($c['name'])?></h3><p>ID: <?=e($c['platform_public_id']?:'—')?> • <?=e(format_phone($c['whatsapp']?:$c['phone']))?></p><div class="item-meta"><span><?=e($c['city'])?><?=!empty($c['state'])?' / '.e($c['state']):''?></span><span><?=e($c['email'])?></span></div><div class="actions" style="margin-top:10px"><details><summary class="btn btn-secondary btn-sm">✏️ Editar tutor</summary><form method="post" action="actions.php" enctype="multipart/form-data" style="margin-top:12px" data-pet-tutor-form><?=csrf_field()?><input type="hidden" name="action" value="save_pet_client"><input type="hidden" name="client_id" value="<?=(int)$c['id']?>"><input type="hidden" name="company_id" value="<?=$companyId?>"><input type="hidden" name="return_anchor" value="clients"><div class="form-grid"><div class="form-group full"><label>ID do cliente</label><div class="actions"><input class="input" name="platform_public_id" value="<?=e($c['platform_public_id']?:'')?>" data-tutor-id style="flex:1"><button class="btn btn-secondary btn-sm" type="button" data-tutor-lookup>Atualizar pelo ID</button></div><small data-tutor-lookup-status></small></div><div class="form-group"><label>Nome</label><input class="input" name="name" value="<?=e($c['name'])?>" required></div><div class="form-group"><label>CPF</label><input class="input" name="document" value="<?=e($c['document'])?>"></div><div class="form-group"><label>Telefone</label><input class="input" name="phone" data-phone-mask value="<?=e($c['phone'])?>"></div><div class="form-group"><label>WhatsApp</label><input class="input" name="whatsapp" data-phone-mask value="<?=e($c['whatsapp'])?>"></div><div class="form-group"><label>E-mail</label><input class="input" type="email" name="email" value="<?=e($c['email'])?>"></div><div class="form-group"><label>Nova foto (opcional)</label><input type="file" name="photo" accept="image/*"></div><div class="form-group full"><label>Endereço</label><input class="input" name="address" value="<?=e($c['address'])?>"></div><div class="form-group"><label>Cidade</label><input class="input" name="city" value="<?=e($c['city'])?>"></div><div class="form-group"><label>Estado</label><input class="input" name="state" maxlength="2" value="<?=e($c['state'])?>"></div><div class="form-group full"><label>Observações</label><textarea name="notes"><?=e($c['notes'])?></textarea></div></div><button class="btn btn-primary btn-sm">Salvar alterações</button></form></details><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="delete_pet_client"><input type="hidden" name="company_id" value="<?=$companyId?>"><input type="hidden" name="client_id" value="<?=(int)$c['id']?>"><input type="hidden" name="return_anchor" value="clients"><button class="btn btn-danger btn-sm" data-confirm="Remover este tutor da clínica? Os pets vinculados ficarão inativos e os agendamentos futuros serão cancelados.">🗑️ Apagar tutor</button></form></div></div></article><?php endforeach;?></div></section><?php endif;?>

<section class="panel" id="pets"><div class="panel-header"><div><h2>🐶 Pets</h2><p>Ficha individual com QR Code e histórico próprio.</p></div></div><?php if($manage):?><details><summary class="btn btn-primary btn-sm">+ Cadastrar pet</summary><form method="post" action="actions.php" enctype="multipart/form-data" style="margin-top:14px"><?=csrf_field()?><input type="hidden" name="action" value="save_pet"><input type="hidden" name="return_anchor" value="pets"><input type="hidden" name="company_id" value="<?=$companyId?>"><div class="form-grid"><div class="form-group"><label>Tutor</label><select name="client_id" required><option value="">Selecione</option><?php foreach($clients as $c):?><option value="<?=(int)$c['id']?>"><?=e($c['name'])?></option><?php endforeach;?></select></div><div class="form-group"><label>Nome do pet</label><input class="input" name="name" required></div><div class="form-group"><label>Foto</label><input type="file" name="photo" accept="image/*"></div><div class="form-group"><label>Espécie</label><input class="input" name="species" placeholder="Cão, gato..."></div><div class="form-group"><label>Raça</label><input class="input" name="breed"></div><div class="form-group"><label>Sexo</label><select name="sex"><option value="">Não informado</option><option value="Macho">Macho</option><option value="Fêmea">Fêmea</option></select></div><div class="form-group"><label>Nascimento</label><input type="date" name="birth_date"></div><div class="form-group"><label>Peso (kg)</label><input class="input" name="weight" inputmode="decimal"></div><div class="form-group"><label>Cor</label><input class="input" name="color"></div><div class="form-group"><label>Porte</label><input class="input" name="size"></div><div class="form-group"><label>Microchip</label><input class="input" name="microchip"></div><div class="form-group full"><label>Alergias</label><textarea name="allergies"></textarea></div><div class="form-group full"><label>Medicamentos em uso</label><textarea name="medications"></textarea></div><div class="form-group full"><label>Doenças / observações</label><textarea name="diseases"></textarea></div></div><button class="btn btn-primary">Salvar pet</button></form></details><?php endif;?><div class="cards-list" style="margin-top:14px"><?php if(!$pets):?><div class="empty-state"><strong>Nenhum pet cadastrado</strong></div><?php endif;?><?php foreach($pets as $p):$qr=pet_public_url((string)$p['public_token']);?><article class="item-card"><div class="item-body"><h3><?=e($p['name'])?> <small>• <?=e($p['species']?:'Pet')?></small></h3><p><?=e($p['breed'])?><?=!empty($p['birth_date'])?' • '.e(date('d/m/Y',strtotime($p['birth_date']))):''?><?=!empty($p['weight'])?' • '.e(rtrim(rtrim(number_format((float)$p['weight'],2,',','.'),'0'),',')).' kg':''?></p><div class="item-meta"><span><strong>Tutor:</strong> <?=e($p['tutor_name'])?></span><span><strong>Microchip:</strong> <?=e($p['microchip']?:'—')?></span></div><?php if(!empty($p['allergies'])):?><div class="notice"><strong>⚠️ Alergias:</strong> <?=nl2br(e($p['allergies']))?></div><?php endif;?><div class="actions"><a class="btn btn-secondary btn-sm" target="_blank" href="<?=e($qr)?>">🪪 Carteira digital</a><button type="button" class="btn btn-secondary btn-sm" data-copy-text="<?=e($qr)?>">Copiar link QR</button></div></div></article><?php endforeach;?></div></section>

<section class="panel" id="agenda"><div class="panel-header"><div><h2><?=$manage?'📅 Agenda e serviços':'📅 Meus agendamentos'?></h2><p><?=$manage?'Consulta, retorno, vacinação, banho, tosa, hospedagem, exames, cirurgia e outros.':'Histórico e próximos horários dos seus pets.'?></p></div></div>
<?php if($manage&&$pets):?><details><summary class="btn btn-primary btn-sm">+ Novo agendamento manual</summary><form method="post" action="actions.php" style="margin-top:14px"><?=csrf_field()?><input type="hidden" name="action" value="save_pet_appointment"><input type="hidden" name="return_page" value="petcare"><input type="hidden" name="return_anchor" value="agenda"><input type="hidden" name="company_id" value="<?=$companyId?>"><div class="form-grid"><div class="form-group"><label>Pet</label><select name="pet_id" required><?php foreach($pets as $p):?><option value="<?=(int)$p['id']?>"><?=e($p['name'])?></option><?php endforeach;?></select></div><div class="form-group"><label>Tipo</label><select name="service_type"><option value="consultation">Consulta veterinária</option><option value="return">Retorno</option><option value="vaccine">Vacinação</option><option value="bath">Banho</option><option value="grooming">Tosa</option><option value="hygienic_grooming">Tosa higiênica</option><option value="boarding">Hospedagem</option><option value="exam">Exame</option><option value="surgery">Cirurgia</option><option value="other">Outro</option></select></div><div class="form-group"><label>Serviço</label><input class="input" name="service_name"></div><div class="form-group"><label>Profissional</label><input class="input" name="professional_name"></div><div class="form-group"><label>Data</label><input type="date" name="appointment_date" min="<?=date('Y-m-d')?>" required></div><div class="form-group"><label>Horário</label><input type="time" name="appointment_time" required></div><div class="form-group"><label>Valor</label><input class="input" name="amount" inputmode="decimal"></div><div class="form-group"><label>Forma de pagamento</label><select name="payment_method"><option value="pix">Pix</option><option value="card">Cartão</option><option value="cash">Dinheiro</option></select></div><div class="form-group full"><label>Observações</label><textarea name="notes"></textarea></div></div><button class="btn btn-primary">Salvar agendamento</button></form></details><?php endif;?>
<div class="clinic-appointment-cards" style="margin-top:14px"><?php if(!$appointments):?><div class="empty-state"><strong>Sem agendamentos</strong><?=$manage?'Nenhum atendimento cadastrado.':'Quando você agendar um horário, ele aparecerá aqui.'?></div><?php endif;?><?php foreach($appointments as $a):?><article class="item-card"><div class="item-body"><h3><?=e($petName($a['pet_id']))?> • <?=e($a['service_name']?:pet_service_label($a['service_type']))?></h3><p><?=e(date('d/m/Y',strtotime($a['appointment_date'])).' às '.substr($a['appointment_time'],0,5))?> • <?=status_badge($a['status'])?></p><div class="item-meta"><span><strong>Profissional:</strong> <?=e($a['professional_name']?:'A definir')?></span><span><strong>Valor:</strong> <?=money($a['amount'])?></span><span><strong>Pagamento:</strong> <?=e(status_label($a['payment_status']))?></span></div>
<?php if($manage):?><form method="post" action="actions.php" class="actions"><?=csrf_field()?><input type="hidden" name="action" value="update_pet_appointment"><input type="hidden" name="return_page" value="petcare"><input type="hidden" name="return_anchor" value="agenda"><input type="hidden" name="id" value="<?=(int)$a['id']?>"><select name="status"><option value="scheduled"<?=selected($a['status'],'scheduled')?>>Agendado</option><option value="confirmed"<?=selected($a['status'],'confirmed')?>>Confirmado</option><option value="in_service"<?=selected($a['status'],'in_service')?>>Em atendimento</option><option value="completed"<?=selected($a['status'],'completed')?>>Concluído</option><option value="cancelled"<?=selected($a['status'],'cancelled')?>>Cancelado</option></select><button class="btn btn-secondary btn-sm">Atualizar</button></form><?php elseif(in_array((string)$a['status'],['scheduled','confirmed'],true)):?><form method="post" action="actions.php" class="actions"><?=csrf_field()?><input type="hidden" name="action" value="update_pet_appointment"><input type="hidden" name="return_page" value="<?=$petPage?>"><input type="hidden" name="return_anchor" value="agenda"><input type="hidden" name="id" value="<?=(int)$a['id']?>"><input type="hidden" name="status" value="cancelled"><button class="btn btn-danger btn-sm" data-confirm="Cancelar este agendamento?">Cancelar agendamento</button></form><?php endif;?></div></article><?php endforeach;?></div></section>

<?php if($manage&&$pets):?><section class="grid-2"><article class="panel"><h2>🩺 Prontuário veterinário</h2><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_pet_medical_record"><input type="hidden" name="return_anchor" value="vaccines"><input type="hidden" name="company_id" value="<?=$companyId?>"><div class="form-group"><label>Pet</label><select name="pet_id"><?php foreach($pets as $p):?><option value="<?=$p['id']?>"><?=e($p['name'])?></option><?php endforeach;?></select></div><div class="form-group"><label>Veterinário</label><input class="input" name="professional_name"></div><div class="form-group"><label>Queixa principal</label><textarea name="complaint"></textarea></div><div class="form-group"><label>Anamnese</label><textarea name="anamnesis"></textarea></div><div class="form-grid"><div class="form-group"><label>Peso</label><input name="weight"></div><div class="form-group"><label>Temperatura</label><input name="temperature"></div></div><div class="form-group"><label>Diagnóstico</label><textarea name="diagnosis"></textarea></div><div class="form-group"><label>Tratamento</label><textarea name="treatment"></textarea></div><div class="form-group"><label>Evolução / observações</label><textarea name="evolution"></textarea></div><button class="btn btn-primary">Salvar prontuário</button></form></article><article class="panel"><h2>💉 Vacinas</h2><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_pet_vaccine"><input type="hidden" name="return_anchor" value="vaccines"><input type="hidden" name="company_id" value="<?=$companyId?>"><div class="form-group"><label>Pet</label><select name="pet_id"><?php foreach($pets as $p):?><option value="<?=$p['id']?>"><?=e($p['name'])?></option><?php endforeach;?></select></div><div class="form-group"><label>Vacina</label><input class="input" name="vaccine_name" required></div><div class="form-grid"><div class="form-group"><label>Aplicação</label><input type="date" name="applied_at" value="<?=date('Y-m-d')?>"></div><div class="form-group"><label>Próxima dose</label><input type="date" name="next_dose_at"></div><div class="form-group"><label>Validade</label><input type="date" name="expires_at"></div><div class="form-group"><label>Lote</label><input name="batch"></div></div><div class="form-group"><label>Veterinário</label><input name="professional_name"></div><button class="btn btn-primary">Registrar vacina</button></form></article></section>
<section class="grid-2"><article class="panel"><h2>🧪 Exames</h2><form method="post" action="actions.php" enctype="multipart/form-data"><?=csrf_field()?><input type="hidden" name="action" value="save_pet_exam"><input type="hidden" name="return_anchor" value="vaccines"><input type="hidden" name="company_id" value="<?=$companyId?>"><div class="form-group"><label>Pet</label><select name="pet_id"><?php foreach($pets as $p):?><option value="<?=$p['id']?>"><?=e($p['name'])?></option><?php endforeach;?></select></div><div class="form-group"><label>Tipo de exame</label><input name="exam_type" required></div><div class="form-group"><label>Resultado</label><textarea name="result_text"></textarea></div><div class="form-group"><label>Laudo</label><textarea name="report_text"></textarea></div><div class="form-group"><label>PDF / imagem</label><input type="file" name="exam_file" accept="application/pdf,image/*"></div><button class="btn btn-primary">Salvar exame</button></form></article><article class="panel"><h2>💊 Prescrição / receita</h2><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_pet_prescription"><input type="hidden" name="return_anchor" value="vaccines"><input type="hidden" name="company_id" value="<?=$companyId?>"><div class="form-group"><label>Pet</label><select name="pet_id"><?php foreach($pets as $p):?><option value="<?=$p['id']?>"><?=e($p['name'])?></option><?php endforeach;?></select></div><div class="form-group"><label>Medicamento</label><input name="medicine_name" required></div><div class="form-grid"><div class="form-group"><label>Dosagem</label><input name="dosage"></div><div class="form-group"><label>Frequência</label><input name="frequency"></div><div class="form-group"><label>Duração</label><input name="duration_text"></div><div class="form-group"><label>Veterinário</label><input name="professional_name"></div></div><div class="form-group"><label>Orientações</label><textarea name="orientations"></textarea></div><button class="btn btn-primary">Emitir receita</button></form></article></section>
<section class="panel"><h2>🏥 Internação</h2><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_pet_hospitalization"><input type="hidden" name="return_anchor" value="vaccines"><input type="hidden" name="company_id" value="<?=$companyId?>"><div class="form-grid"><div class="form-group"><label>Pet</label><select name="pet_id"><?php foreach($pets as $p):?><option value="<?=$p['id']?>"><?=e($p['name'])?></option><?php endforeach;?></select></div><div class="form-group"><label>Box / baia</label><input name="box_name"></div><div class="form-group"><label>Entrada</label><input type="datetime-local" name="admitted_at" value="<?=date('Y-m-d\TH:i')?>"></div><div class="form-group"><label>Veterinário</label><input name="professional_name"></div><div class="form-group full"><label>Motivo</label><textarea name="reason"></textarea></div><div class="form-group full"><label>Medicamentos / alimentação / sinais vitais</label><textarea name="care_notes"></textarea></div></div><button class="btn btn-primary">Registrar internação</button></form></section><?php endif;?>

<section class="panel" id="vaccines"><div class="panel-header"><div><h2>📚 Histórico veterinário</h2><p>Vacinas, exames, prescrições, prontuários e internações.</p></div></div><div class="grid-2"><div><h3>Vacinas</h3><?php if(!$vaccines):?><div class="empty-state">Nenhuma vacina.</div><?php endif;?><?php foreach($vaccines as $v):?><div class="notice"><strong><?=e($petName($v['pet_id']))?> • <?=e($v['vaccine_name'])?></strong><br>Aplicada: <?=e($v['applied_at']?date('d/m/Y',strtotime($v['applied_at'])):'—')?> • Próxima: <?=e($v['next_dose_at']?date('d/m/Y',strtotime($v['next_dose_at'])):'—')?></div><?php endforeach;?></div><div><h3>Receitas</h3><?php if(!$prescriptions):?><div class="empty-state">Nenhuma receita.</div><?php endif;?><?php foreach($prescriptions as $r):?><div class="notice"><strong><?=e($petName($r['pet_id']))?> • <?=e($r['medicine_name'])?></strong><br><?=e(trim(($r['dosage']??'').' • '.($r['frequency']??''),' •'))?><br><?=nl2br(e($r['orientations']??''))?></div><?php endforeach;?></div></div><div class="grid-2"><div><h3>Exames</h3><?php foreach($exams as $x):?><div class="notice"><strong><?=e($petName($x['pet_id']))?> • <?=e($x['exam_type'])?></strong><br><?=nl2br(e($x['result_text']?:$x['report_text']?:'Sem resultado liberado'))?><?php if(!empty($x['file_path'])):?><br><a target="_blank" href="<?=e(media_url($x['file_path']))?>">Acessar Anexo</a><?php endif;?></div><?php endforeach;?></div><div><h3>Prontuários</h3><?php foreach($records as $r):?><div class="notice"><strong><?=e($petName($r['pet_id']))?> • <?=e($r['diagnosis']?:'Atendimento')?></strong><br><?=nl2br(e($r['treatment']?:$r['evolution']?:''))?></div><?php endforeach;?></div></div></section>

<?php if($manage):?><section class="panel" id="stock"><div class="panel-header"><div><h2>📦 Estoque do Pet Shop</h2><p>Produtos abaixo do estoque mínimo, lote e validade.</p></div><a class="btn btn-secondary btn-sm" href="dashboard.php?page=catalog">Gerenciar produtos</a></div><?php if($products):?><details><summary class="btn btn-secondary btn-sm">Configurar estoque mínimo / lote / validade</summary><div class="cards-list" style="margin-top:12px"><?php foreach($products as $pr):?><form method="post" action="actions.php" class="item-card"><div class="item-body"><?=csrf_field()?><input type="hidden" name="action" value="save_pet_product_details"><input type="hidden" name="return_anchor" value="stock"><input type="hidden" name="company_id" value="<?=$companyId?>"><input type="hidden" name="product_id" value="<?=(int)$pr['id']?>"><h3><?=e($pr['name'])?></h3><div class="form-grid"><div class="form-group"><label>Marca</label><input name="brand" value="<?=e($pr['brand']??'')?>"></div><div class="form-group"><label>Estoque mínimo</label><input name="stock_min" value="<?=e($pr['stock_min']??0)?>"></div><div class="form-group"><label>Lote</label><input name="batch" value="<?=e($pr['batch']??'')?>"></div><div class="form-group"><label>Validade</label><input type="date" name="expires_at" value="<?=e($pr['expires_at']??'')?>"></div></div><button class="btn btn-primary btn-sm">Salvar</button></div></form><?php endforeach;?></div></details><?php endif;?><div class="grid-2"><div><h3>Estoque baixo</h3><?php if(!$lowStock):?><div class="empty-state">Nenhum alerta.</div><?php endif;?><?php foreach($lowStock as $pr):?><div class="notice"><strong><?=e($pr['name'])?></strong><br>Atual: <?=e($pr['stock'])?> • mínimo: <?=e($pr['stock_min'])?></div><?php endforeach;?></div><div><h3>Validade</h3><?php if(!$expiring):?><div class="empty-state">Nenhum item vencendo em até 30 dias.</div><?php endif;?><?php foreach($expiring as $pr):?><div class="notice"><strong><?=e($pr['name'])?></strong><br>Validade: <?=e(date('d/m/Y',strtotime($pr['expires_at'])))?> • lote <?=e($pr['batch']?:'—')?></div><?php endforeach;?></div></div>
<?php if($products):?><div class="grid-2" style="margin-top:16px"><div><h3>↕️ Movimentar estoque</h3><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_pet_stock_movement"><input type="hidden" name="return_anchor" value="stock"><input type="hidden" name="company_id" value="<?=$companyId?>"><div class="form-group"><label>Produto</label><select name="product_id"><?php foreach($products as $pr):?><option value="<?=$pr['id']?>"><?=e($pr['name'])?> (<?=e($pr['stock'])?>)</option><?php endforeach;?></select></div><div class="form-grid"><div class="form-group"><label>Movimento</label><select name="movement_type"><option value="entry">Entrada</option><option value="exit">Saída</option><option value="adjustment_add">Ajuste +</option><option value="adjustment_sub">Ajuste -</option></select></div><div class="form-group"><label>Quantidade</label><input name="qty" inputmode="decimal" required></div></div><div class="form-group"><label>Motivo</label><input name="reason" placeholder="Compra, perda, correção..."></div><button class="btn btn-primary btn-sm">Registrar movimentação</button></form></div><div><h3>🏭 Fornecedores</h3><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_pet_supplier"><input type="hidden" name="return_anchor" value="stock"><input type="hidden" name="company_id" value="<?=$companyId?>"><div class="form-grid"><div class="form-group"><label>Nome</label><input name="name" required></div><div class="form-group"><label>CPF/CNPJ</label><input name="document"></div><div class="form-group"><label>Telefone</label><input name="phone"></div><div class="form-group"><label>E-mail</label><input type="email" name="email"></div><div class="form-group full"><label>Produtos / observações</label><textarea name="products_notes"></textarea></div></div><button class="btn btn-secondary btn-sm">Salvar fornecedor</button></form><?php foreach($suppliers as $sp):?><div class="notice"><strong><?=e($sp['name'])?></strong><br><?=e(format_phone($sp['phone']))?> • <?=e($sp['email'])?><br><?=e($sp['products_notes'])?></div><?php endforeach;?></div></div><?php endif;?>
<?php if($stockMovements):?><h3 style="margin-top:20px">Histórico de movimentações</h3><div class="table-wrap"><table><thead><tr><th>Data</th><th>Produto</th><th>Tipo</th><th>Qtd.</th><th>Motivo</th><th>Responsável</th></tr></thead><tbody><?php foreach($stockMovements as $m):?><tr><td><?=e(date('d/m/Y H:i',strtotime($m['created_at'])))?></td><td><?=e($m['product_name'])?></td><td><?=e(status_label($m['movement_type']))?></td><td><?=e($m['qty'])?></td><td><?=e($m['reason'])?></td><td><?=e($m['user_name']?:'Sistema')?></td></tr><?php endforeach;?></tbody></table></div><?php endif;?></section><?php endif;?>
<script>
document.querySelectorAll('[data-copy-text]').forEach(b=>b.addEventListener('click',async()=>{try{await navigator.clipboard.writeText(b.dataset.copyText||'');const o=b.textContent;b.textContent='Copiado ✓';setTimeout(()=>b.textContent=o,1400);}catch(e){prompt('Copie o link:',b.dataset.copyText||'');}}));
document.querySelectorAll('[data-pet-tutor-form]').forEach(form=>{const id=form.querySelector('[data-tutor-id]'),btn=form.querySelector('[data-tutor-lookup]'),status=form.querySelector('[data-tutor-lookup-status]');if(!id||!btn)return;const lookup=async()=>{const value=(id.value||'').trim();if(!value){if(status)status.textContent='Informe o ID do cliente.';return;}btn.disabled=true;if(status)status.textContent='Buscando cliente...';try{const r=await fetch('user_lookup.php?purpose=pet_tutor&company_id=<?=($companyId)?>&id='+encodeURIComponent(value),{headers:{'Accept':'application/json'}});const d=await r.json();if(!d.ok){if(status)status.textContent=d.message||'Cliente não encontrado.';return;}['name','document','phone','whatsapp','email','address','city','state'].forEach(k=>{const el=form.elements[k];if(el&&d[k]!==undefined&&d[k]!==null&&String(d[k]).trim()!=='')el.value=d[k];});if(status)status.textContent=d.message||'Cliente localizado e preenchido.';}catch(e){if(status)status.textContent='Não foi possível consultar o ID agora.';}finally{btn.disabled=false;}};btn.addEventListener('click',lookup);id.addEventListener('change',lookup);});
</script>
