<?php
$u=current_user();
$uid=(int)($u['id']??0);
$role=(string)($u['role']??'');
$linkedCompanyId=resolve_company_id_for_user($u);
$isCompany=in_array($role,['company','employee'],true)&&$linkedCompanyId>0;
$isAdmin=is_super_admin();
$fee=max(0,localized_decimal(setting('career_monthly_fee','0')));
$subscription=$isAdmin?['status'=>'active','amount'=>0]:career_subscription($uid);
$careerAllowed=$isAdmin||career_access_allowed($uid);
$platformPix=trim((string)setting('pix_key',''));
$careerSubscriptions=[];
if($isAdmin){
    $sq=db()->query("SELECT cs.*,u.name,u.public_id,u.email FROM career_subscriptions cs JOIN users u ON u.id=cs.user_id ORDER BY CASE cs.status WHEN 'proof_sent' THEN 0 WHEN 'pending' THEN 1 WHEN 'rejected' THEN 2 ELSE 3 END,cs.updated_at DESC");
    $careerSubscriptions=$sq->fetchAll();
}
?>
<section class="page-intro"><div><span class="mini-label">💼 CURRÍCULOS E VAGAS</span><h2>Carreira LinkExpress</h2><p>Currículos profissionais, vagas, candidaturas e recrutamento em um só lugar.</p></div><div class="actions"><a class="btn btn-secondary" href="dashboard.php?page=home">← Início</a></div></section>

<?php if($isAdmin):?>
<section class="panel"><div class="panel-header"><div><h2>⚙️ Mensalidade da Área de Currículos</h2><p>0,00 mantém a área gratuita. Acima de zero, o usuário fica limitado à tela de pagamento até a liberação.</p></div></div><form method="post" action="actions.php" class="module-toolbar"><?=csrf_field()?><input type="hidden" name="action" value="save_career_fee_setting"><div class="form-group"><label>Valor mensal</label><input class="input" name="amount" value="<?=e(number_format($fee,2,',','.'))?>"></div><button class="btn btn-primary">Salvar mensalidade</button></form></section>
<section class="panel"><div class="panel-header"><div><h2>🧾 Comprovantes da mensalidade</h2><p>Analise os pagamentos enviados e libere ou recuse o acesso.</p></div></div><div class="table-wrap"><table><thead><tr><th>Usuário</th><th>Valor</th><th>Status</th><th>Comprovante</th><th>Ação</th></tr></thead><tbody><?php if(!$careerSubscriptions):?><tr><td colspan="5"><div class="empty-state">Nenhuma cobrança registrada.</div></td></tr><?php endif;?><?php foreach($careerSubscriptions as $cs):?><tr><td><strong><?=e($cs['name'])?></strong><small style="display:block"><?=e($cs['public_id'].' • '.$cs['email'])?></small></td><td><?=money($cs['amount'])?></td><td><?=e(career_subscription_status_label($cs['status']))?></td><td><?php if($cs['proof_path']):?><a target="_blank" href="<?=e(media_url($cs['proof_path']))?>">Acessar Comprovante</a><?php else:?>—<?php endif;?></td><td><?php if(in_array($cs['status'],['proof_sent','pending','rejected'],true)):?><form method="post" action="actions.php" class="actions"><?=csrf_field()?><input type="hidden" name="action" value="review_career_subscription"><input type="hidden" name="user_id" value="<?=(int)$cs['user_id']?>"><button class="btn btn-danger btn-sm" name="decision" value="rejected">Recusar</button><button class="btn btn-accent btn-sm" name="decision" value="active">Liberar</button></form><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section>
<?php endif;?>

<?php if(!$careerAllowed&&!$isAdmin):?>
<section class="panel"><div class="panel-header"><div><h2>💳 Regularize a mensalidade</h2><p>Seu painel de Currículos e Vagas será liberado após o comprovante ser aprovado pelo Administrador Sênior.</p></div></div><div class="stats-grid"><div class="stat-card"><div class="stat-top"><span>Mensalidade</span><span class="stat-icon">💼</span></div><strong><?=money($subscription['amount']??$fee)?></strong><small><?=e(career_subscription_status_label((string)($subscription['status']??'pending')))?></small></div></div><?php if($platformPix):?><div class="notice"><strong>Pix da plataforma:</strong> <span style="word-break:break-all"><?=e($platformPix)?></span><div class="actions" style="margin-top:8px"><button type="button" class="btn btn-accent btn-sm" data-copy-text="<?=e($platformPix)?>">📋 Copiar Pix</button></div></div><?php else:?><div class="alert alert-warning">O Administrador Sênior ainda não cadastrou uma chave Pix para esta mensalidade.</div><?php endif;?><form method="post" action="actions.php" enctype="multipart/form-data" style="margin-top:14px"><?=csrf_field()?><input type="hidden" name="action" value="upload_career_subscription_proof"><div class="form-group"><label>Comprovante de pagamento</label><input type="file" name="proof" accept="application/pdf,image/*" required></div><button class="btn btn-primary">Enviar comprovante para análise</button></form></section>
<script>document.querySelectorAll('[data-copy-text]').forEach(b=>b.addEventListener('click',async()=>{try{await navigator.clipboard.writeText(b.dataset.copyText||'');b.textContent='Copiado ✓'}catch(e){prompt('Copie o Pix:',b.dataset.copyText||'')}}));</script>
<?php return;endif;?>

