<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
require DENTAL_ROOT . '/app/layout.php';
require DENTAL_ROOT . '/app/module_helpers.php';
require_once DENTAL_ROOT . '/app/help_support.php';

$pdo = db();
$user = current_user() ?? [];
$userId = (int)($user['id'] ?? 0);
$actualRole = actual_role();
$role = active_role();
$isAdmin = in_array($actualRole, ['super_admin','clinic_admin'], true);
$branchId = $actualRole === 'super_admin' ? max(0, (int)($_GET['branch_id'] ?? $_POST['branch_id'] ?? 0)) : signed_user_branch_id();
$requestedRoute = strtolower(trim((string)($_GET['from'] ?? $_POST['page_route'] ?? 'dashboard')));
if (!preg_match('/^[a-z0-9_-]{1,64}$/', $requestedRoute)) $requestedRoute = 'dashboard';
$context = help_support_context($requestedRoute, $role);
$clinic = public_clinic_profile();
$schemaReady = help_support_schema_ready();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    try {
        if (!$schemaReady) throw new RuntimeException('The Help & Support database update is pending. Ask the Superuser to apply Version 0.5.9.8.30.');
        $action = (string)($_POST['action'] ?? '');
        if ($action === 'create_request') {
            $category = (string)($_POST['category'] ?? 'workflow');
            if (!array_key_exists($category, help_support_categories())) $category = 'other';
            $priority = (string)($_POST['priority'] ?? 'normal');
            if (!in_array($priority, ['low','normal','high','urgent'], true)) $priority = 'normal';
            $subject = trim((string)($_POST['subject'] ?? ''));
            $message = trim((string)($_POST['message'] ?? ''));
            $errorReference = strtoupper(trim((string)($_POST['error_reference'] ?? '')));
            $pageRoute = strtolower(trim((string)($_POST['page_route'] ?? $requestedRoute)));
            if (!preg_match('/^[a-z0-9_-]{1,64}$/', $pageRoute)) $pageRoute = 'dashboard';
            if (mb_strlen($subject) < 5 || mb_strlen($subject) > 180) throw new RuntimeException('Enter a support subject between 5 and 180 characters.');
            if (mb_strlen($message) < 10 || mb_strlen($message) > 5000) throw new RuntimeException('Describe the issue in 10 to 5,000 characters.');
            if (mb_strlen($errorReference) > 100) throw new RuntimeException('The error reference is too long.');
            $requestBranchId = signed_user_branch_id();
            if ($actualRole === 'super_admin') $requestBranchId = max(0, (int)($_POST['request_branch_id'] ?? $branchId));
            $pageUrl = $pageRoute . '.php';
            $contextJson = json_encode([
                'release_version' => app_release_version(),
                'installed_version' => installed_application_version(),
                'actual_role' => $actualRole,
                'active_role' => $role,
                'branch_id' => $requestBranchId,
                'user_agent' => mb_substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 500),
                'submitted_at' => date(DATE_ATOM),
            ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            $stmt = $pdo->prepare(
                'INSERT INTO `' . table('support_requests') . '` '
                . '(branch_id,user_id,category,priority,subject,message,page_route,page_url,error_reference,context_json,status,created_at,updated_at) '
                . 'VALUES (?,?,?,?,?,?,?,?,?,?,"open",NOW(),NOW())'
            );
            $stmt->execute([
                $requestBranchId > 0 ? $requestBranchId : null,
                $userId,
                $category,
                $priority,
                $subject,
                $message,
                $pageRoute,
                $pageUrl,
                $errorReference !== '' ? $errorReference : null,
                $contextJson,
            ]);
            $requestId = (int)$pdo->lastInsertId();
            audit('support_request_created','support_request',$requestId,[
                'category'=>$category,'priority'=>$priority,'page_route'=>$pageRoute,'branch_id'=>$requestBranchId,
            ]);
            flash('success','Support request ' . help_support_reference($requestId) . ' was submitted.');
            header('Location: help_support.php?from=' . rawurlencode($pageRoute) . '&request=' . $requestId);
            exit;
        }
        if ($action === 'update_request') {
            if (!$isAdmin) throw new RuntimeException('Only an Administrator can update support requests.');
            $requestId = (int)($_POST['request_id'] ?? 0);
            $status = (string)($_POST['status'] ?? 'in_review');
            if (!in_array($status, ['open','in_review','waiting_user','resolved','closed'], true)) throw new RuntimeException('Select a valid support status.');
            $assignedTo = max(0, (int)($_POST['assigned_to_user_id'] ?? 0));
            $resolution = trim((string)($_POST['resolution_note'] ?? ''));
            if (in_array($status, ['resolved','closed'], true) && mb_strlen($resolution) < 5) throw new RuntimeException('Record a resolution note before resolving or closing the request.');
            $where = 'id=?';
            $args = [$requestId];
            if ($actualRole !== 'super_admin' && $branchId > 0) { $where .= ' AND branch_id=?'; $args[] = $branchId; }
            $check = $pdo->prepare('SELECT id,status FROM `' . table('support_requests') . '` WHERE ' . $where . ' LIMIT 1');
            $check->execute($args);
            $existing = $check->fetch();
            if (!$existing) throw new RuntimeException('Support request not found in your branch scope.');
            if ($assignedTo > 0) {
                $staffSql = 'SELECT u.id FROM `' . table('users') . '` u JOIN `' . table('roles') . '` r ON r.id=u.role_id WHERE u.id=? AND u.status="active" AND r.code IN ("super_admin","clinic_admin")';
                $staffArgs = [$assignedTo];
                if ($actualRole !== 'super_admin' && $branchId > 0) {
                    $staffSql .= ' AND (r.code="super_admin" OR u.branch_id=?)';
                    $staffArgs[] = $branchId;
                }
                $staffSql .= ' LIMIT 1';
                $staffCheck = $pdo->prepare($staffSql);
                $staffCheck->execute($staffArgs);
                if (!$staffCheck->fetchColumn()) throw new RuntimeException('Select an active Administrator or Superuser within your support scope.');
            }
            $updateSql = 'UPDATE `' . table('support_requests') . '` SET status=?,assigned_to_user_id=?,resolution_note=?,resolved_at=' . (in_array($status,['resolved','closed'],true) ? 'NOW()' : 'NULL') . ',updated_at=NOW() WHERE id=?';
            $updateArgs = [$status,$assignedTo > 0 ? $assignedTo : null,$resolution !== '' ? $resolution : null,$requestId];
            if ($actualRole !== 'super_admin' && $branchId > 0) { $updateSql .= ' AND branch_id=?'; $updateArgs[] = $branchId; }
            $update = $pdo->prepare($updateSql);
            $update->execute($updateArgs);
            audit('support_request_updated','support_request',$requestId,[
                'previous_status'=>(string)$existing['status'],'status'=>$status,'assigned_to_user_id'=>$assignedTo ?: null,
            ]);
            flash('success','Support request ' . help_support_reference($requestId) . ' was updated.');
            header('Location: help_support.php?from=' . rawurlencode($requestedRoute) . '&request=' . $requestId);
            exit;
        }
        throw new RuntimeException('Unsupported support action.');
    } catch (Throwable $exception) {
        error_log('DentalCare Help & Support action failed: ' . $exception);
        flash('error',$exception->getMessage());
    }
}

