<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_once DENTAL_ROOT . '/app/record_release.php';
require_once DENTAL_ROOT . '/app/transaction_integrity.php';

$portal = patient_portal_user();
if (!$portal) { header('Location: ' . dental_clean_url('patient-login.php?portal_reauth=1&reason=record_session'), true, 303); exit; }
$pdo = db();
$releaseId = (int)($_GET['release_id'] ?? 0);
$patientId = (int)($_GET['patient_id'] ?? $_SESSION['portal_patient_id'] ?? 0);
$release = patient_record_release_portal_access($pdo,$releaseId,(int)$portal['id'],$patientId);
if (!$release) { http_response_code(403); exit('This dental-record copy is unavailable, expired, revoked, or outside your portal access.'); }
$patient = require_patient($patientId);
$scope = (string)$release['release_scope'];
$isFinancial = $scope === 'financial';
$isReferral = $scope === 'referral';
$isSummary = $scope === 'summary';

$pdo->prepare('UPDATE `' . table('patient_record_releases') . '` SET view_count=view_count+1,last_viewed_at=NOW(),updated_at=NOW() WHERE id=?')->execute([$releaseId]);
audit('patient_record_release_viewed','patient_record_release',$releaseId,[
    'patient_id'=>$patientId,'portal_account_id'=>(int)$portal['id'],'scope'=>$scope,
]);

function portal_record_rows(PDO $pdo, string $sql, array $args): array {
    try { $stmt=$pdo->prepare($sql);$stmt->execute($args);return $stmt->fetchAll(); } catch(Throwable $e){ error_log('Patient record copy section unavailable: '.$e->getMessage()); return []; }
}
function portal_record_value($value): string { $value=trim((string)$value); return $value===''?'—':nl2br(e($value)); }
function portal_record_date(?string $value, bool $time=false): string { return $value?date($time?'F j, Y g:i A':'F j, Y',strtotime($value)):'—'; }

$medical=[];$encounters=[];$procedures=[];$plans=[];$prescriptions=[];$documents=[];$referrals=[];$followups=[];$invoices=[];$payments=[];
if (!$isFinancial) {
    $medicalRows=portal_record_rows($pdo,'SELECT * FROM `' . table('medical_histories') . '` WHERE patient_id=? AND verification_status="verified" ORDER BY COALESCE(verified_at,created_at) DESC,id DESC LIMIT 1',[$patientId]);
    $medical=$medicalRows[0]??[];
}
if (!$isFinancial && !$isReferral) {
    $args=[$patientId];$dateSql=patient_record_release_date_clause($release,'COALESCE(finalized_at,created_at)',$args);
    $limit=$isSummary?' LIMIT 5':'';
    $encounters=portal_record_rows($pdo,'SELECT id,dentist_name,chief_complaint,diagnosis,procedure_done,patient_advice,follow_up_date,follow_up_purpose,status,COALESCE(finalized_at,created_at) record_date FROM `' . table('clinical_encounters') . '` WHERE patient_id=? AND status IN ("finalized","addendum")'.$dateSql.' ORDER BY record_date DESC,id DESC'.$limit,$args);
    $args=[$patientId];$dateSql=patient_record_release_date_clause($release,'COALESCE(ended_at,started_at,created_at)',$args);
    $procedures=portal_record_rows($pdo,'SELECT procedure_name,tooth_region,status,COALESCE(ended_at,started_at,created_at) record_date FROM `' . table('procedures') . '` WHERE patient_id=? AND status="completed"'.$dateSql.' ORDER BY record_date DESC,id DESC'.($isSummary?' LIMIT 10':''),$args);
    $args=[$patientId];$dateSql=patient_record_release_date_clause($release,'created_at',$args);
    $plans=portal_record_rows($pdo,'SELECT title,phase,status,estimate_total,accepted_at,created_at,notes FROM `' . table('treatment_plans') . '` WHERE patient_id=? AND status IN ("presented","partially_accepted","accepted","scheduled","in_progress","completed")'.$dateSql.' ORDER BY created_at DESC,id DESC'.($isSummary?' LIMIT 5':''),$args);
    $args=[$patientId];$dateSql=patient_record_release_date_clause($release,'issued_at',$args);
    $prescriptions=portal_record_rows($pdo,'SELECT r.id,r.prescription_no,r.issued_at,r.clinical_indication,r.signed_by_name,r.status,i.medication_name,i.strength,i.dosage,i.frequency,i.instructions FROM `' . table('prescriptions') . '` r LEFT JOIN `' . table('prescription_items') . '` i ON i.prescription_id=r.id WHERE r.patient_id=? AND r.status="issued"'.$dateSql.' ORDER BY r.issued_at DESC,r.id DESC'.($isSummary?' LIMIT 10':''),$args);
    $args=[$patientId];$dateSql=patient_record_release_date_clause($release,'created_at',$args);
    $followups=portal_record_rows($pdo,'SELECT purpose,recommended_date,status,created_at FROM `' . table('follow_ups') . '` WHERE patient_id=?'.$dateSql.' ORDER BY recommended_date DESC,id DESC'.($isSummary?' LIMIT 10':''),$args);
}
if (!$isFinancial) {
    $args=[$patientId];$dateSql=patient_record_release_date_clause($release,'created_at',$args);
    $referrals=portal_record_rows($pdo,'SELECT provider_name,provider_type,reason,urgency,status,sent_at,outcome,created_at FROM `' . table('referrals') . '` WHERE patient_id=? AND status<>"draft"'.$dateSql.' ORDER BY created_at DESC,id DESC',$args);
    $args=[$patientId];$dateSql=patient_record_release_date_clause($release,'created_at',$args);
    $documents=portal_record_rows($pdo,'SELECT id,category,file_name,description,created_at FROM `' . table('documents') . '` WHERE patient_id=? AND access_level="patient"'.$dateSql.' ORDER BY created_at DESC,id DESC',$args);
}
if ($isFinancial || $scope === 'complete') {
    $args=[$patientId];$dateSql=patient_record_release_date_clause($release,'created_at',$args);
    $invoices=portal_record_rows($pdo,'SELECT id,invoice_no,description,amount,paid_amount,status,created_at FROM `' . table('invoices') . '` WHERE patient_id=? AND status<>"voided"'.$dateSql.' ORDER BY created_at DESC,id DESC',$args);
    if ($invoices) {
        $ids=array_map(static fn(array $r):int=>(int)$r['id'],$invoices);$marks=implode(',',array_fill(0,count($ids),'?'));
        $payments=portal_record_rows($pdo,'SELECT invoice_id,amount,method,reference_no,status,created_at FROM `' . table('payments') . '` WHERE invoice_id IN ('.$marks.') ORDER BY created_at DESC,id DESC',$ids);
    }
}

