<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
require_permission('records.print', ['super_admin','clinic_admin','dentist','receptionist','staff','dental_assistant','cashier','inventory_officer']);
require DENTAL_ROOT . '/app/layout.php';
require DENTAL_ROOT . '/app/module_helpers.php';
require_documentation_schema();

$pdo = db();
$role = active_role();
$userId = (int)(current_user()['id'] ?? 0);
$printBranchId = superuser_primary_workspace() ? 0 : signed_user_branch_id();
$allowedCategories = [];
if (in_array($role,['super_admin','clinic_admin','dentist','dental_assistant'],true)) {
    $allowedCategories[]='patients';
    $allowedCategories[]='appointments';
}
if (in_array($role,['super_admin','clinic_admin','dentist','dental_assistant'],true)) {
    $allowedCategories[]='encounters';
    $allowedCategories[]='plans';
}
if (in_array($role,['super_admin','clinic_admin','dentist'],true)) $allowedCategories[]='prescriptions';
if (in_array($role,['super_admin','clinic_admin','cashier','staff'],true)) $allowedCategories[]='invoices';
if (in_array($role,['super_admin','clinic_admin','inventory_officer'],true)) $allowedCategories[]='reports';
if (schema_table_exists(table('print_logs'))) $allowedCategories[]='activity';

$category=(string)($_GET['category']??($allowedCategories[0]??'reports'));
if(!in_array($category,$allowedCategories,true)) $category=$allowedCategories[0]??'reports';
$q=trim((string)($_GET['q']??''));
$state=module_management_state('page','per_page',25);
$page=$state['page'];
$perPage=$state['per_page'];
$offset=$state['offset'];
$params=[];
$where=[];
$from='';
$select='';
$order='';

$activityFrom = trim((string)($_GET['activity_from'] ?? date('Y-m-d', strtotime('-30 days'))));
$activityTo = trim((string)($_GET['activity_to'] ?? date('Y-m-d')));
$activityType = trim((string)($_GET['document_type'] ?? ''));
if ($activityFrom !== '' && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $activityFrom)) $activityFrom='';
if ($activityTo !== '' && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $activityTo)) $activityTo='';

function print_center_document_label(string $type): string
{
    return match ($type) {
        'patient_summary' => 'Patient record',
        'appointment_slip' => 'Appointment slip',
        'appointment_schedule' => 'Daily appointment schedule',
        'queue_ticket' => 'Queue ticket',
        'encounter' => 'Encounter summary',
        'treatment_plan' => 'Treatment plan',
        'prescription' => 'Dental prescription',
        'invoice' => 'Invoice',
        'receipt' => 'Receipt',
        'payment_adjustment' => 'Payment return receipt',
        'inventory_stock' => 'Current stock report',
        'inventory_expiry' => 'Lot and expiration report',
        'sterilization_log' => 'Sterilization log',
        'audit_log' => 'Audit log',
        'collection_report' => 'Collection report',
        default => ucwords(str_replace('_',' ',trim($type) ?: 'Printable record')),
    };
}

