<?php
require __DIR__.'/app/bootstrap.php';require_auth();
$id=(int)request('id',0);if($id<1){http_response_code(404);exit('Currículo não encontrado.');}
$q=db()->prepare("SELECT r.*,u.name,u.email,u.phone,u.public_id,u.avatar,cp.birth_date,cp.city,cp.state,cp.address,cp.linkedin,cp.portfolio,cp.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.id=? AND r.status='active' LIMIT 1");$q->execute([$id]);$r=$q->fetch();if(!$r){http_response_code(404);exit('Currículo não encontrado.');}
$viewer=current_user();$viewerId=(int)$viewer['id'];$viewerCompany=resolve_company_id_for_user($viewer);$owner=$viewerId===(int)$r['user_id'];$allowed=$owner||is_super_admin();
if(!$allowed&&in_array((string)$viewer['role'],['company','employee'],true)&&$viewerCompany>0&&career_access_allowed($viewerId)){
    if(in_array((string)$r['visibility'],['public','registered'],true))$allowed=true;
    else{$aq=db()->prepare('SELECT COUNT(*) FROM job_applications a JOIN job_posts j ON j.id=a.job_id WHERE a.resume_id=? AND j.company_id=?');$aq->execute([$id,$viewerCompany]);$allowed=(int)$aq->fetchColumn()>0;}
}
if(!$allowed){http_response_code(403);exit('Este currículo não está disponível para sua conta.');}
if(!$owner&&$viewerCompany>0){try{$seen=db()->prepare("SELECT COUNT(*) FROM resume_views WHERE resume_id=? AND company_id=? AND viewed_by=? AND date(viewed_at)=date('now')");$seen->execute([$id,$viewerCompany,$viewerId]);if(!(int)$seen->fetchColumn()){db()->prepare('INSERT INTO resume_views(resume_id,company_id,viewed_by,viewed_at) VALUES(?,?,?,?)')->execute([$id,$viewerCompany,$viewerId,now()]);$cq=db()->prepare('SELECT name FROM companies WHERE id=?');$cq->execute([$viewerCompany]);$companyName=(string)($cq->fetchColumn()?:'Uma empresa');create_notification((int)$r['user_id'],'👁️ Currículo visualizado',$companyName.' visualizou seu currículo '.$r['title'].'.','info','dashboard.php?page=careers','resume_view',$id);}}catch(Throwable $e){}}
$q=db()->prepare('SELECT * FROM resume_experiences WHERE resume_id=? ORDER BY CASE WHEN end_date IS NULL OR end_date="" THEN 0 ELSE 1 END,COALESCE(end_date,start_date) DESC,id DESC');$q->execute([$id]);$exp=$q->fetchAll();
$q=db()->prepare('SELECT * FROM resume_education WHERE resume_id=? ORDER BY completion_year DESC,id DESC');$q->execute([$id]);$edu=$q->fetchAll();