$q = trim((string)($_GET['q'] ?? ''));
$statusFilter = trim((string)($_GET['status'] ?? ''));
$categoryFilter = trim((string)($_GET['category'] ?? ''));
if (!in_array($statusFilter, ['','open','in_review','waiting_user','resolved','closed'], true)) $statusFilter = '';
if ($categoryFilter !== '' && !array_key_exists($categoryFilter, help_support_categories())) $categoryFilter = '';
$page = module_page_number();
$perPage = module_page_size('per_page',20);
$total = 0;
$requests = [];
$selected = null;
$supportStaff = [];

if ($schemaReady) {
    $where = [];
    $args = [];
    if (!$isAdmin) {
        $where[] = 'sr.user_id=?';
        $args[] = $userId;
    } elseif ($actualRole !== 'super_admin' && $branchId > 0) {
        $where[] = 'sr.branch_id=?';
        $args[] = $branchId;
    } elseif ($actualRole === 'super_admin' && $branchId > 0) {
        $where[] = 'sr.branch_id=?';
        $args[] = $branchId;
    }
    if ($statusFilter !== '') { $where[] = 'sr.status=?'; $args[] = $statusFilter; }
    if ($categoryFilter !== '') { $where[] = 'sr.category=?'; $args[] = $categoryFilter; }
    if ($q !== '') {
        $like = '%' . $q . '%';
        $where[] = '(sr.subject LIKE ? OR sr.message LIKE ? OR sr.error_reference LIKE ? OR u.name LIKE ? OR u.email LIKE ?)';
        array_push($args,$like,$like,$like,$like,$like);
    }
    $whereSql = $where ? ' WHERE ' . implode(' AND ', $where) : '';
    $fromSql = ' FROM `' . table('support_requests') . '` sr JOIN `' . table('users') . '` u ON u.id=sr.user_id LEFT JOIN `' . table('users') . '` au ON au.id=sr.assigned_to_user_id LEFT JOIN `' . table('branches') . '` b ON b.id=sr.branch_id';
    $countStmt = $pdo->prepare('SELECT COUNT(*)' . $fromSql . $whereSql);
    $countStmt->execute($args);
    $total = (int)$countStmt->fetchColumn();
    $offset = (max(1,$page)-1)*$perPage;
    $stmt = $pdo->prepare('SELECT sr.*,u.name requester_name,u.email requester_email,au.name assigned_to_name,b.name branch_name' . $fromSql . $whereSql . ' ORDER BY FIELD(sr.status,"open","in_review","waiting_user","resolved","closed"),FIELD(sr.priority,"urgent","high","normal","low"),sr.updated_at DESC,sr.id DESC LIMIT ' . $perPage . ' OFFSET ' . $offset);
    $stmt->execute($args);
    $requests = $stmt->fetchAll();

    $selectedId = (int)($_GET['request'] ?? 0);
    if ($selectedId > 0) {
        $selectWhere = ['sr.id=?'];
        $selectArgs = [$selectedId];
        if (!$isAdmin) { $selectWhere[] = 'sr.user_id=?'; $selectArgs[] = $userId; }
        elseif ($actualRole !== 'super_admin' && $branchId > 0) { $selectWhere[] = 'sr.branch_id=?'; $selectArgs[] = $branchId; }
        elseif ($actualRole === 'super_admin' && $branchId > 0) { $selectWhere[] = 'sr.branch_id=?'; $selectArgs[] = $branchId; }
        $selectStmt = $pdo->prepare('SELECT sr.*,u.name requester_name,u.email requester_email,au.name assigned_to_name,b.name branch_name' . $fromSql . ' WHERE ' . implode(' AND ',$selectWhere) . ' LIMIT 1');
        $selectStmt->execute($selectArgs);
        $selected = $selectStmt->fetch() ?: null;
    }

    if ($isAdmin) {
        $staffSql = 'SELECT u.id,u.name,r.name role_name,b.name branch_name FROM `' . table('users') . '` u JOIN `' . table('roles') . '` r ON r.id=u.role_id LEFT JOIN `' . table('branches') . '` b ON b.id=u.branch_id WHERE u.status="active" AND r.code IN ("super_admin","clinic_admin")';
        $staffArgs = [];
        if ($actualRole !== 'super_admin' && $branchId > 0) { $staffSql .= ' AND (u.branch_id=? OR r.code="super_admin")'; $staffArgs[] = $branchId; }
        $staffSql .= ' ORDER BY r.code="super_admin" DESC,u.name';
        $staffStmt = $pdo->prepare($staffSql);$staffStmt->execute($staffArgs);$supportStaff=$staffStmt->fetchAll();
    }
}