switch($category){
    case 'patients':
        $from=' FROM `' . table('patients') . '` p';
        $where=['1=1'];
        $select='p.id,p.patient_no,p.first_name,p.last_name,p.email,p.mobile';
        $order='p.last_name,p.first_name,p.id';
        [$scopeSql,$scopeParams]=task_patient_scope_condition('p.id');
        if($scopeSql!==''){$where[]='1=1'.$scopeSql;$params=array_merge($params,$scopeParams);}
        break;
    case 'appointments':
        $from=' FROM `' . table('appointments') . '` a JOIN `' . table('patients') . '` p ON p.id=a.patient_id';
        $where=['a.start_at>=DATE_SUB(NOW(),INTERVAL 180 DAY)'];
        $select='a.id,a.start_at,a.service_name,a.dentist_name,a.status,p.patient_no,p.first_name,p.last_name';
        $order='a.start_at DESC,a.id DESC';
        if($role==='dentist'){
            $ids=task_dentist_scope_ids();
            if($ids){$marks=implode(',',array_fill(0,count($ids),'?'));$where[]='a.dentist_user_id IN ('.$marks.')';$params=array_merge($params,$ids);}else{$where[]='1=0';}
        } elseif(!superuser_primary_workspace()) {
            if($printBranchId>0){$where[]='a.branch_id=?';$params[]=$printBranchId;}else{$where[]='1=0';}
        }
        break;
    case 'encounters':
        $from=' FROM `' . table('clinical_encounters') . '` ce JOIN `' . table('patients') . '` p ON p.id=ce.patient_id';
        $where=['1=1'];
        $select='ce.id,ce.dentist_name,ce.created_at,p.patient_no,p.first_name,p.last_name';
        $order='ce.created_at DESC,ce.id DESC';
        [$scopeSql,$scopeParams]=task_patient_scope_condition('ce.patient_id');
        if($scopeSql!==''){$where[]='1=1'.$scopeSql;$params=array_merge($params,$scopeParams);}
        break;
    case 'plans':
        $from=' FROM `' . table('treatment_plans') . '` tp JOIN `' . table('patients') . '` p ON p.id=tp.patient_id';
        $where=['1=1'];
        $select='tp.id,tp.title,tp.status,tp.created_at,p.patient_no,p.first_name,p.last_name';
        $order='tp.created_at DESC,tp.id DESC';
        [$scopeSql,$scopeParams]=task_patient_scope_condition('tp.patient_id');
        if($scopeSql!==''){$where[]='1=1'.$scopeSql;$params=array_merge($params,$scopeParams);}
        break;
    case 'prescriptions':
        $from=' FROM `' . table('prescriptions') . '` rx JOIN `' . table('patients') . '` p ON p.id=rx.patient_id';
        $where=['1=1'];
        $select='rx.id,rx.prescription_no,rx.issued_at,p.patient_no,p.first_name,p.last_name';
        $order='rx.issued_at DESC,rx.id DESC';
        [$scopeSql,$scopeParams]=task_patient_scope_condition('rx.patient_id');
        if($scopeSql!==''){$where[]='1=1'.$scopeSql;$params=array_merge($params,$scopeParams);}
        break;
    case 'invoices':
        $from=' FROM `' . table('invoices') . '` i JOIN `' . table('patients') . '` p ON p.id=i.patient_id';
        $where=['1=1'];
        $select='i.id,i.invoice_no,i.status,i.amount,i.paid_amount,i.created_at,p.patient_no,p.first_name,p.last_name';
        $order='i.created_at DESC,i.id DESC';
        if(!superuser_primary_workspace()){
            if($printBranchId>0){$where[]='i.branch_id=?';$params[]=$printBranchId;}else{$where[]='1=0';}
        }
        break;
    case 'activity':
        $from=' FROM `' . table('print_logs') . '` pl LEFT JOIN `' . table('users') . '` u ON u.id=pl.printed_by LEFT JOIN `' . table('patients') . '` p ON p.id=pl.patient_id LEFT JOIN `' . table('branches') . '` b ON b.id=pl.branch_id';
        $where=['1=1'];
        $select='pl.*,u.name requested_by_name,p.patient_no,p.first_name,p.last_name,b.name branch_name';
        $order='pl.printed_at DESC,pl.id DESC';
        if (!superuser_primary_workspace()) {
            if ($role === 'clinic_admin') {
                if ($printBranchId > 0) {$where[]='pl.branch_id=?';$params[]=$printBranchId;} else {$where[]='1=0';}
            } else {
                $where[]='pl.printed_by=?';
                $params[]=$userId;
            }
        }
        if ($activityFrom !== '') {$where[]='pl.printed_at>=?';$params[]=$activityFrom . ' 00:00:00';}
        if ($activityTo !== '') {$where[]='pl.printed_at<?';$params[]=date('Y-m-d',strtotime($activityTo.' +1 day')).' 00:00:00';}
        if ($activityType !== '') {$where[]='pl.document_type=?';$params[]=$activityType;}
        break;
}

