<?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';
$pdo=db();$canEdit=clinical_record_edit_allowed(['dentist']);$patients=patient_options();$dentists=dentist_options();$patientId=(int)($_GET['patient_id']??0);if($patientId)require_patient($patientId);
if($_SERVER['REQUEST_METHOD']==='POST'){
 verify_csrf();require_clinical_record_editor(['dentist']);$action=$_POST['action']??'create';
 if($action==='create'){$patientId=(int)$_POST['patient_id'];require_patient($patientId);$stmt=$pdo->prepare('INSERT INTO `' . table('referrals') . '` (patient_id,encounter_id,referring_dentist_id,provider_name,provider_type,reason,urgency,status,sent_at,notes,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,NOW())');$status=$_POST['status'];$stmt->execute([$patientId,$_POST['encounter_id']?:null,has_role('dentist')?(int)current_user()['id']:($_POST['referring_dentist_id']?:null),trim((string)$_POST['provider_name']),trim((string)$_POST['provider_type']),trim((string)$_POST['reason']),$_POST['urgency'],$status,$status==='sent'?date('Y-m-d H:i:s'):null,trim((string)$_POST['notes'])]);$id=(int)$pdo->lastInsertId();audit('referral_created','referral',$id,['patient_id'=>$patientId]);module_return('referrals.php?patient_id='.$patientId,'success','Referral saved.');}
 if($action==='status'){$id=(int)$_POST['id'];module_require_record_scope($pdo,'referrals',$id,'patient_id','referring_dentist_id',true);$status=(string)$_POST['status'];if(!in_array($status,['draft','sent','received','appointment_scheduled','report_returned','completed','cancelled'],true))throw new RuntimeException('Select a valid referral status.');$returned=in_array($status,['report_returned','completed'],true)?date('Y-m-d H:i:s'):null;$stmt=$pdo->prepare('UPDATE `' . table('referrals') . '` SET status=?,returned_at=COALESCE(?,returned_at),outcome=?,notes=? WHERE id=?');$stmt->execute([$status,$returned,trim((string)$_POST['outcome']),trim((string)$_POST['notes']),$id]);$stmt=$pdo->prepare('SELECT patient_id FROM `' . table('referrals') . '` WHERE id=?');$stmt->execute([$id]);$patientId=(int)$stmt->fetchColumn();audit('referral_status_updated','referral',$id,['status'=>$status]);module_return('referrals.php?patient_id='.$patientId,'success','Referral updated.');}
}
$state=module_management_state();$q=$state['query'];$statusFilter=module_safe_status_filter('status',['','draft','sent','received','appointment_scheduled','report_returned','completed','cancelled']);$urgencyFilter=module_safe_status_filter('urgency',['','routine','urgent','emergency']);
$where=['1=1'];$args=[];if($patientId){$where[]='r.patient_id=?';$args[]=$patientId;}[$scopeSql,$scopeArgs]=task_patient_scope_condition('r.patient_id');if($scopeSql!==''){$where[]=substr(trim($scopeSql),4);$args=array_merge($args,$scopeArgs);}if($q!==''){$term=module_like_term($q);$where[]='(r.provider_name LIKE ? ESCAPE "\\" OR r.provider_type LIKE ? ESCAPE "\\" OR r.reason LIKE ? ESCAPE "\\" OR CONCAT(p.first_name," ",p.last_name) LIKE ? ESCAPE "\\")';array_push($args,$term,$term,$term,$term);}if($statusFilter!==''){$where[]='r.status=?';$args[]=$statusFilter;}if($urgencyFilter!==''){$where[]='r.urgency=?';$args[]=$urgencyFilter;}$whereSql=implode(' AND ',$where);
$count=$pdo->prepare('SELECT COUNT(*) FROM `' . table('referrals') . '` r JOIN `' . table('patients') . '` p ON p.id=r.patient_id WHERE '.$whereSql);$count->execute($args);$total=(int)$count->fetchColumn();$pages=max(1,(int)ceil($total/$state['per_page']));$state['page']=min($state['page'],$pages);$state['offset']=($state['page']-1)*$state['per_page'];$stmt=$pdo->prepare('SELECT r.*,CONCAT(p.first_name," ",p.last_name) patient,p.patient_no,u.name dentist FROM `' . table('referrals') . '` r JOIN `' . table('patients') . '` p ON p.id=r.patient_id LEFT JOIN `' . table('users') . '` u ON u.id=r.referring_dentist_id WHERE '.$whereSql.' ORDER BY r.created_at DESC LIMIT '.$state['per_page'].' OFFSET '.$state['offset']);$stmt->execute($args);$rows=$stmt->fetchAll();
$selected=null;if($state['manage_id']>0){$stmt=$pdo->prepare('SELECT r.*,CONCAT(p.first_name," ",p.last_name) patient,p.patient_no,u.name dentist FROM `' . table('referrals') . '` r JOIN `' . table('patients') . '` p ON p.id=r.patient_id LEFT JOIN `' . table('users') . '` u ON u.id=r.referring_dentist_id WHERE r.id=? LIMIT 1');$stmt->execute([$state['manage_id']]);$candidate=$stmt->fetch();if($candidate){require_patient((int)$candidate['patient_id']);$selected=$candidate;}}
render_header('Referrals');render_module_intro('Referral coordination','Track medical clearance and specialist referrals from creation through returned reports.',$canEdit?'New referral':null,$canEdit?'referral-form':null);
?>
<div class="management-workspace"><form method="get" class="card management-filters"><label>Search referrals<input type="search" name="q" value="<?=e($q)?>" placeholder="Patient, provider, type, or reason"></label><label>Patient<select name="patient_id"><option value="">All patients</option><?php foreach($patients as $patient):?><option value="<?=(int)$patient['id']?>" <?=$patientId===(int)$patient['id']?'selected':''?>><?=e($patient['patient_no'].' — '.$patient['last_name'].', '.$patient['first_name'])?></option><?php endforeach;?></select></label><label>Status<select name="status"><option value="">All statuses</option><?php foreach(['draft','sent','received','appointment_scheduled','report_returned','completed','cancelled'] as $status):?><option value="<?=$status?>" <?=$statusFilter===$status?'selected':''?>><?=e(module_status($status))?></option><?php endforeach;?></select></label><label>Urgency<select name="urgency"><option value="">All</option><?php foreach(['routine','urgent','emergency'] as $urgency):?><option value="<?=$urgency?>" <?=$urgencyFilter===$urgency?'selected':''?>><?=e(module_status($urgency))?></option><?php endforeach;?></select></label><div class="filter-actions"><button class="btn primary">Filter</button><a class="btn ghost" href="referrals.php">Reset</a></div></form>
<section class="card management-table-card"><div class="card-head"><div><h2>Referral directory</h2><p>One compact row per referral; clinical updates open only for the selected record.</p></div><?php module_render_list_count($total,'referrals');?></div><?php module_render_server_pagination($total,$state['page'],$state['per_page'],'page','per_page','referrals');?><div class="table-wrap"><table><thead><tr><th>Created</th><th>Patient</th><th>Receiving provider</th><th>Type</th><th>Urgency</th><th>Referring Dentist</th><th>Status</th><th></th></tr></thead><tbody><?php foreach($rows as $row):?><tr><td><?=e(date('M j, Y',strtotime((string)$row['created_at'])))?></td><td><strong><?=e($row['patient'])?></strong><small><?=e((string)$row['patient_no'])?></small></td><td><strong><?=e($row['provider_name'])?></strong><small class="management-row-note"><?=e((string)$row['reason'])?></small></td><td><?=e((string)($row['provider_type']?:'Referral'))?></td><td><span class="badge"><?=e(module_status((string)$row['urgency']))?></span></td><td><?=e((string)($row['dentist']?:'—'))?></td><td><span class="badge"><?=e(module_status((string)$row['status']))?></span></td><td><?php if($canEdit):?><a class="btn ghost compact" href="<?=e(module_management_url(['manage_id'=>(int)$row['id']]))?>">Manage</a><?php endif;?></td></tr><?php endforeach;?><?php if(!$rows):?><tr><td colspan="8" class="management-empty">No referrals match this view.</td></tr><?php endif;?></tbody></table></div><?php module_render_server_pagination($total,$state['page'],$state['per_page'],'page','per_page','referrals');?></section>
<?php if($selected&&$canEdit):?><dialog id="manage-referral" class="management-dialog" data-auto-open-dialog="manage-referral"><form method="post" class="form-grid"><button type="button" class="dialog-close" data-close>×</button><h2 class="wide"><?=e((string)$selected['provider_name'])?></h2><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="status"><input type="hidden" name="id" value="<?=(int)$selected['id']?>"><div class="wide management-summary"><div><span>Patient</span><strong><?=e((string)$selected['patient'])?></strong></div><div><span>Urgency</span><strong><?=e(module_status((string)$selected['urgency']))?></strong></div><div><span>Created</span><strong><?=e(date('M j, Y',strtotime((string)$selected['created_at'])))?></strong></div></div><label>Status<select name="status"><?php foreach(['draft','sent','received','appointment_scheduled','report_returned','completed','cancelled'] as $status):?><option value="<?=$status?>" <?=$selected['status']===$status?'selected':''?>><?=e(module_status($status))?></option><?php endforeach;?></select></label><label>Outcome<input name="outcome" value="<?=e((string)$selected['outcome'])?>"></label><label class="wide">Notes<textarea name="notes"><?=e((string)$selected['notes'])?></textarea></label><button class="btn primary">Update referral</button><a class="btn ghost" href="<?=e(module_management_url(['manage_id'=>null]))?>">Close</a></form></dialog><?php endif;?>
<?php if($canEdit):?><dialog id="referral-form" class="wide-dialog"><form method="post" class="form-grid"><button type="button" class="dialog-close" data-close>×</button><h2 class="wide">Create referral</h2><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="create"><label>Patient<?php module_patient_select($patients,'patient_id',$patientId);?></label><label>Referring Dentist<?php module_dentist_select($dentists,'referring_dentist_id');?></label><label>Receiving provider<input name="provider_name" required></label><label>Provider type<select name="provider_type"><option>Medical Clearance</option><option>Oral Surgeon</option><option>Endodontist</option><option>Periodontist</option><option>Orthodontist</option><option>Prosthodontist</option><option>Pediatric Dentist</option><option>Radiology Center</option><option>Hospital</option><option>Dental Laboratory</option></select></label><label>Urgency<select name="urgency"><option value="routine">Routine</option><option value="urgent">Urgent</option><option value="emergency">Emergency</option></select></label><label>Status<select name="status"><option value="draft">Draft</option><option value="sent">Sent</option></select></label><label>Encounter ID<input type="number" name="encounter_id"></label><label class="wide">Reason<textarea name="reason" required></textarea></label><label class="wide">Notes<textarea name="notes"></textarea></label><button class="btn primary">Save referral</button></form></dialog><?php endif;?></div>
<?php render_footer();