$faq = [
    ['Why can I see a page but not complete an action?','Page visibility and action authority are checked separately. The active Task View, signed-in role, branch, clinical assignment, and record status can all limit an action. Open Scope & limits on the dashboard or submit an Access support request with the page and action.'],
    ['Why did a patient disappear from my queue?','Queue panels update automatically and may move the patient to another status column, Dentist, chair, Cashier, or completed list. Search the patient in Patient Journey before creating another queue entry.'],
    ['Why can’t a clinical encounter be finalized?','The responsible Dentist must complete required intake, charting, diagnosis, performed procedures, SOAP documentation, instructions, follow-up, billing review, and verification of any Dental Assistant entries. Use Next required inside the treatment workspace.'],
    ['Why can’t the Cashier open another patient?','An active Cashier transaction intentionally locks focus to one patient. Complete or cancel the current transaction before switching patients.'],
    ['Why is an inventory transaction waiting for approval?','Controlled adjustments, damage, expiry, disposal, and similar stock changes require independent review. Open the original inventory document; the Reconciliation Center does not approve it.'],
    ['What should I include in a technical support request?','Include the page, action you attempted, exact error reference, expected result, and what happened. Do not paste passwords, card details, or unnecessary patient clinical information.'],
];

render_header('Help & Support');
?>
<section class="help-hero card">
    <div><span class="eyebrow">Help & Support</span><h2>Get guidance without leaving the workflow unclear.</h2><p>Page help follows the active Task View. Support requests automatically include the release, role, branch, and page context without storing passwords or form contents.</p></div>
    <div class="help-system-context"><span>Release</span><strong><?=e(app_release_version())?></strong><span>Task View</span><strong><?=e((string)$context['role_label'])?></strong><span>Page</span><strong><?=e((string)$context['title'])?></strong></div>