if($category==='activity'&&$q!==''){
    $like=module_like_term($q);
    $where[]='(pl.document_type LIKE ? OR pl.reason LIKE ? OR u.name LIKE ? OR p.patient_no LIKE ? OR p.first_name LIKE ? OR p.last_name LIKE ?)';
    array_push($params,$like,$like,$like,$like,$like,$like);
} elseif($category!=='reports'&&$q!=='') {
    $like=module_like_term($q);
    $where[]='(p.patient_no LIKE ? OR p.first_name LIKE ? OR p.last_name LIKE ?'.($category==='appointments'?' OR a.service_name LIKE ? OR a.dentist_name LIKE ?':'').($category==='plans'?' OR tp.title LIKE ?':'').($category==='prescriptions'?' OR rx.prescription_no LIKE ?':'').($category==='invoices'?' OR i.invoice_no LIKE ?':'').')';
    array_push($params,$like,$like,$like);
    if($category==='appointments') array_push($params,$like,$like);
    elseif(in_array($category,['plans','prescriptions','invoices'],true)) $params[]=$like;
}

$rows=[];
$total=0;
if($category!=='reports'){
    $whereSql=implode(' AND ',$where);
    $countStmt=$pdo->prepare('SELECT COUNT(*)'.$from.' WHERE '.$whereSql);
    $countStmt->execute($params);
    $total=(int)$countStmt->fetchColumn();
    $listStmt=$pdo->prepare('SELECT '.$select.$from.' WHERE '.$whereSql.' ORDER BY '.$order.' LIMIT '.$perPage.' OFFSET '.$offset);
    $listStmt->execute($params);
    $rows=$listStmt->fetchAll();
}

$activityTypes=[];
if ($category==='activity') {
    try {
        $typeSql='SELECT DISTINCT document_type FROM `' . table('print_logs') . '` WHERE document_type<>""';
        $typeArgs=[];
        if (!superuser_primary_workspace()) {
            if ($role==='clinic_admin' && $printBranchId>0) {$typeSql.=' AND branch_id=?';$typeArgs[]=$printBranchId;}
            elseif ($role!=='clinic_admin') {$typeSql.=' AND printed_by=?';$typeArgs[]=$userId;}
        }
        $typeSql.=' ORDER BY document_type';
        $typeStmt=$pdo->prepare($typeSql);
        $typeStmt->execute($typeArgs);
        $activityTypes=$typeStmt->fetchAll(PDO::FETCH_COLUMN) ?: [];
    } catch (Throwable $exception) {
        error_log('Print activity type filter unavailable: '.$exception->getMessage());
    }
}

render_header('Records & Printing');
?>
<section class="card print-center-intro">
    <div><span class="eyebrow">Controlled records</span><h2>Search, select, and print an authorized record</h2><p>Only the selected record category is queried. This avoids loading hundreds of patients, encounters, appointments, and invoices into large dropdowns.</p></div>
    <div class="print-guide"><strong>Browser printing</strong><span>Open a record, then choose Print or Save as PDF.</span></div>
</section>
<div class="toolbar"><div class="tabs"><?php foreach($allowedCategories as $tab): $tabLabel=$tab==='activity'?'Print activity':ucwords(str_replace('_',' ',$tab));?><a class="<?=$category===$tab?'active':''?>" href="print_center.php?category=<?=e($tab)?>"><?=e($tabLabel)?></a><?php endforeach;?></div></div>

<?php if($category==='activity'): ?>
<section class="card">
    <div class="card-head"><div><span class="eyebrow">Requested printable pages</span><h2>Print activity</h2><p>This records when an authorized printable page was opened. A web application cannot confirm whether the browser physically printed it or saved it as a PDF.</p></div><span class="version-pill"><?=$total?> request<?=$total===1?'':'s'?></span></div>
    <form method="get" class="management-filter-bar">
        <input type="hidden" name="category" value="activity">
        <label>Search<input name="q" value="<?=e($q)?>" placeholder="Document, patient, user, or reason"></label>
        <label>Document<select name="document_type"><option value="">All document types</option><?php foreach($activityTypes as $typeOption):?><option value="<?=e((string)$typeOption)?>" <?=$activityType===(string)$typeOption?'selected':''?>><?=e(print_center_document_label((string)$typeOption))?></option><?php endforeach;?></select></label>
        <label>From<input type="date" name="activity_from" value="<?=e($activityFrom)?>"></label>
        <label>To<input type="date" name="activity_to" value="<?=e($activityTo)?>"></label>
        <label>Rows<select name="per_page"><?php foreach([10,25,50,100] as $size):?><option value="<?=$size?>" <?=$perPage===$size?'selected':''?>><?=$size?></option><?php endforeach;?></select></label>
        <button class="btn primary">Apply</button><a class="btn ghost" href="print_center.php?category=activity">Reset</a>
    </form>
