<?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();$patientId=(int)($_GET['patient_id']??0);if($patientId)require_patient($patientId);$chartId=(int)($_GET['chart_id']??0);
if($_SERVER['REQUEST_METHOD']==='POST'){
    verify_csrf();require_clinical_record_editor(['dentist']);$action=$_POST['action']??'';
    if($action==='create_chart'){$patientId=(int)$_POST['patient_id'];require_patient($patientId);$stmt=$pdo->prepare('INSERT INTO `' . table('periodontal_charts') . '` (patient_id,encounter_id,dentist_user_id,chart_date,risk_classification,notes,created_at) VALUES (?,?,?,?,?,?,NOW())');$stmt->execute([$patientId,$_POST['encounter_id']?:null,has_role('dentist')?(int)current_user()['id']:($_POST['dentist_user_id']?:null),$_POST['chart_date'],trim((string)$_POST['risk_classification']),trim((string)$_POST['notes'])]);$chartId=(int)$pdo->lastInsertId();audit('periodontal_chart_created','periodontal_chart',$chartId,['patient_id'=>$patientId]);module_return('periodontal.php?patient_id='.$patientId.'&chart_id='.$chartId,'success','Periodontal chart created.');}
    if($action==='save_measurement'){$chartId=(int)$_POST['chart_id'];$chart=module_require_record_scope($pdo,'periodontal_charts',$chartId,'patient_id','dentist_user_id',true);$patientId=(int)$chart['patient_id'];$stmt=$pdo->prepare('INSERT INTO `' . table('periodontal_measurements') . '` (chart_id,tooth_number,site,probing_depth_mm,recession_mm,bleeding,suppuration,plaque,mobility,furcation,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,NOW()) ON DUPLICATE KEY UPDATE probing_depth_mm=VALUES(probing_depth_mm),recession_mm=VALUES(recession_mm),bleeding=VALUES(bleeding),suppuration=VALUES(suppuration),plaque=VALUES(plaque),mobility=VALUES(mobility),furcation=VALUES(furcation)');$stmt->execute([$chartId,trim((string)$_POST['tooth_number']),$_POST['site'],$_POST['probing_depth_mm']!==''?(int)$_POST['probing_depth_mm']:null,$_POST['recession_mm']!==''?(int)$_POST['recession_mm']:null,isset($_POST['bleeding'])?1:0,isset($_POST['suppuration'])?1:0,isset($_POST['plaque'])?1:0,$_POST['mobility']!==''?(int)$_POST['mobility']:null,trim((string)$_POST['furcation'])]);audit('periodontal_measurement_saved','periodontal_chart',$chartId);module_return('periodontal.php?patient_id='.$patientId.'&chart_id='.$chartId,'success','Measurement saved.');}
}
$charts=[];$chart=null;$measurements=[];if($patientId){$stmt=$pdo->prepare('SELECT c.*,u.name dentist FROM `' . table('periodontal_charts') . '` c LEFT JOIN `' . table('users') . '` u ON u.id=c.dentist_user_id WHERE c.patient_id=? ORDER BY c.chart_date DESC,c.id DESC');$stmt->execute([$patientId]);$charts=$stmt->fetchAll();if(!$chartId&&$charts)$chartId=(int)$charts[0]['id'];}
if($chartId){$stmt=$pdo->prepare('SELECT c.*,CONCAT(p.first_name," ",p.last_name) patient FROM `' . table('periodontal_charts') . '` c JOIN `' . table('patients') . '` p ON p.id=c.patient_id WHERE c.id=?');$stmt->execute([$chartId]);$chart=$stmt->fetch();if($chart){$patientId=(int)$chart['patient_id'];$m=$pdo->prepare('SELECT * FROM `' . table('periodontal_measurements') . '` WHERE chart_id=? ORDER BY tooth_number,FIELD(site,"MB","B","DB","ML","L","DL")');$m->execute([$chartId]);$measurements=$m->fetchAll();}}
$dentists=dentist_options();render_header('Periodontal Charts');render_module_intro('Periodontal assessment','Create date-based charts and record six-point tooth measurements.',$canEdit?'New periodontal chart':null,$canEdit?'perio-chart-form':null);render_patient_filter($patients,'periodontal.php',$patientId);
if($patientId):?><div class="tabs"><?php foreach($charts as $item):?><a class="<?=$chartId===(int)$item['id']?'active':''?>" href="periodontal.php?patient_id=<?=$patientId?>&chart_id=<?=(int)$item['id']?>"><?=e(date('M j, Y',strtotime($item['chart_date'])))?></a><?php endforeach;?></div><?php endif;?>
<?php if($chart):?><div class="card"><div class="card-head"><div><h2><?=e($chart['patient'])?></h2><p><?=e(date('F j, Y',strtotime($chart['chart_date'])))?> · Risk: <?=e($chart['risk_classification']?:'Not classified')?></p></div><?php if($canEdit):?><button class="btn primary" data-open="perio-measure-form">Add measurement</button><?php endif;?></div><?php if($chart['notes']):?><p><?=nl2br(e($chart['notes']))?></p><?php endif;?></div><div class="card table-wrap"><table><thead><tr><th>Tooth</th><th>Site</th><th>Probing</th><th>Recession</th><th>Bleeding</th><th>Plaque</th><th>Mobility</th><th>Furcation</th></tr></thead><tbody><?php foreach($measurements as $row):?><tr><td><strong><?=e($row['tooth_number'])?></strong></td><td><?=e($row['site'])?></td><td><?=e($row['probing_depth_mm']??'—')?> mm</td><td><?=e($row['recession_mm']??'—')?> mm</td><td><?= $row['bleeding']?'Yes':'No' ?></td><td><?= $row['plaque']?'Yes':'No' ?></td><td><?=e($row['mobility']??'—')?></td><td><?=e($row['furcation']?:'—')?></td></tr><?php endforeach;?><?php if(!$measurements):?><tr><td colspan="8">No measurements recorded.</td></tr><?php endif;?></tbody></table></div><?php elseif($patientId):?><div class="card queue-empty">No periodontal chart yet. Create the first chart.</div><?php else:?><div class="card queue-empty">Select a patient to review periodontal history.</div><?php endif;?>
<?php if($canEdit):?><dialog id="perio-chart-form" class="wide-dialog"><form method="post" class="form-grid"><button type="button" class="dialog-close" data-close>×</button><h2 class="wide">New periodontal chart</h2><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="create_chart"><label>Patient<?php module_patient_select($patients,'patient_id',$patientId);?></label><label>Chart date<input type="date" name="chart_date" value="<?=e(date('Y-m-d'))?>" required></label><label>Dentist<?php module_dentist_select($dentists);?></label><label>Encounter ID<input type="number" name="encounter_id"></label><label>Risk classification<input name="risk_classification" placeholder="Low, moderate, high"></label><label class="wide">Notes<textarea name="notes"></textarea></label><button class="btn primary" type="submit">Create chart</button></form></dialog>
<dialog id="perio-measure-form" class="wide-dialog"><form method="post" class="form-grid"><button type="button" class="dialog-close" data-close>×</button><h2 class="wide">Periodontal measurement</h2><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="save_measurement"><input type="hidden" name="chart_id" value="<?=$chartId?>"><label>Tooth number<input name="tooth_number" required></label><label>Site<select name="site"><?php foreach(['MB','B','DB','ML','L','DL'] as $site):?><option><?=e($site)?></option><?php endforeach;?></select></label><label>Probing depth (mm)<input type="number" min="0" max="20" name="probing_depth_mm"></label><label>Recession (mm)<input type="number" min="0" max="20" name="recession_mm"></label><label>Mobility<input type="number" min="0" max="3" name="mobility"></label><label>Furcation<input name="furcation" placeholder="I, II, III"></label><label class="check-option"><input type="checkbox" name="bleeding"><span>Bleeding on probing</span></label><label class="check-option"><input type="checkbox" name="suppuration"><span>Suppuration</span></label><label class="check-option"><input type="checkbox" name="plaque"><span>Plaque present</span></label><button class="btn primary" type="submit">Save measurement</button></form></dialog>
<?php endif; render_footer();