<?php
$profile=career_profile($uid);
$resumes=[];$experiences=[];$education=[];$documents=[];$applications=[];$favorites=[];$jobs=[];$companyJobs=[];$companyApplications=[];$candidateResumes=[];$candidateFavorites=[];
if(!$isAdmin){
    $q=db()->prepare("SELECT r.*,(SELECT COUNT(*) FROM resume_views rv WHERE rv.resume_id=r.id) view_count FROM resumes r WHERE r.user_id=? AND r.status='active' ORDER BY r.id DESC");$q->execute([$uid]);$resumes=$q->fetchAll();
    $resumeIds=array_map('intval',array_column($resumes,'id'));
    if($resumeIds){
        $marks=implode(',',array_fill(0,count($resumeIds),'?'));
        $q=db()->prepare("SELECT * FROM resume_experiences WHERE resume_id IN ($marks) ORDER BY COALESCE(end_date,start_date) DESC,id DESC");$q->execute($resumeIds);$experiences=$q->fetchAll();
        $q=db()->prepare("SELECT * FROM resume_education WHERE resume_id IN ($marks) ORDER BY completion_year DESC,id DESC");$q->execute($resumeIds);$education=$q->fetchAll();
        $q=db()->prepare("SELECT * FROM resume_documents WHERE resume_id IN ($marks) ORDER BY id DESC");$q->execute($resumeIds);$documents=$q->fetchAll();
    }
    $city=trim((string)request('job_city'));$area=trim((string)request('job_area'));$mode=trim((string)request('job_mode'));$contract=trim((string)request('job_contract'));$salaryMin=max(0,localized_decimal(request('job_salary_min',0)));$salaryMax=max(0,localized_decimal(request('job_salary_max',0)));$distanceKm=max(0,(float)request('job_distance',0));
    $sql="SELECT j.*,c.name company_name,c.latitude company_latitude,c.longitude company_longitude FROM job_posts j JOIN companies c ON c.id=j.company_id WHERE j.status='active'";$params=[];
    if($city!==''){$sql.=' AND lower(j.city) LIKE lower(?)';$params[]='%'.$city.'%';}
    if($area!==''){$sql.=' AND (lower(j.professional_area) LIKE lower(?) OR lower(j.title) LIKE lower(?))';$params[]='%'.$area.'%';$params[]='%'.$area.'%';}
    if($mode!==''){$sql.=' AND j.work_mode=?';$params[]=$mode;}
    if($contract!==''){$sql.=' AND lower(j.contract_type) LIKE lower(?)';$params[]='%'.$contract.'%';}
    if($salaryMin>0){$sql.=' AND COALESCE(NULLIF(j.salary_max,0),j.salary_min,0)>=?';$params[]=$salaryMin;}
    if($salaryMax>0){$sql.=' AND COALESCE(NULLIF(j.salary_min,0),j.salary_max,0)<=?';$params[]=$salaryMax;}
    $sql.=' ORDER BY j.id DESC LIMIT 300';$q=db()->prepare($sql);$q->execute($params);$jobs=$q->fetchAll();
    $userLat=$u['latitude']??$u['home_lat']??null;$userLng=$u['longitude']??$u['home_lng']??null;
    if($distanceKm>0&&$userLat!==null&&$userLng!==null){$ulat=(float)$userLat;$ulon=(float)$userLng;$filtered=[];foreach($jobs as $jobRow){if($jobRow['company_latitude']===null||$jobRow['company_longitude']===null)continue;$km=distance_km($ulat,$ulon,(float)$jobRow['company_latitude'],(float)$jobRow['company_longitude']);if($km!==null&&$km<=$distanceKm){$jobRow['distance_km']=$km;$filtered[]=$jobRow;}}$jobs=$filtered;}
    $fq=db()->prepare('SELECT job_id FROM job_favorites WHERE user_id=?');$fq->execute([$uid]);$favorites=array_map('intval',$fq->fetchAll(PDO::FETCH_COLUMN));
    $aq=db()->prepare("SELECT a.*,j.title job_title,j.company_id,c.name company_name FROM job_applications a JOIN job_posts j ON j.id=a.job_id JOIN companies c ON c.id=j.company_id WHERE a.user_id=? ORDER BY a.id DESC");$aq->execute([$uid]);$applications=$aq->fetchAll();
}
if($isCompany){
    $q=db()->prepare("SELECT * FROM job_posts WHERE company_id=? AND status<>'deleted' ORDER BY id DESC");$q->execute([$linkedCompanyId]);$companyJobs=$q->fetchAll();
    $q=db()->prepare("SELECT a.*,j.title job_title,u.name candidate_name,u.public_id candidate_public_id,u.phone candidate_phone,r.title resume_title,r.objective,r.summary,r.skills,r.visibility,COALESCE(cp.allow_company_contact,1) allow_company_contact FROM job_applications a JOIN job_posts j ON j.id=a.job_id JOIN users u ON u.id=a.user_id JOIN resumes r ON r.id=a.resume_id LEFT JOIN career_profiles cp ON cp.user_id=u.id WHERE j.company_id=? ORDER BY a.id DESC");$q->execute([$linkedCompanyId]);$companyApplications=$q->fetchAll();
    $search=trim((string)request('candidate_search'));$candidateArea=trim((string)request('candidate_area'));$candidateCity=trim((string)request('candidate_city'));$candidateExperience=trim((string)request('candidate_experience'));$candidateEducation=trim((string)request('candidate_education'));$candidateDistance=max(1,min(500,(float)request('candidate_distance',50)));
    $cq=db()->prepare('SELECT latitude,longitude FROM companies WHERE id=?');$cq->execute([$linkedCompanyId]);$companyCoords=$cq->fetch()?:[];$companyLat=$companyCoords['latitude']??null;$companyLng=$companyCoords['longitude']??null;
    $sql="SELECT r.*,u.name candidate_name,u.public_id,u.city user_city,u.phone candidate_phone,COALESCE(u.latitude,u.home_lat) candidate_latitude,COALESCE(u.longitude,u.home_lng) candidate_longitude,cp.city profile_city,cp.state profile_state,COALESCE(cp.allow_company_contact,1) allow_company_contact FROM resumes r JOIN users u ON u.id=r.user_id LEFT JOIN career_profiles cp ON cp.user_id=u.id WHERE r.status='active' AND r.visibility IN ('public','registered')";$params=[];
    if($search!==''){$sql.=" AND (lower(u.name) LIKE lower(?) OR lower(r.objective) LIKE lower(?) OR lower(r.skills) LIKE lower(?) OR lower(cp.city) LIKE lower(?))";$params=array_merge($params,array_fill(0,4,'%'.$search.'%'));}
    if($candidateArea!==''){$sql.=" AND (lower(r.objective) LIKE lower(?) OR lower(r.skills) LIKE lower(?))";$params[]='%'.$candidateArea.'%';$params[]='%'.$candidateArea.'%';}
    if($candidateCity!==''){$sql.=" AND lower(COALESCE(cp.city,u.city,'')) LIKE lower(?)";$params[]='%'.$candidateCity.'%';}
    if($candidateExperience!==''){$sql.=" AND EXISTS(SELECT 1 FROM resume_experiences re WHERE re.resume_id=r.id AND (lower(re.job_title) LIKE lower(?) OR lower(re.activities) LIKE lower(?) OR lower(re.company_name) LIKE lower(?)))";$params=array_merge($params,array_fill(0,3,'%'.$candidateExperience.'%'));}
    if($candidateEducation!==''){$sql.=" AND EXISTS(SELECT 1 FROM resume_education ed WHERE ed.resume_id=r.id AND (lower(ed.education_level) LIKE lower(?) OR lower(ed.course) LIKE lower(?) OR lower(ed.institution) LIKE lower(?)))";$params=array_merge($params,array_fill(0,3,'%'.$candidateEducation.'%'));}
    $sql.=' ORDER BY r.id DESC LIMIT 300';$q=db()->prepare($sql);$q->execute($params);$candidateResumes=$q->fetchAll();
    if($companyLat!==null&&$companyLng!==null){$clat=(float)$companyLat;$clng=(float)$companyLng;$filtered=[];foreach($candidateResumes as $candidateRow){if($candidateRow['candidate_latitude']===null||$candidateRow['candidate_longitude']===null)continue;$km=distance_km($clat,$clng,(float)$candidateRow['candidate_latitude'],(float)$candidateRow['candidate_longitude']);if($km!==null&&$km<=$candidateDistance){$candidateRow['distance_km']=$km;$filtered[]=$candidateRow;}}$candidateResumes=$filtered;usort($candidateResumes,fn($a,$b)=>(float)($a['distance_km']??99999)<=>(float)($b['distance_km']??99999));}
    $cfq=db()->prepare('SELECT resume_id FROM candidate_favorites WHERE company_id=?');$cfq->execute([$linkedCompanyId]);$candidateFavorites=array_map('intval',$cfq->fetchAll(PDO::FETCH_COLUMN));
}
$requiredProfileFields=[
    (string)($u['name']??''),(string)($u['email']??''),(string)($u['phone']??''),(string)($u['avatar']??''),
    (string)($profile['birth_date']??''),(string)($profile['city']??''),(string)($profile['state']??''),(string)($profile['address']??''),
    (string)($profile['desired_job_type']??''),(string)($profile['desired_work_mode']??''),(string)($profile['availability']??'')
];
$profileFilled=count(array_filter($requiredProfileFields,fn($v)=>trim($v)!==''));$profilePercent=(int)round(($profileFilled/max(1,count($requiredProfileFields)))*100);
$totalViews=array_sum(array_map(fn($r)=>(int)($r['view_count']??0),$resumes));$favoriteCount=count($favorites);
$byResume=function(array $rows,int $resumeId):array{return array_values(array_filter($rows,fn($x)=>(int)$x['resume_id']===$resumeId));};
$lastCompanyApplication=[];foreach($applications as $a){$cid=(int)($a['company_id']??0);if($cid&&!isset($lastCompanyApplication[$cid]))$lastCompanyApplication[$cid]=(string)$a['created_at'];}
?>