$brand=branding_profile();$clinic=public_clinic_profile();
?><!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title><?=e(patient_record_scope_label($scope))?></title><style>
@page{size:A4;margin:15mm}*{box-sizing:border-box}body{margin:0;background:#eef4f5;color:#172033;font-family:Arial,sans-serif;font-size:12px;line-height:1.5}.toolbar{position:sticky;top:0;z-index:3;display:flex;justify-content:flex-end;gap:8px;padding:10px 18px;background:#fff;border-bottom:1px solid #dce5e8}.toolbar a,.toolbar button{border:0;border-radius:9px;padding:9px 14px;font-weight:800;text-decoration:none;cursor:pointer}.toolbar a{background:#edf2f3;color:#344054}.toolbar button{background:<?=e($brand['primary'])?>;color:#fff}.document{max-width:900px;margin:20px auto;background:#fff;padding:28px;box-shadow:0 15px 45px rgba(20,33,61,.12)}.head{display:flex;justify-content:space-between;gap:20px;border-bottom:3px solid <?=e($brand['primary'])?>;padding-bottom:14px}.head h1{margin:0;font-size:23px}.head p{margin:3px 0;color:#667085}.meta{text-align:right}.notice{margin:16px 0;padding:12px;border:1px solid #cfe0e2;border-radius:10px;background:#f5fbfb}.patient{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin:16px 0}.field strong{display:block;font-size:10px;text-transform:uppercase;color:#667085}.section{margin:20px 0;break-inside:avoid}.section h2{font-size:15px;color:#0f5e59;border-bottom:1px solid #dce5e8;padding-bottom:6px}.card{border:1px solid #dce5e8;border-radius:9px;padding:11px;margin:9px 0;break-inside:avoid}.card strong,.card small{display:block}.muted{color:#667085}table{width:100%;border-collapse:collapse}th,td{text-align:left;vertical-align:top;border-bottom:1px solid #e1e7ea;padding:7px}th{font-size:10px;text-transform:uppercase;color:#667085}.footer{margin-top:28px;padding-top:10px;border-top:1px solid #dce5e8;color:#667085;font-size:10px;display:flex;justify-content:space-between}@media print{body{background:#fff}.toolbar{display:none}.document{box-shadow:none;margin:0;padding:0}}@media(max-width:700px){.document{margin:0;padding:18px}.head{display:block}.meta{text-align:left;margin-top:10px}.patient{grid-template-columns:1fr}}
</style></head><body><div class="toolbar"><a href="patient-portal?patient_id=<?=$patientId?>&amp;view=records">Back to portal</a><button onclick="window.print()">Print / Save PDF</button></div><main class="document">
<header class="head"><div><h1><?=e((string)$brand['name'])?></h1><p><?=e((string)($clinic['address']??''))?></p><p><?=e((string)($clinic['phone']??''))?><?=!empty($clinic['email'])?' · '.e((string)$clinic['email']):''?></p></div><div class="meta"><strong><?=e(patient_record_scope_label($scope))?></strong><p>Released <?=e(portal_record_date((string)$release['released_at'],true))?></p><p>Available until <?=e(portal_record_date((string)$release['expires_at']))?></p></div></header>
<div class="notice"><strong>Patient-safe dental record copy</strong><br>This copy contains finalized and patient-shared dental information only. Internal queue movement, audit history, staff approvals, and draft notes are excluded.</div>
<section class="patient"><div class="field"><strong>Patient</strong><?=e(trim((string)$patient['first_name'].' '.(string)$patient['middle_name'].' '.(string)$patient['last_name']))?></div><div class="field"><strong>Patient number</strong><?=e((string)$patient['patient_no'])?></div><div class="field"><strong>Birth date</strong><?=e(portal_record_date((string)$patient['birth_date']))?></div><div class="field"><strong>Scope</strong><?=e(patient_record_scope_label($scope))?></div><div class="field"><strong>Date range</strong><?=e((string)($release['date_from']?:'Beginning'))?> to <?=e((string)($release['date_to']?:'Present'))?></div><div class="field"><strong>Request reason</strong><?=e((string)($release['reason']?:'Patient-requested copy'))?></div></section>
<?php if(!$isFinancial&&!$isReferral):?><section class="section"><h2>Dental treatment safety summary</h2><div class="patient"><div class="field"><strong>Allergies</strong><?=portal_record_value($medical['allergies']??'')?></div><div class="field"><strong>Medicines relevant to dental care</strong><?=portal_record_value($medical['medications']??'')?></div><div class="field"><strong>Health information affecting dental care</strong><?=portal_record_value($medical['conditions']??'')?></div><div class="field"><strong>Dental history</strong><?=portal_record_value($medical['dental_history']??'')?></div></div></section><?php endif;?>
<?php if($encounters):?><section class="section"><h2>Finalized dental visits</h2><?php foreach($encounters as $row):?><article class="card"><strong><?=e(portal_record_date((string)$row['record_date'],true))?> · <?=e((string)($row['dentist_name']?:'Dentist'))?></strong><small>Chief concern: <?=e((string)($row['chief_complaint']?:'—'))?></small><p><b>Diagnosis:</b> <?=portal_record_value($row['diagnosis']??'')?></p><p><b>Treatment / procedure:</b> <?=portal_record_value($row['procedure_done']??'')?></p><p><b>Patient instructions:</b> <?=portal_record_value($row['patient_advice']??'')?></p><?php if(!empty($row['follow_up_date'])):?><small>Follow-up: <?=e(portal_record_date((string)$row['follow_up_date']))?> · <?=e((string)$row['follow_up_purpose'])?></small><?php endif;?></article><?php endforeach;?></section><?php endif;?>
<?php if($procedures):?><section class="section"><h2>Completed procedures</h2><table><thead><tr><th>Date</th><th>Procedure</th><th>Tooth / region</th></tr></thead><tbody><?php foreach($procedures as $row):?><tr><td><?=e(portal_record_date((string)$row['record_date']))?></td><td><?=e((string)$row['procedure_name'])?></td><td><?=e(trim((string)($row['tooth_region']?:'General dentition')))?></td></tr><?php endforeach;?></tbody></table></section><?php endif;?>
<?php if($plans):?><section class="section"><h2>Treatment plans shared with the patient</h2><?php foreach($plans as $row):?><article class="card"><strong><?=e((string)$row['title'])?></strong><small><?=e(ucwords(str_replace('_',' ',(string)$row['status'])))?> · <?=e((string)($row['phase']?:'No phase'))?></small><p><?=portal_record_value($row['notes']??'')?></p></article><?php endforeach;?></section><?php endif;?>
<?php if($prescriptions):?><section class="section"><h2>Issued dental prescriptions</h2><table><thead><tr><th>Date</th><th>Prescription</th><th>Instructions</th><th>Dentist</th></tr></thead><tbody><?php foreach($prescriptions as $row):?><tr><td><?=e(portal_record_date((string)$row['issued_at']))?></td><td><strong><?=e(trim((string)$row['medication_name'].' '.(string)$row['strength']))?></strong><small><?=e((string)$row['prescription_no'])?></small></td><td><?=e(trim((string)$row['dosage'].' · '.(string)$row['frequency']))?><br><?=e((string)$row['instructions'])?></td><td><?=e((string)($row['signed_by_name']?:'Dentist'))?></td></tr><?php endforeach;?></tbody></table></section><?php endif;?>
<?php if($referrals):?><section class="section"><h2>Referrals</h2><?php foreach($referrals as $row):?><article class="card"><strong><?=e((string)$row['provider_name'])?></strong><small><?=e(ucfirst((string)$row['urgency']))?> · <?=e(ucwords(str_replace('_',' ',(string)$row['status'])))?></small><p><?=portal_record_value($row['reason']??'')?></p><?php if(!empty($row['outcome'])):?><p><b>Outcome:</b> <?=portal_record_value($row['outcome'])?></p><?php endif;?></article><?php endforeach;?></section><?php endif;?>
<?php if($documents):?><section class="section"><h2>Patient-shared documents</h2><table><thead><tr><th>Date</th><th>Document</th><th>Description</th></tr></thead><tbody><?php foreach($documents as $row):?><tr><td><?=e(portal_record_date((string)$row['created_at']))?></td><td><?=e((string)$row['file_name'])?></td><td><?=e((string)($row['description']?:$row['category']))?></td></tr><?php endforeach;?></tbody></table><p class="muted">Open the original shared files from the Documents section of the patient portal.</p></section><?php endif;?>
<?php if($followups):?><section class="section"><h2>Follow-up recommendations</h2><table><thead><tr><th>Recommended date</th><th>Purpose</th><th>Status</th></tr></thead><tbody><?php foreach($followups as $row):?><tr><td><?=e(portal_record_date((string)$row['recommended_date']))?></td><td><?=e((string)$row['purpose'])?></td><td><?=e(ucwords(str_replace('_',' ',(string)$row['status'])))?></td></tr><?php endforeach;?></tbody></table></section><?php endif;?>
<?php if($invoices):?><section class="section"><h2>Financial records</h2><table><thead><tr><th>Date</th><th>Invoice</th><th>Description</th><th>Total</th><th>Paid</th><th>Status</th></tr></thead><tbody><?php foreach($invoices as $row):?><tr><td><?=e(portal_record_date((string)$row['created_at']))?></td><td><?=e((string)$row['invoice_no'])?></td><td><?=e((string)$row['description'])?></td><td>₱<?=number_format((float)$row['amount'],2)?></td><td>₱<?=number_format((float)$row['paid_amount'],2)?></td><td><?=e(ucwords(str_replace('_',' ',(string)$row['status'])))?></td></tr><?php endforeach;?></tbody></table><?php if($payments):?><h3>Payments and receipt references</h3><table><thead><tr><th>Date</th><th>Method</th><th>Reference</th><th>Amount</th><th>Status</th></tr></thead><tbody><?php foreach($payments as $row):?><tr><td><?=e(portal_record_date((string)$row['created_at'],true))?></td><td><?=e(ucwords(str_replace('_',' ',(string)$row['method'])))?></td><td><?=e((string)($row['reference_no']?:'—'))?></td><td>₱<?=number_format((float)$row['amount'],2)?></td><td><?=e(ucwords(str_replace('_',' ',(string)$row['status'])))?></td></tr><?php endforeach;?></tbody></table><?php endif;?></section><?php endif;?>
<?php if(!$medical&&!$encounters&&!$procedures&&!$plans&&!$prescriptions&&!$documents&&!$referrals&&!$followups&&!$invoices):?><section class="section"><p class="muted">No finalized or patient-shared records match the approved scope.</p></section><?php endif;?>
<footer class="footer"><span>Confidential dental record. Share only with the intended recipient.</span><span>Release #<?=$releaseId?></span></footer></main></body></html>