</section>

<?php if(!$schemaReady):?>
<div class="alert warning"><strong>Help articles are available, but support requests are not yet enabled.</strong> The Superuser must apply Version 0.5.9.8.30 from Updates & Database.</div>
<?php endif;?>

<div class="help-layout">
    <main class="help-main">
        <section class="card contextual-help-card">
            <div class="card-head"><div><span class="eyebrow">Current page guide</span><h2><?=e((string)$context['title'])?></h2></div><span class="badge"><?=e((string)$context['role_label'])?></span></div>
            <p class="help-summary"><?=e((string)$context['summary'])?></p>
            <div class="help-action-list"><?php foreach((array)$context['actions'] as $index=>$action):?><div><span><?=($index+1)?></span><p><?=e((string)$action)?></p></div><?php endforeach;?></div>
            <?php if(!empty($context['tips'])):?><div class="help-tip-list"><?php foreach((array)$context['tips'] as $tip):?><span><?=dental_icon('check')?> <?=e((string)$tip)?></span><?php endforeach;?></div><?php endif;?>
        </section>

        <section class="card role-help-card">
            <div class="card-head"><div><span class="eyebrow">Role guide</span><h2><?=e((string)$context['role_label'])?> responsibilities</h2></div><button class="btn ghost compact" type="button" data-open="role-scope-dialog">View scope & limits</button></div>
            <p><?=e((string)$context['role_purpose'])?></p>
            <ol class="task-steps compact-task-steps"><?php foreach((array)$context['role_steps'] as $step):?><li><?=e((string)$step)?></li><?php endforeach;?></ol>
        </section>

        <section class="card faq-card">
            <div class="card-head"><div><span class="eyebrow">Common questions</span><h2>Quick answers</h2></div></div>
            <div class="help-faq-list"><?php foreach($faq as [$question,$answer]):?><details><summary><?=e($question)?></summary><p><?=e($answer)?></p></details><?php endforeach;?></div>
        </section>

        <section class="card support-request-list">
            <div class="card-head"><div><span class="eyebrow"><?=$isAdmin?'Support queue':'My requests'?></span><h2><?=$isAdmin?'Staff support requests':'Support request history'?></h2></div><?php if($schemaReady):?><button class="btn primary" type="button" data-open="new-support-request">New support request</button><?php endif;?></div>
            <?php if($schemaReady):?>
            <form method="get" class="support-filter-toolbar" data-auto-submit><input type="hidden" name="from" value="<?=e($requestedRoute)?>"><label>Search<input type="search" name="q" value="<?=e($q)?>" placeholder="Reference, subject, requester, or error" data-auto-search data-min-length="2"></label><label>Status<select name="status"><option value="">All statuses</option><?php foreach(['open','in_review','waiting_user','resolved','closed'] as $status):?><option value="<?=$status?>" <?=$statusFilter===$status?'selected':''?>><?=e(help_support_status_label($status))?></option><?php endforeach;?></select></label><label>Category<select name="category"><option value="">All categories</option><?php foreach(help_support_categories() as $key=>$label):?><option value="<?=e($key)?>" <?=$categoryFilter===$key?'selected':''?>><?=e($label)?></option><?php endforeach;?></select></label><label>Items per page<select name="per_page"><?php foreach([10,20,50] as $size):?><option value="<?=$size?>" <?=$perPage===$size?'selected':''?>><?=$size?></option><?php endforeach;?></select></label><?php if($q!==''||$statusFilter!==''||$categoryFilter!==''):?><a class="btn ghost compact" href="help_support.php?from=<?=rawurlencode($requestedRoute)?>">Clear</a><?php endif;?></form>
            <?php module_render_server_pagination($total,$page,$perPage,'page','per_page','requests'); ?>
            <div class="table-wrap"><table class="support-request-table"><thead><tr><th>Reference</th><?php if($isAdmin):?><th>Requester</th><?php endif;?><th>Subject</th><th>Priority</th><th>Status</th><th>Updated</th><th></th></tr></thead><tbody><?php foreach($requests as $request):?><tr><td><strong><?=e(help_support_reference((int)$request['id']))?></strong><small><?=e((string)($request['branch_name']??'All branches'))?></small></td><?php if($isAdmin):?><td><?=e((string)$request['requester_name'])?><small><?=e((string)$request['requester_email'])?></small></td><?php endif;?><td><strong><?=e((string)$request['subject'])?></strong><small><?=e((string)(help_support_categories()[$request['category']]??$request['category']))?> · <?=e(ucwords(str_replace('_',' ',(string)$request['page_route'])))?></small></td><td><span class="badge support-priority-<?=e((string)$request['priority'])?>"><?=e(help_support_priority_label((string)$request['priority']))?></span></td><td><span class="badge support-status-<?=e((string)$request['status'])?>"><?=e(help_support_status_label((string)$request['status']))?></span><?php if(!empty($request['assigned_to_name'])):?><small><?=e((string)$request['assigned_to_name'])?></small><?php endif;?></td><td><?=e(date('M j, Y',strtotime((string)$request['updated_at'])))?><small><?=e(date('g:i A',strtotime((string)$request['updated_at'])))?></small></td><td><a href="help_support.php?from=<?=rawurlencode($requestedRoute)?>&request=<?=(int)$request['id']?>">Open</a></td></tr><?php endforeach;?><?php if(!$requests):?><tr><td colspan="<?=$isAdmin?7:6?>" class="muted">No support requests match this view.</td></tr><?php endif;?></tbody></table></div>
            <?php module_render_server_pagination($total,$page,$perPage,'page','per_page','requests'); ?>
            <?php else:?><p class="muted">Support history becomes available after the database update is applied.</p><?php endif;?>
        </section>
    </main>

    <aside class="help-side">
        <section class="card support-contact-card"><span class="eyebrow">Clinic support</span><h2>Contact details</h2><?php if(!empty($clinic['public_email'])||!empty($clinic['email'])):?><a href="mailto:<?=e((string)($clinic['public_email']??$clinic['email']))?>"><?=dental_icon('mail')?> <span><?=e((string)($clinic['public_email']??$clinic['email']))?></span></a><?php endif;?><?php if(!empty($clinic['phone'])):?><a href="tel:<?=e(preg_replace('/[^0-9+]/','',(string)$clinic['phone']))?>"><?=dental_icon('phone')?> <span><?=e((string)$clinic['phone'])?></span></a><?php endif;?><p>For urgent patient-care concerns, follow the clinic’s emergency escalation procedure rather than relying on a software support request.</p></section>
        <section class="card support-safe-report"><span class="eyebrow">Before submitting</span><h2>Safe reporting</h2><ul><li>Include the error reference shown on screen.</li><li>Describe the exact button or action used.</li><li>Do not include passwords or card numbers.</li><li>Use patient numbers only when necessary.</li></ul></section>
        <?php if($isAdmin&&$schemaReady):?><section class="card support-admin-note"><span class="eyebrow">Administrator</span><h2>Support ownership</h2><p>Assign requests to an Administrator or Superuser, update the status, and record the final resolution. All changes remain attributable.</p></section><?php endif;?>
    </aside>