<?php if(!$isAdmin):?>
<section class="stats-grid">
<a class="stat-card stat-card-link" href="#professional-profile"><div class="stat-top"><span>Meu perfil profissional</span><span class="stat-icon">👤</span></div><strong><?=$profilePercent?>%</strong><small>toque para preencher / editar</small></a>
<a class="stat-card stat-card-link" href="#resumes"><div class="stat-top"><span>Currículos</span><span class="stat-icon">📄</span></div><strong><?=count($resumes)?></strong><small>ativos</small></a>
<?php if(!$isCompany):?><a class="stat-card stat-card-link" href="#applications"><div class="stat-top"><span>Candidaturas</span><span class="stat-icon">📤</span></div><strong><?=count($applications)?></strong><small>enviadas</small></a><div class="stat-card"><div class="stat-top"><span>Em análise</span><span class="stat-icon">🔎</span></div><strong><?=count(array_filter($applications,fn($a)=>in_array($a['status'],['sent','analysis'],true)))?></strong><small>processos</small></div><div class="stat-card"><div class="stat-top"><span>Entrevistas</span><span class="stat-icon">🗓️</span></div><strong><?=count(array_filter($applications,fn($a)=>$a['status']==='interview'))?></strong><small>agendadas</small></div><div class="stat-card"><div class="stat-top"><span>Favoritos</span><span class="stat-icon">⭐</span></div><strong><?=$favoriteCount?></strong><small>vagas</small></div><?php endif;?>
<div class="stat-card"><div class="stat-top"><span>Visualizações</span><span class="stat-icon">👁️</span></div><strong><?=$totalViews?></strong><small>dos currículos</small></div>
</section>