</section>
<div class="card server-list-card"><?php module_render_server_pagination($total,$page,$perPage,'page','per_page','print-activity');?><div class="table-wrap"><table><thead><tr><th>Opened</th><th>Printable document</th><th>Patient / record</th><th>Requested by</th><th>Reason and scope</th></tr></thead><tbody><?php foreach($rows as $row): $patientName=trim((string)($row['first_name']??'').' '.(string)($row['last_name']??''));?><tr><td><strong><?=e(date('M j, Y',strtotime((string)$row['printed_at'])))?></strong><small><?=e(date('g:i A',strtotime((string)$row['printed_at'])))?></small></td><td><strong><?=e(print_center_document_label((string)$row['document_type']))?></strong><small><?=e(strtoupper((string)($row['format']??'html')))?> · Opened for print</small></td><td><?= $patientName!==''?'<strong>'.e($patientName).'</strong>':'<span class="muted">No patient attached</span>' ?><?php if(!empty($row['patient_no'])):?><small><?=e((string)$row['patient_no'])?></small><?php endif;?><?php if(!empty($row['record_id'])):?><small>Record #<?=(int)$row['record_id']?></small><?php endif;?></td><td><strong><?=e((string)($row['requested_by_name']??'System/removed user'))?></strong><small><?=e((string)($row['branch_name']??($row['branch_id']?'Assigned branch':'Organization-wide')))?></small></td><td><?=e((string)($row['reason']?:'Routine authorized print request'))?></td></tr><?php endforeach;if(!$rows):?><tr><td colspan="5" class="muted">No printable-page requests match these filters.</td></tr><?php endif;?></tbody></table></div><?php module_render_server_pagination($total,$page,$perPage,'page','per_page','print-activity');?></div>
<?php elseif($category!=='reports'): ?>
<form method="get" class="management-filter-bar"><input type="hidden" name="category" value="<?=e($category)?>"><label>Search<input name="q" value="<?=e($q)?>" placeholder="Patient number, name, service or document no."></label><label>Rows<select name="per_page"><?php foreach([10,25,50,100] as $size):?><option value="<?=$size?>" <?=$perPage===$size?'selected':''?>><?=$size?></option><?php endforeach;?></select></label><button class="btn primary">Search</button><a class="btn ghost" href="print_center.php?category=<?=e($category)?>">Reset</a></form>
<div class="card server-list-card"><?php module_render_list_count($total,'records');module_render_server_pagination($total,$page,$perPage,'page','per_page','print-records');?><div class="table-wrap"><table><thead><tr><th>Record</th><th>Details</th><th>Available print documents</th></tr></thead><tbody><?php foreach($rows as $row):?><tr><td><strong><?=e((string)$row['last_name'].', '.(string)$row['first_name'])?></strong><small><?=e((string)$row['patient_no'])?></small></td><td><?php if($category==='patients'):?><?=e((string)($row['mobile']?:$row['email']?:'No contact recorded'))?><?php elseif($category==='appointments'):?><?=e(date('M j, Y g:i A',strtotime((string)$row['start_at'])))?><small><?=e((string)$row['service_name'])?> · <?=e((string)($row['dentist_name']?:'Provider not recorded'))?></small><?php elseif($category==='encounters'):?><?=e(date('M j, Y',strtotime((string)$row['created_at'])))?><small><?=e((string)($row['dentist_name']?:'Dentist not recorded'))?></small><?php elseif($category==='plans'):?><?=e((string)$row['title'])?><small><?=e(module_status((string)$row['status']))?></small><?php elseif($category==='prescriptions'):?><?=e((string)$row['prescription_no'])?><small><?=e(date('M j, Y',strtotime((string)$row['issued_at'])))?></small><?php else:?><?=e((string)$row['invoice_no'])?> · ₱<?=number_format((float)$row['amount'],2)?><small><?=e(module_status((string)$row['status']))?> · paid ₱<?=number_format((float)$row['paid_amount'],2)?></small><?php endif;?></td><td><div class="inline-actions"><?php if($category==='patients'):?><a target="_blank" href="print_record.php?type=patient_summary&amp;id=<?=(int)$row['id']?>&amp;document=summary">Profile summary</a><?php if(in_array($role,['super_admin','clinic_admin','dentist','dental_assistant'],true)):?><a target="_blank" href="print_record.php?type=patient_summary&amp;id=<?=(int)$row['id']?>&amp;document=complete">Complete record</a><?php endif;?><?php if(in_array($role,['super_admin','clinic_admin','dentist','dental_assistant'],true)):?><a target="_blank" href="print_record.php?type=patient_summary&amp;id=<?=(int)$row['id']?>&amp;document=medical">Dental safety history</a><?php endif;?><?php if(in_array($role,['super_admin','clinic_admin','cashier','staff'],true)):?><a target="_blank" href="print_record.php?type=patient_summary&amp;id=<?=(int)$row['id']?>&amp;document=ledger">Ledger</a><?php endif;?><?php elseif($category==='appointments'):?><a class="btn primary" target="_blank" href="print_record.php?type=appointment_slip&amp;id=<?=(int)$row['id']?>">Appointment slip</a><?php elseif($category==='encounters'):?><a class="btn primary" target="_blank" href="print_record.php?type=encounter&amp;id=<?=(int)$row['id']?>">Encounter summary</a><?php elseif($category==='plans'):?><a class="btn primary" target="_blank" href="print_record.php?type=treatment_plan&amp;id=<?=(int)$row['id']?>">Treatment plan</a><?php elseif($category==='prescriptions'):?><a class="btn primary" target="_blank" href="print_record.php?type=prescription&amp;id=<?=(int)$row['id']?>">Prescription</a><?php else:?><a target="_blank" href="print_record.php?type=invoice&amp;id=<?=(int)$row['id']?>">Invoice</a><a target="_blank" href="print_record.php?type=receipt&amp;id=<?=(int)$row['id']?>">Receipt</a><?php endif;?></div></td></tr><?php endforeach;if(!$rows):?><tr><td colspan="3" class="muted">No records match the search.</td></tr><?php endif;?></tbody></table></div><?php module_render_server_pagination($total,$page,$perPage,'page','per_page','print-records');?></div>
<?php endif; ?>