</div>

<dialog id="role-scope-dialog" class="role-guidance-dialog"><div class="dialog-body"><button type="button" class="dialog-close" data-close>×</button><span class="eyebrow"><?=e((string)$context['role_label'])?></span><h2>Scope and limits</h2><p><?=e((string)$context['role_purpose'])?></p><div class="alert"><?=e((string)$context['role_limits'])?></div><?php if(task_preview_mode()):?><p class="muted">Task View changes the operational perspective only. Transactions remain attributed to <?=e((string)($user['name']??'the signed-in user'))?>.</p><?php endif;?></div></dialog>

<?php if($schemaReady):?><dialog id="new-support-request" class="wide-dialog support-request-dialog"><form method="post" class="form-grid"><button type="button" class="dialog-close" data-close>×</button><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="create_request"><input type="hidden" name="page_route" value="<?=e($requestedRoute)?>"><div class="wide"><span class="eyebrow">New support request</span><h2>Tell the clinic support team what happened</h2><p class="muted">System release, role, branch, and browser context are attached automatically. Form contents and passwords are not collected.</p></div><?php if($actualRole==='super_admin'):?><label>Branch ID <input type="number" name="request_branch_id" min="0" value="<?=$branchId?>" placeholder="0 for system-wide"></label><?php endif;?><label>Category<select name="category" required><?php foreach(help_support_categories() as $key=>$label):?><option value="<?=e($key)?>"><?=e($label)?></option><?php endforeach;?></select></label><label>Priority<select name="priority"><option value="normal">Normal</option><option value="high">High</option><option value="urgent">Urgent</option><option value="low">Low</option></select></label><label class="wide">Subject<input name="subject" maxlength="180" required placeholder="Example: Cashier queue does not move after payment"></label><label>Error reference <input name="error_reference" maxlength="100" placeholder="Example: 3077DC90"></label><label>Related page<input value="<?=e((string)$context['title'])?>" readonly></label><label class="wide">What happened?<textarea name="message" minlength="10" maxlength="5000" required placeholder="State what you were trying to do, the exact action taken, what you expected, and what appeared instead."></textarea></label><div class="alert warning wide"><strong>Do not include passwords, card information, or unnecessary clinical details.</strong></div><button class="btn primary wide" type="submit">Submit support request</button></form></dialog><?php endif;?>