<section class="panel" id="professional-profile"><div class="panel-header"><div><h2>👤 Meu perfil profissional</h2><p>Preencha seus dados aqui. A porcentagem considera os campos essenciais do perfil e sua foto.</p></div><span class="status <?=$profilePercent>=100?'status-active':'status-pending'?>"><?=$profilePercent?>% completo</span></div>
<form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_career_profile"><input type="hidden" name="return_anchor" value="professional-profile"><div class="form-grid"><div class="form-group"><label>Nome</label><input class="input" value="<?=e($u['name'])?>" readonly></div><div class="form-group"><label>Data de nascimento</label><input type="date" name="birth_date" value="<?=e($profile['birth_date'])?>"></div><div class="form-group"><label>Telefone / WhatsApp</label><input class="input" value="<?=e(format_phone($u['phone']))?>" readonly></div><div class="form-group"><label>E-mail</label><input class="input" value="<?=e($u['email'])?>" readonly></div><div class="form-group"><label>Cidade</label><input name="city" value="<?=e($profile['city'])?>"></div><div class="form-group"><label>Estado</label><input name="state" value="<?=e($profile['state'])?>"></div><div class="form-group full"><label>Endereço</label><input name="address" value="<?=e($profile['address'])?>"></div><div class="form-group"><label>LinkedIn (opcional)</label><input type="url" name="linkedin" value="<?=e($profile['linkedin'])?>"></div><div class="form-group"><label>Portfólio (opcional)</label><input type="url" name="portfolio" value="<?=e($profile['portfolio'])?>"></div><div class="form-group"><label>Disponibilidade</label><input name="availability" value="<?=e($profile['availability'])?>"></div><div class="form-group"><label>Pretensão salarial (opcional)</label><input name="salary_expectation" value="<?=e($profile['salary_expectation'])?>"></div><div class="form-group"><label>Tipo de contratação / área desejada</label><input name="desired_job_type" value="<?=e($profile['desired_job_type'])?>"></div><div class="form-group"><label>Modelo de trabalho</label><select name="desired_work_mode"><option value="">Selecione</option><option value="onsite"<?=selected($profile['desired_work_mode'],'onsite')?>>Presencial</option><option value="hybrid"<?=selected($profile['desired_work_mode'],'hybrid')?>>Híbrido</option><option value="remote"<?=selected($profile['desired_work_mode'],'remote')?>>Home office</option></select></div><div class="form-group"><label>Privacidade</label><select name="visibility"><option value="public"<?=selected($profile['visibility'],'public')?>>Público</option><option value="registered"<?=selected($profile['visibility'],'registered')?>>Somente empresas cadastradas</option><option value="private"<?=selected($profile['visibility'],'private')?>>Privado</option></select></div><div class="form-group"><label>Contato por empresas</label><select name="allow_company_contact"><option value="1"<?=selected($profile['allow_company_contact'],1)?>>Permitido</option><option value="0"<?=selected($profile['allow_company_contact'],0)?>>Bloqueado</option></select></div></div><button class="btn btn-primary">Salvar perfil</button></form></section>

