<?php
require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
require_documentation_schema();
require_permission('clinical.view',['super_admin','clinic_admin','dentist','dental_assistant']);
require DENTAL_ROOT . '/app/layout.php';
require DENTAL_ROOT . '/app/module_helpers.php';
require_once DENTAL_ROOT . '/app/clinical_media.php';
require_once DENTAL_ROOT . '/app/transaction_integrity.php';
$pdo=db();$canEdit=clinical_record_edit_allowed(['dentist','dental_assistant']);$patients=patient_options();$patientId=(int)($_GET['patient_id']??0);if($patientId){$selectedPatient=require_patient($patientId);if(!integrity_branch_scope_allowed(null,(int)($selectedPatient['branch_id']??0)))access_denied('This patient belongs to another clinic branch.');}
if($_SERVER['REQUEST_METHOD']==='POST'){
    verify_csrf();require_clinical_record_editor(['dentist','dental_assistant']);
    $patientId=(int)$_POST['patient_id'];$uploadPatient=require_patient($patientId);if(!integrity_branch_scope_allowed(null,(int)($uploadPatient['branch_id']??0)))throw new RuntimeException('This patient belongs to another clinic branch.');
    $id=clinical_store_document_upload(
        $pdo,
        (array)($_FILES['document']??[]),
        $patientId,
        (int)($_POST['encounter_id']??0)?:null,
        trim((string)($_POST['category']??'')),
        trim((string)($_POST['tooth_region']??'')),
        trim((string)($_POST['description']??'')),
        (string)($_POST['access_level']??'clinical')
    );
    audit('clinical_document_uploaded','document',$id,['patient_id'=>$patientId,'category'=>$_POST['category']??'']);module_return('documents.php?patient_id='.$patientId,'success','Clinical file uploaded securely.');
}
$sql='SELECT d.*,p.branch_id patient_branch_id,CONCAT(p.first_name," ",p.last_name) patient,u.name uploader FROM `' . table('documents') . '` d JOIN `' . table('patients') . '` p ON p.id=d.patient_id LEFT JOIN `' . table('users') . '` u ON u.id=d.uploaded_by WHERE 1=1';$args=[];if($patientId){$sql.=' AND d.patient_id=?';$args[]=$patientId;}[$scopeSql,$scopeArgs]=task_patient_scope_condition('d.patient_id');$sql.=$scopeSql;$args=array_merge($args,$scopeArgs);$sql.=' ORDER BY d.created_at DESC LIMIT 100';$stmt=$pdo->prepare($sql);$stmt->execute($args);$rows=array_values(array_filter($stmt->fetchAll(),static function(array $row): bool { return integrity_document_staff_decision($row)['allowed']; }));
render_header('Images & Documents');render_module_intro('Secure clinical files','Store radiographs, photographs, clearances, referrals, laboratory reports, and signed records outside the public web root.',$canEdit?'Upload document':null,$canEdit?'document-form':null);render_patient_filter($patients,'documents.php',$patientId);
?>
<div class="module-card-grid"><?php foreach($rows as $row):?><article class="module-card"><div class="file-preview"><span class="file-icon"><?=str_contains($row['mime_type'],'pdf')?'PDF':'IMG'?></span><div><h3><?=e($row['category'])?></h3><p><?=e($row['file_name'])?></p></div></div><p><strong><?=e($row['patient'])?></strong><?= $row['tooth_region']?' · '.e($row['tooth_region']):'' ?></p><dl><dt>Access</dt><dd><?=e(module_status($row['access_level']))?></dd><dt>Uploaded</dt><dd><?=e(date('M j, Y',strtotime($row['created_at'])))?></dd><dt>By</dt><dd><?=e($row['uploader']?:'System')?></dd></dl><?php if($row['description']):?><p><?=nl2br(e($row['description']))?></p><?php endif;?><a class="btn ghost" href="download_document.php?id=<?=(int)$row['id']?>">Open file</a></article><?php endforeach;?><?php if(!$rows):?><div class="card queue-empty">No clinical documents found.</div><?php endif;?></div>
<?php if($canEdit):?><dialog id="document-form" class="wide-dialog"><form method="post" enctype="multipart/form-data" class="form-grid"><button type="button" class="dialog-close" data-close>×</button><h2 class="wide">Upload clinical document</h2><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><label>Patient<?php module_patient_select($patients,'patient_id',$patientId);?></label><label>Category<select name="category"><?php foreach(clinical_imaging_categories() as $category):?><option><?=e($category)?></option><?php endforeach;?><option>Medical Clearance</option><option>Laboratory Result</option><option>Referral Letter</option><option>Consent Form</option><option>Other</option></select></label><label class="wide">File<input type="file" name="document" accept="image/jpeg,image/png,image/webp,application/pdf,.jpg,.jpeg,.png,.webp,.pdf" capture="environment" required><small>Capture with the device camera or choose a JPG, PNG, WebP, or PDF up to 10 MB.</small></label><label>Encounter ID<input type="number" name="encounter_id"></label><label>Tooth or region<input name="tooth_region"></label><label>Access level<select name="access_level"><option value="clinical">Clinical team only</option><option value="staff">Authorized staff</option><option value="patient">Visible in patient portal</option></select></label><label class="wide">Description<textarea name="description"></textarea></label><button class="btn primary">Upload document</button></form></dialog>
<?php endif; render_footer();