function cv_clean(string $s): string {$s=strip_tags($s);$s=preg_replace('/\s+/u',' ',trim($s));return $s?:'';}
function cv_wrap(string $text,int $limit=88): array {$text=trim($text);if($text==='')return [];$out=[];foreach(preg_split('/\R/u',$text) as $paragraph){$words=preg_split('/\s+/u',trim($paragraph),-1,PREG_SPLIT_NO_EMPTY);$line='';foreach($words as $word){$test=$line===''?$word:$line.' '.$word;if(mb_strlen($test,'UTF-8')>$limit&&$line!==''){$out[]=$line;$line=$word;}else{$line=$test;}}if($line!=='')$out[]=$line;}return $out;}
function pdf_enc(string $s): string {$v=@iconv('UTF-8','Windows-1252//TRANSLIT//IGNORE',$s);return $v===false?$s:$v;}
function pdf_esc(string $s): string {return str_replace(['\\','(',')'],['\\\\','\\(','\\)'],pdf_enc($s));}
$pages=[];$content='';$y=760;
$startPage=function()use(&$content,&$y){$content="0.075 0.36 0.66 rg 0 700 595 142 re f\n";$y=665;};$finishPage=function()use(&$pages,&$content){$pages[]=$content;$content='';};$startPage();
$line=function(string $text,float $size=10,bool $bold=false,float $indent=52,float $gap=15)use(&$content,&$y,&$startPage,&$finishPage){if($y<62){$finishPage();$startPage();}$font=$bold?'F2':'F1';$content.="0.08 0.12 0.20 rg BT /$font $size Tf $indent $y Td (".pdf_esc($text).") Tj ET\n";$y-=$gap;};
$section=function(string $title)use(&$content,&$y,&$line){if($y<95)$line('');$y-=7;$content.="0.86 0.91 0.97 rg 48 ".($y-5)." 499 26 re f\n";$line(mb_strtoupper($title,'UTF-8'),12,true,58,30);};
$para=function(string $text,int $limit=90)use(&$line){foreach(cv_wrap($text,$limit) as $l)$line($l,9.5,false,58,13);};
// Header
$content.="1 1 1 rg BT /F2 24 Tf 52 785 Td (".pdf_esc(mb_strtoupper(cv_clean((string)$r['name']),'UTF-8')).") Tj ET\n";
$content.="1 1 1 rg BT /F1 12 Tf 52 755 Td (".pdf_esc(cv_clean((string)($r['objective']?:$r['title']))).") Tj ET\n";
$showContact=$owner||is_super_admin()||(int)($r['allow_company_contact']??1)===1;$contact=array_filter(array_merge($showContact?[cv_clean((string)$r['phone']),cv_clean((string)$r['email'])]:[],[cv_clean(trim((string)$r['city'].' / '.(string)$r['state'],' /')),cv_clean((string)$r['public_id'])]));
$content.="1 1 1 rg BT /F1 9 Tf 52 728 Td (".pdf_esc(implode('  |  ',$contact)).") Tj ET\n";
$y=675;
if(cv_clean((string)$r['summary'])!==''){$section('Resumo profissional');$para((string)$r['summary']);}
if($exp){$section('Experiência profissional');foreach($exp as $e){$period=trim((!empty($e['start_date'])?date('m/Y',strtotime($e['start_date'])):'').' - '.(!empty($e['end_date'])?date('m/Y',strtotime($e['end_date'])):'Atual'),' -');$line(cv_clean($e['job_title'].' • '.$e['company_name']),11,true,58,16);if($period!=='')$line($period,9,false,58,13);$para((string)$e['activities'],88);if(!empty($e['leaving_reason']))$line('Motivo da saída: '.cv_clean((string)$e['leaving_reason']),8.8,false,58,14);$y-=5;}}
if($edu){$section('Formação acadêmica e cursos');foreach($edu as $e){$title=trim(cv_clean((string)$e['course']).' • '.cv_clean((string)$e['institution']),' •');$line($title?:cv_clean((string)$e['education_level']),10.5,true,58,15);$details=trim(cv_clean((string)$e['education_level']).(!empty($e['completion_year'])?' • Conclusão: '.cv_clean((string)$e['completion_year']):''),' •');if($details)$line($details,9,false,58,14);}}
if(cv_clean((string)$r['skills'])!==''){$section('Habilidades');$para((string)$r['skills']);}
if(cv_clean((string)$r['languages'])!==''){$section('Idiomas');$para((string)$r['languages']);}
if(cv_clean((string)$r['additional_info'])!==''){$section('Informações adicionais');$para((string)$r['additional_info']);}
$section('Disponibilidade e links');if(!empty($r['availability']))$line('Disponibilidade: '.cv_clean((string)$r['availability']),9.5,false,58,14);if(!empty($r['desired_contract']))$line('Contratação desejada: '.cv_clean((string)$r['desired_contract']),9.5,false,58,14);if((float)$r['salary_expectation']>0)$line('Pretensão salarial: '.money((float)$r['salary_expectation']),9.5,false,58,14);if(!empty($r['linkedin']))$line('LinkedIn: '.cv_clean((string)$r['linkedin']),9,false,58,14);if(!empty($r['portfolio']))$line('Portfólio: '.cv_clean((string)$r['portfolio']),9,false,58,14);
$y-=8;$line('Currículo gerado por '.platform_name().' em '.date('d/m/Y').'.',8,false,58,12);$finishPage();

// Minimal multi-page PDF with Helvetica/Helvetica-Bold and WinAnsi encoding.
$objects=[];$objects[1]='<< /Type /Catalog /Pages 2 0 R >>';$objects[3]='<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>';$objects[4]='<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>';$pageObjIds=[];$contentObjIds=[];$next=5;foreach($pages as $pg){$pageObjIds[]=$next++;$contentObjIds[]=$next++;}$kids=implode(' ',array_map(fn($n)=>$n.' 0 R',$pageObjIds));$objects[2]='<< /Type /Pages /Kids [ '.$kids.' ] /Count '.count($pageObjIds).' >>';foreach($pages as $i=>$pg){$pid=$pageObjIds[$i];$cid=$contentObjIds[$i];$objects[$pid]='<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 3 0 R /F2 4 0 R >> >> /Contents '.$cid.' 0 R >>';$objects[$cid]='<< /Length '.strlen($pg).' >>' . "\nstream\n".$pg."endstream";}
ksort($objects);$pdf="%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";$offsets=[0=>0];foreach($objects as $num=>$obj){$offsets[$num]=strlen($pdf);$pdf.=$num." 0 obj\n".$obj."\nendobj\n";}$xref=strlen($pdf);$max=max(array_keys($objects));$pdf.="xref\n0 ".($max+1)."\n0000000000 65535 f \n";for($i=1;$i<=$max;$i++)$pdf.=sprintf('%010d 00000 n ',(int)($offsets[$i]??0))."\n";$pdf.="trailer\n<< /Size ".($max+1)." /Root 1 0 R >>\nstartxref\n$xref\n%%EOF";
$name='curriculo-'.preg_replace('/[^a-z0-9_-]+/i','-',cv_clean((string)$r['name'])).'.pdf';header('Content-Type: application/pdf');header('Content-Disposition: attachment; filename="'.$name.'"');header('Content-Length: '.strlen($pdf));echo $pdf;exit;