<section class="panel" id="resumes"><div class="panel-header"><div><h2>📄 Meus currículos</h2><p>Crie vários modelos. Cada informação possui acesso direto para visualizar ou editar.</p></div></div>
<details><summary class="btn btn-primary btn-sm">+ Novo currículo</summary><form method="post" action="actions.php" style="margin-top:14px"><?=csrf_field()?><input type="hidden" name="action" value="save_resume"><input type="hidden" name="return_anchor" value="resumes"><div class="form-grid"><div class="form-group"><label>Título</label><input name="title" required placeholder="Ex.: Administrativo 2026"></div><div class="form-group"><label>Objetivo profissional</label><input name="objective"></div><div class="form-group full"><label>Resumo profissional</label><textarea name="summary"></textarea></div><div class="form-group full"><label>Habilidades</label><textarea name="skills"></textarea></div><div class="form-group full"><label>Idiomas</label><textarea name="languages"></textarea></div><div class="form-group full"><label>Informações adicionais</label><textarea name="additional_info"></textarea></div><div class="form-group"><label>Pretensão salarial</label><input name="salary_expectation"></div><div class="form-group"><label>Disponibilidade</label><input name="availability"></div><div class="form-group"><label>Contratação desejada</label><input name="desired_contract"></div><div class="form-group"><label>Visibilidade</label><select name="visibility"><option value="public">Público</option><option value="registered" selected>Empresas cadastradas</option><option value="private">Privado</option></select></div></div><button class="btn btn-primary">Criar currículo</button></form></details>
<div class="cards-list" style="margin-top:14px"><?php if(!$resumes):?><div class="empty-state"><strong>Você ainda não criou currículo</strong></div><?php endif;?>
<?php foreach($resumes as $r):$rid=(int)$r['id'];$rx=$byResume($experiences,$rid);$re=$byResume($education,$rid);$rd=$byResume($documents,$rid);?><article class="item-card" id="resume-<?=$rid?>"><div class="item-body"><div class="panel-header" style="margin-bottom:8px"><div><h3><?=e($r['title'])?></h3><p><?=e($r['objective']?:'Objetivo não informado')?> • <?=e(status_label($r['visibility']))?></p></div><span class="status status-active"><?=(int)$r['view_count']?> visualização(ões)</span></div><div class="actions"><a class="btn btn-primary btn-sm" target="_blank" href="career_resume_pdf.php?id=<?=$rid?>">⬇️ Gerar PDF</a><a class="btn btn-secondary btn-sm" href="#resume-info-<?=$rid?>">ℹ️ Informações</a><a class="btn btn-secondary btn-sm" href="#resume-edit-<?=$rid?>">✏️ Editar</a><form method="post" action="actions.php" onsubmit="return confirm('Apagar este currículo?');"><?=csrf_field()?><input type="hidden" name="action" value="delete_resume"><input type="hidden" name="id" value="<?=$rid?>"><button class="btn btn-danger btn-sm">🗑️ Apagar</button></form></div>
<details id="resume-info-<?=$rid?>" style="margin-top:12px"><summary class="btn btn-secondary btn-sm">Ver experiências, formação e documentos</summary><div class="grid-2" style="margin-top:12px"><div class="notice"><strong>💼 Experiências</strong><?php if(!$rx):?><br>Nenhuma cadastrada.<?php endif;?><?php foreach($rx as $x):?><p><b><?=e($x['job_title'])?></b> — <?=e($x['company_name'])?><br><?=nl2br(e($x['activities']??''))?></p><?php endforeach;?></div><div class="notice"><strong>🎓 Formação</strong><?php if(!$re):?><br>Nenhuma cadastrada.<?php endif;?><?php foreach($re as $x):?><p><b><?=e($x['course']?:$x['education_level'])?></b> — <?=e($x['institution'])?> <?=e($x['completion_year'])?></p><?php endforeach;?></div></div><div class="notice"><strong>📎 Documentos</strong><?php if(!$rd):?> — nenhum anexo.<?php endif;?><?php foreach($rd as $x):?> <a target="_blank" href="<?=e(media_url($x['file_path']))?>"><?=e($x['title'])?></a><?php endforeach;?></div></details>
<details id="resume-edit-<?=$rid?>" style="margin-top:12px"><summary class="btn btn-secondary btn-sm">Editar currículo</summary><form method="post" action="actions.php" style="margin-top:12px"><?=csrf_field()?><input type="hidden" name="action" value="save_resume"><input type="hidden" name="id" value="<?=$rid?>"><input type="hidden" name="return_anchor" value="resume-<?=$rid?>"><div class="form-grid"><div class="form-group"><label>Título</label><input name="title" value="<?=e($r['title'])?>" required></div><div class="form-group"><label>Objetivo</label><input name="objective" value="<?=e($r['objective'])?>"></div><div class="form-group full"><label>Resumo</label><textarea name="summary"><?=e($r['summary'])?></textarea></div><div class="form-group full"><label>Habilidades</label><textarea name="skills"><?=e($r['skills'])?></textarea></div><div class="form-group full"><label>Idiomas</label><textarea name="languages"><?=e($r['languages'])?></textarea></div><div class="form-group full"><label>Informações adicionais</label><textarea name="additional_info"><?=e($r['additional_info'])?></textarea></div><div class="form-group"><label>Pretensão salarial</label><input name="salary_expectation" value="<?=e($r['salary_expectation'])?>"></div><div class="form-group"><label>Disponibilidade</label><input name="availability" value="<?=e($r['availability'])?>"></div><div class="form-group"><label>Contratação</label><input name="desired_contract" value="<?=e($r['desired_contract'])?>"></div><div class="form-group"><label>Visibilidade</label><select name="visibility"><option value="public"<?=selected($r['visibility'],'public')?>>Público</option><option value="registered"<?=selected($r['visibility'],'registered')?>>Empresas cadastradas</option><option value="private"<?=selected($r['visibility'],'private')?>>Privado</option></select></div></div><button class="btn btn-primary btn-sm">Salvar alterações</button></form></details>
<details style="margin-top:12px"><summary class="btn btn-secondary btn-sm">+ Experiência / formação / documento</summary><div class="grid-2" style="margin-top:12px"><form method="post" action="actions.php" class="panel"><?=csrf_field()?><input type="hidden" name="action" value="save_resume_experience"><input type="hidden" name="resume_id" value="<?=$rid?>"><input type="hidden" name="return_anchor" value="resume-<?=$rid?>"><h4>💼 Experiência</h4><input name="company_name" placeholder="Empresa" required><input name="job_title" placeholder="Cargo" required><div class="form-grid"><input type="date" name="start_date"><input type="date" name="end_date"></div><textarea name="activities" placeholder="Atividades"></textarea><input name="last_salary" placeholder="Último salário (opcional)"><input name="leaving_reason" placeholder="Motivo da saída"><button class="btn btn-primary btn-sm">Adicionar</button></form><form method="post" action="actions.php" class="panel"><?=csrf_field()?><input type="hidden" name="action" value="save_resume_education"><input type="hidden" name="resume_id" value="<?=$rid?>"><input type="hidden" name="return_anchor" value="resume-<?=$rid?>"><h4>🎓 Formação / curso</h4><input name="education_level" placeholder="Escolaridade"><input name="institution" placeholder="Instituição"><input name="course" placeholder="Curso"><input name="completion_year" placeholder="Ano de conclusão"><button class="btn btn-primary btn-sm">Adicionar</button></form></div><form method="post" action="actions.php" enctype="multipart/form-data" style="margin-top:10px"><?=csrf_field()?><input type="hidden" name="action" value="upload_resume_document"><input type="hidden" name="resume_id" value="<?=$rid?>"><input type="hidden" name="return_anchor" value="resume-<?=$rid?>"><div class="form-grid"><div class="form-group"><label>Tipo</label><select name="document_type"><option value="resume_pdf">Currículo PDF</option><option value="certificate">Certificado</option><option value="portfolio">Portfólio</option><option value="professional">Documento profissional</option></select></div><div class="form-group"><label>Título</label><input name="title" required></div><div class="form-group"><label>Arquivo</label><input type="file" name="document" accept="application/pdf,image/*" required></div></div><button class="btn btn-secondary btn-sm">Anexar documento</button></form></details>
</div></article><?php endforeach;?></div></section>
<?php endif;?>