<?php if($category!=='activity'): ?><div class="print-category-grid"><?php if(in_array($role,['super_admin','clinic_admin','dentist','dental_assistant'],true)):?><section class="card"><h2>Daily schedules</h2><form action="print_record.php" method="get" target="_blank" class="form-grid"><input type="hidden" name="type" value="appointment_schedule"><label>Date<input type="date" name="date" value="<?=e(date('Y-m-d'))?>" required></label><button class="btn ghost">Print daily schedule</button></form></section><?php endif;?><?php if(in_array($role,['super_admin','clinic_admin','inventory_officer'],true)):?><section class="card"><h2>Inventory and sterilization</h2><div class="quick-actions"><a target="_blank" href="print_record.php?type=inventory_stock">Current Stock Report</a><a target="_blank" href="print_record.php?type=inventory_expiry">Lot and Expiration Report</a><a target="_blank" href="print_record.php?type=sterilization_log&amp;date=<?=e(date('Y-m-d'))?>">Sterilization Log</a></div></section><?php endif;?><?php if(in_array($role,['super_admin','clinic_admin'],true)):?><section class="card"><h2>Administrative reports</h2><div class="quick-actions"><a target="_blank" href="print_record.php?type=audit_log&amp;date=<?=e(date('Y-m-d'))?>">Daily Audit Log</a><a target="_blank" href="print_record.php?type=collection_report&amp;date=<?=e(date('Y-m-d'))?>">Daily Collection Report</a></div></section><?php endif;?></div><?php endif; ?>
<?php render_footer();