<?php if($selected):?><dialog id="support-request-detail" class="management-dialog" data-auto-open-dialog="support-request-detail"><div class="management-dialog-body"><button type="button" class="dialog-close" data-close>×</button><span class="eyebrow"><?=e(help_support_reference((int)$selected['id']))?></span><h2><?=e((string)$selected['subject'])?></h2><div class="management-summary"><div><span>Requester</span><strong><?=e((string)$selected['requester_name'])?></strong></div><div><span>Category</span><strong><?=e((string)(help_support_categories()[$selected['category']]??$selected['category']))?></strong></div><div><span>Priority</span><strong><?=e(help_support_priority_label((string)$selected['priority']))?></strong></div><div><span>Status</span><strong><?=e(help_support_status_label((string)$selected['status']))?></strong></div><div><span>Page</span><strong><?=e(ucwords(str_replace('_',' ',(string)$selected['page_route'])))?></strong></div><div><span>Created</span><strong><?=e(date('M j, Y g:i A',strtotime((string)$selected['created_at'])))?></strong></div></div><?php if(!empty($selected['error_reference'])):?><div class="alert warning"><strong>Error reference:</strong> <?=e((string)$selected['error_reference'])?></div><?php endif;?><div class="support-message-block"><span>Request</span><p><?=nl2br(e((string)$selected['message']))?></p></div><?php if(!empty($selected['resolution_note'])):?><div class="support-message-block resolution"><span>Resolution</span><p><?=nl2br(e((string)$selected['resolution_note']))?></p></div><?php endif;?><?php if($isAdmin):?><form method="post" class="form-grid support-resolution-form"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="update_request"><input type="hidden" name="request_id" value="<?=(int)$selected['id']?>"><input type="hidden" name="page_route" value="<?=e($requestedRoute)?>"><label>Status<select name="status"><?php foreach(['open','in_review','waiting_user','resolved','closed'] as $status):?><option value="<?=$status?>" <?=$selected['status']===$status?'selected':''?>><?=e(help_support_status_label($status))?></option><?php endforeach;?></select></label><label>Assigned to<select name="assigned_to_user_id"><option value="">Unassigned</option><?php foreach($supportStaff as $staff):?><option value="<?=(int)$staff['id']?>" <?=(int)($selected['assigned_to_user_id']??0)===(int)$staff['id']?'selected':''?>><?=e((string)$staff['name'])?> · <?=e((string)$staff['role_name'])?></option><?php endforeach;?></select></label><label class="wide">Resolution or response note<textarea name="resolution_note" placeholder="Record investigation, user instructions, or the final resolution."><?=e((string)($selected['resolution_note']??''))?></textarea></label><button class="btn primary wide">Update support request</button></form><?php endif;?><a class="btn ghost" href="help_support.php?from=<?=rawurlencode($requestedRoute)?>">Close</a></div></dialog><?php endif;?>

<?php render_footer();