<?php if(!$isAdmin&&!$isCompany):?>
<section class="panel" id="jobs"><div class="panel-header"><div><h2>🔎 Buscar vagas</h2><p>Pesquise por área, cidade, contratação e modalidade.</p></div></div><form method="get" action="dashboard.php" class="module-toolbar"><input type="hidden" name="page" value="careers"><input name="job_area" placeholder="Cargo / área" value="<?=e(request('job_area',''))?>"><input name="job_city" placeholder="Cidade" value="<?=e(request('job_city',''))?>"><select name="job_mode"><option value="">Todas modalidades</option><option value="onsite"<?=selected(request('job_mode'),'onsite')?>>Presencial</option><option value="hybrid"<?=selected(request('job_mode'),'hybrid')?>>Híbrido</option><option value="remote"<?=selected(request('job_mode'),'remote')?>>Home office</option></select><input name="job_contract" placeholder="Contratação" value="<?=e(request('job_contract',''))?>"><input name="job_salary_min" inputmode="decimal" placeholder="Salário mín." value="<?=e(request('job_salary_min',''))?>"><input name="job_salary_max" inputmode="decimal" placeholder="Salário máx." value="<?=e(request('job_salary_max',''))?>"><select name="job_distance"><option value="0">Qualquer distância</option><?php foreach([5,10,25,50,100] as $km):?><option value="<?=$km?>"<?=selected(request('job_distance'),$km)?>>Até <?=$km?> km</option><?php endforeach;?></select><button class="btn btn-primary">Pesquisar</button></form><?php if((float)request('job_distance',0)>0&&(($u['latitude']??$u['home_lat']??null)===null||($u['longitude']??$u['home_lng']??null)===null)):?><div class="alert alert-warning" style="margin-top:10px">Para filtrar por distância, atualize/permita sua localização no perfil da plataforma.</div><?php endif;?>
<div class="cards-list" style="margin-top:14px"><?php if(!$jobs):?><div class="empty-state"><strong>Nenhuma vaga encontrada</strong></div><?php endif;?><?php foreach($jobs as $j):$last=$lastCompanyApplication[(int)$j['company_id']]??'';$cooling=$last!==''&&strtotime($last)>strtotime('-5 days');$availableAt=$cooling?date('d/m/Y H:i',strtotime($last.' +5 days')):'';?><article class="item-card"><div class="item-body"><h3><?=e($j['title'])?></h3><p><?=e($j['company_name'])?> • <?=e(trim(($j['city']??'').' / '.($j['state']??''),' /'))?><?php if(isset($j['distance_km'])):?> • <?=number_format((float)$j['distance_km'],1,',','.')?> km<?php endif;?></p><div class="item-meta"><span><?=e(status_label($j['work_mode']))?></span><span><?=e($j['contract_type']?:'Contratação a combinar')?></span><span><?=($j['salary_min']||$j['salary_max'])?money($j['salary_min']).' – '.money($j['salary_max']):'Salário a combinar'?></span></div><p><?=nl2br(e($j['description']))?></p><div class="actions"><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="toggle_job_favorite"><input type="hidden" name="job_id" value="<?=$j['id']?>"><button class="btn btn-secondary btn-sm"><?=in_array((int)$j['id'],$favorites,true)?'★ Favoritada':'☆ Favoritar'?></button></form><?php if($resumes&&!$cooling):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="apply_job"><input type="hidden" name="job_id" value="<?=$j['id']?>"><input type="hidden" name="return_anchor" value="jobs"><select name="resume_id"><?php foreach($resumes as $r):?><option value="<?=$r['id']?>"><?=e($r['title'])?></option><?php endforeach;?></select><button class="btn btn-primary btn-sm">Candidatar-se</button></form><?php elseif($cooling):?><span class="notice">Aguarde 5 dias para nova candidatura nesta empresa. Disponível em <?=$availableAt?>.</span><?php else:?><span class="notice">Crie um currículo para se candidatar.</span><?php endif;?></div></div></article><?php endforeach;?></div></section>
<section class="panel" id="applications"><div class="panel-header"><div><h2>⭐ Minhas candidaturas</h2><p>Acompanhe todas as etapas.</p></div></div><div class="table-wrap"><table><thead><tr><th>Vaga</th><th>Empresa</th><th>Data</th><th>Status</th><th>Entrevista</th></tr></thead><tbody><?php foreach($applications as $a):?><tr><td><?=e($a['job_title'])?></td><td><?=e($a['company_name'])?></td><td><?=e(date('d/m/Y',strtotime($a['created_at'])))?></td><td><?=e(status_label($a['status']))?></td><td><?=!empty($a['interview_at'])?e(date('d/m/Y H:i',strtotime($a['interview_at']))):'—'?></td></tr><?php endforeach;?></tbody></table></div></section>
<?php endif;?>

