<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
require_roles(['super_admin','clinic_admin']);
require DENTAL_ROOT . '/app/layout.php';
require_once DENTAL_ROOT . '/app/module_helpers.php';


if (!function_exists('module_status')) {
    function module_status(string $status): string { return ucwords(str_replace('_', ' ', $status)); }
}

$pdo = db();
$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        verify_csrf();
        $mode = (string)($_POST['mode'] ?? 'auto');
        if (!in_array($mode, ['auto','auto_allow_override','manual'], true)) $mode = 'auto';
        $prefix = strtoupper(trim((string)($_POST['prefix'] ?? 'P')));
        $prefix = preg_replace('/[^A-Z0-9]/', '', $prefix) ?: 'P';
        $yearFormat = (string)($_POST['year_format'] ?? 'Y');
        if (!in_array($yearFormat, ['none','Y','y','ym','ymd'], true)) $yearFormat = 'Y';
        $separator = trim((string)($_POST['separator'] ?? ''));
        if (!in_array($separator, ['', '-', '/', '.'], true)) $separator = '';
        $padding = max(1, min(8, (int)($_POST['padding'] ?? 4)));
        $next = max(1, (int)($_POST['next_number'] ?? 1));
        setting_set('patient_numbering','mode',$mode);
        setting_set('patient_numbering','prefix',$prefix);
        setting_set('patient_numbering','year_format',$yearFormat);
        setting_set('patient_numbering','separator',$separator);
        setting_set('patient_numbering','padding',(string)$padding);
        setting_set('patient_numbering','next_number',(string)$next);
        setting_set('system','patient_numbering_configured','1');
        audit('patient_numbering_updated','system',null,['mode'=>$mode,'prefix'=>$prefix,'year_format'=>$yearFormat,'separator'=>$separator,'padding'=>$padding,'next_number'=>$next]);
        flash('success','Patient numbering settings were saved.');
        header('Location: patient_numbering.php'); exit;
    } catch (Throwable $exception) {
        $error = $exception->getMessage();
    }
}

$settings = dental_patient_numbering_settings();
$preview = dental_patient_number_preview($settings);
$lastPatients = [];
try {
    if (schema_table_exists(table('patients'))) {
        $lastPatients = $pdo->query('SELECT patient_no,first_name,last_name,created_at FROM `' . table('patients') . '` ORDER BY id DESC LIMIT 8')->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
} catch (Throwable) {}

render_header('Patient Numbering');
?>
<section class="admin-hero card">
    <div><span class="eyebrow">Superuser settings</span><h2>Patient number control</h2><p>Control how new patient numbers are issued. Default live format is P + YYYY + four-digit sequence, for example P20260001.</p><div class="status-actions"><a class="btn ghost" href="patients.php?action=new">Register Patient</a><a class="btn ghost" href="setup_wizard.php">Setup Wizard</a></div></div>
    <div class="admin-hero-icon"><?= dental_icon('patients') ?></div>
</section>
<?php if($error):?><div class="flash error"><?=e($error)?></div><?php endif;?>
<section class="stats setup-stats">
    <?php stat_card('Current mode', module_status((string)$settings['mode']), 'Automatic, manual, or override'); ?>
    <?php stat_card('Next preview', $preview, 'Next generated number'); ?>
    <?php stat_card('Next counter', (string)$settings['next_number'], 'Incremented after each auto issue'); ?>
</section>
<section class="card">
    <div class="card-head"><div><h2>Numbering format</h2><p>Example output updates after saving. Manual mode requires staff to type the number during patient registration.</p></div><span class="version-pill">Preview: <?=e($preview)?></span></div>
    <form method="post" class="form-grid">
        <input type="hidden" name="csrf" value="<?=e(csrf_token())?>">
        <label>Mode<select name="mode"><option value="auto" <?=$settings['mode']==='auto'?'selected':''?>>Automatic only</option><option value="auto_allow_override" <?=$settings['mode']==='auto_allow_override'?'selected':''?>>Automatic, allow manual override</option><option value="manual" <?=$settings['mode']==='manual'?'selected':''?>>Manual entry required</option></select><small>Recommended: Automatic only for live clinics.</small></label>
        <label>Prefix<input name="prefix" maxlength="12" value="<?=e((string)$settings['prefix'])?>"><small>Letters/numbers only. Example: P, DC, MB.</small></label>
        <label>Date segment<select name="year_format"><option value="Y" <?=$settings['year_format']==='Y'?'selected':''?>>YYYY — recommended</option><option value="ymd" <?=$settings['year_format']==='ymd'?'selected':''?>>YYMMDD</option><option value="ym" <?=$settings['year_format']==='ym'?'selected':''?>>YYMM</option><option value="y" <?=$settings['year_format']==='y'?'selected':''?>>YY</option><option value="none" <?=$settings['year_format']==='none'?'selected':''?>>No date</option></select><small>Recommended: YYYY gives IDs such as P20260001.</small></label>
        <label>Separator<select name="separator"><option value="" <?=$settings['separator']===''?'selected':''?>>None</option><option value="-" <?=$settings['separator']==='-'?'selected':''?>>Dash -</option><option value="/" <?=$settings['separator']==='/'?'selected':''?>>Slash /</option><option value="." <?=$settings['separator']==='.'?'selected':''?>>Dot .</option></select></label>
        <label>Number padding<input type="number" min="1" max="8" name="padding" value="<?=e((string)$settings['padding'])?>"><small>Example: 4 gives 0001.</small></label>
        <label>Next number<input type="number" min="1" name="next_number" value="<?=e((string)$settings['next_number'])?>"><small>Use carefully. Do not set it lower than existing records unless you know the number is unused.</small></label>
        <div class="wide alert info"><strong>Generated example:</strong> <?=e($preview)?>. Existing patient numbers are not changed automatically.</div>
        <button class="btn primary">Save patient numbering</button>
    </form>
</section>
<section class="card table-wrap">
    <div class="card-head"><div><h2>Recent patient numbers</h2><p>Use this to avoid duplicates before changing the counter.</p></div></div>
    <table><thead><tr><th>Patient No.</th><th>Name</th><th>Created</th></tr></thead><tbody><?php foreach($lastPatients as $row):?><tr><td><strong><?=e((string)$row['patient_no'])?></strong></td><td><?=e(trim((string)$row['last_name'].', '.(string)$row['first_name'],', '))?></td><td><?=!empty($row['created_at'])?e(date('M j, Y g:i A',strtotime((string)$row['created_at']))):'—'?></td></tr><?php endforeach;if(!$lastPatients):?><tr><td colspan="3" class="muted">No patient records found.</td></tr><?php endif;?></tbody></table>
</section>
<?php render_footer();