<?php if($isCompany):?>
<section class="panel" id="company-jobs"><div class="panel-header"><div><h2>🏢 Acessar Empresa — vagas</h2><p>Publique, edite ou apague oportunidades.</p></div></div><details><summary class="btn btn-primary btn-sm">+ Publicar vaga</summary><form method="post" action="actions.php" style="margin-top:14px"><?=csrf_field()?><input type="hidden" name="action" value="save_job_post"><input type="hidden" name="return_anchor" value="company-jobs"><div class="form-grid"><div class="form-group"><label>Título</label><input name="title" required></div><div class="form-group"><label>Área profissional</label><input name="professional_area"></div><div class="form-group"><label>Cidade</label><input name="city"></div><div class="form-group"><label>Estado</label><input name="state"></div><div class="form-group"><label>Salário mínimo</label><input name="salary_min"></div><div class="form-group"><label>Salário máximo</label><input name="salary_max"></div><div class="form-group"><label>Contratação</label><input name="contract_type" placeholder="CLT, PJ, estágio..."></div><div class="form-group"><label>Modalidade</label><select name="work_mode"><option value="onsite">Presencial</option><option value="hybrid">Híbrido</option><option value="remote">Home office</option></select></div><div class="form-group full"><label>Descrição</label><textarea name="description" required></textarea></div><div class="form-group full"><label>Requisitos</label><textarea name="requirements"></textarea></div></div><button class="btn btn-primary">Publicar vaga</button></form></details>
<div class="cards-list" style="margin-top:14px"><?php foreach($companyJobs as $j):?><article class="item-card"><div class="item-body"><div class="panel-header"><div><h3><?=e($j['title'])?></h3><p><?=status_badge($j['status'])?> • <?=e($j['professional_area'])?> • <?=e($j['city'])?></p></div><div class="actions"><form method="post" action="actions.php" onsubmit="return confirm('Apagar esta vaga?');"><?=csrf_field()?><input type="hidden" name="action" value="delete_job_post"><input type="hidden" name="id" value="<?=(int)$j['id']?>"><button class="btn btn-danger btn-sm">🗑️ Apagar</button></form></div></div><details><summary class="btn btn-secondary btn-sm">✏️ Editar vaga</summary><form method="post" action="actions.php" style="margin-top:12px"><?=csrf_field()?><input type="hidden" name="action" value="save_job_post"><input type="hidden" name="id" value="<?=(int)$j['id']?>"><input type="hidden" name="return_anchor" value="company-jobs"><div class="form-grid"><div class="form-group"><label>Título</label><input name="title" value="<?=e($j['title'])?>" required></div><div class="form-group"><label>Área</label><input name="professional_area" value="<?=e($j['professional_area'])?>"></div><div class="form-group"><label>Cidade</label><input name="city" value="<?=e($j['city'])?>"></div><div class="form-group"><label>Estado</label><input name="state" value="<?=e($j['state'])?>"></div><div class="form-group"><label>Salário mínimo</label><input name="salary_min" value="<?=e($j['salary_min'])?>"></div><div class="form-group"><label>Salário máximo</label><input name="salary_max" value="<?=e($j['salary_max'])?>"></div><div class="form-group"><label>Contratação</label><input name="contract_type" value="<?=e($j['contract_type'])?>"></div><div class="form-group"><label>Modalidade</label><select name="work_mode"><option value="onsite"<?=selected($j['work_mode'],'onsite')?>>Presencial</option><option value="hybrid"<?=selected($j['work_mode'],'hybrid')?>>Híbrido</option><option value="remote"<?=selected($j['work_mode'],'remote')?>>Home office</option></select></div><div class="form-group full"><label>Descrição</label><textarea name="description" required><?=e($j['description'])?></textarea></div><div class="form-group full"><label>Requisitos</label><textarea name="requirements"><?=e($j['requirements'])?></textarea></div></div><button class="btn btn-primary btn-sm">Salvar vaga</button></form></details></div></article><?php endforeach;?></div></section>

<section class="panel" id="company-applications"><div class="panel-header"><div><h2>📥 Currículos recebidos</h2><p>Visualize, altere status e agende entrevista.</p></div></div><div class="cards-list"><?php if(!$companyApplications):?><div class="empty-state"><strong>Nenhuma candidatura recebida</strong></div><?php endif;?><?php foreach($companyApplications as $a):?><article class="item-card"><div class="item-body"><h3><?=e($a['candidate_name'])?> • <?=e($a['job_title'])?></h3><p>ID <?=e($a['candidate_public_id'])?><?php if(!empty($a['allow_company_contact'])):?> • <?=e(format_phone($a['candidate_phone']))?><?php else:?> • Contato privado<?php endif;?></p><p><?=e($a['objective'])?><br><?=e(short_text($a['summary'],220))?></p><div class="actions"><a class="btn btn-secondary btn-sm" target="_blank" href="career_resume_pdf.php?id=<?=(int)$a['resume_id']?>">Ver currículo PDF</a></div><form method="post" action="actions.php" style="margin-top:12px"><?=csrf_field()?><input type="hidden" name="action" value="update_job_application"><input type="hidden" name="id" value="<?=$a['id']?>"><input type="hidden" name="return_anchor" value="company-applications"><div class="form-grid"><div class="form-group"><label>Status</label><select name="status"><option value="sent"<?=selected($a['status'],'sent')?>>Enviado</option><option value="analysis"<?=selected($a['status'],'analysis')?>>Em análise</option><option value="interview"<?=selected($a['status'],'interview')?>>Entrevista</option><option value="approved"<?=selected($a['status'],'approved')?>>Aprovado</option><option value="rejected"<?=selected($a['status'],'rejected')?>>Recusado</option></select></div><div class="form-group"><label>Entrevista</label><input type="datetime-local" name="interview_at" value="<?=!empty($a['interview_at'])?e(date('Y-m-d\TH:i',strtotime($a['interview_at']))):''?>"></div><div class="form-group full"><label>Anotação interna</label><textarea name="company_notes"><?=e($a['company_notes'])?></textarea></div></div><button class="btn btn-primary btn-sm">Atualizar candidato</button></form></div></article><?php endforeach;?></div></section>

<section class="panel" id="candidate-search"><div class="panel-header"><div><h2>🔎 Pesquisar candidatos</h2><p>Por padrão a busca considera até 50 km do estabelecimento. A empresa pode alterar o raio.</p></div></div><form method="get" action="dashboard.php" class="module-toolbar"><input type="hidden" name="page" value="careers"><input name="candidate_search" value="<?=e(request('candidate_search',''))?>" placeholder="Nome / palavra-chave"><input name="candidate_area" value="<?=e(request('candidate_area',''))?>" placeholder="Profissão / área"><input name="candidate_city" value="<?=e(request('candidate_city',''))?>" placeholder="Cidade"><input name="candidate_experience" value="<?=e(request('candidate_experience',''))?>" placeholder="Experiência"><input name="candidate_education" value="<?=e(request('candidate_education',''))?>" placeholder="Formação / curso"><select name="candidate_distance"><?php foreach([10,25,50,75,100,200,500] as $km):?><option value="<?=$km?>"<?=selected((int)$candidateDistance,$km)?>>Até <?=$km?> km</option><?php endforeach;?></select><button class="btn btn-primary">Pesquisar</button></form><?php if($companyLat===null||$companyLng===null):?><div class="alert alert-warning" style="margin-top:10px">Cadastre a localização da empresa para aplicar corretamente o raio de distância. Enquanto isso, a lista não é limitada por quilômetros.</div><?php endif;?><div class="cards-list" style="margin-top:14px"><?php if(!$candidateResumes):?><div class="empty-state"><strong>Nenhum currículo encontrado neste raio/filtro</strong></div><?php endif;?><?php foreach($candidateResumes as $r):?><article class="item-card"><div class="item-body"><h3><?=e($r['candidate_name'])?> • <?=e($r['title'])?></h3><p><?=e($r['objective'])?> • <?=e($r['profile_city']?:$r['user_city'])?> / <?=e($r['profile_state'])?><?php if(isset($r['distance_km'])):?> • <strong><?=number_format((float)$r['distance_km'],1,',','.')?> km</strong><?php endif;?></p><p><?=e(short_text($r['skills'],180))?></p><div class="actions"><a class="btn btn-secondary btn-sm" target="_blank" href="career_resume_pdf.php?id=<?=(int)$r['id']?>">Acessar Currículo</a><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="toggle_candidate_favorite"><input type="hidden" name="resume_id" value="<?=(int)$r['id']?>"><button class="btn btn-secondary btn-sm"><?=in_array((int)$r['id'],$candidateFavorites,true)?'★ Favorito':'☆ Favoritar'?></button></form><?php if(!empty($r['allow_company_contact'])&&!empty($r['candidate_phone'])):?><a class="btn btn-accent btn-sm" target="_blank" href="<?=e(whatsapp_url($r['candidate_phone'],'Olá, vimos seu currículo na '.platform_name().'.'))?>">WhatsApp</a><?php endif;?></div></div></article><?php endforeach;?></div></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:',b.dataset.copyText||'')}}));</script>
