'Title', 'Description'=>'Details / description', 'Instructions'=>'Instructions', 'Questions'=>'Questions', 'Answers'=>'Answer choices', 'Notes'=>'Notes field', 'Layout'=>'Display / layout', 'Workflow'=>'Workflow / next action', 'Timers'=>'Timers / reminders', 'Other'=>'Other change']; } function PADashReviewRole(string $role): string { return match ($role) { 'PART Admin' => 'Pink Angels Admin', 'Private Investigator' => 'Private Detective', 'PART Tracker User' => 'Tracker User', default => $role, }; } function PADashReviewPlain(string $text): string { $text = preg_replace('/|<\/p>|<\/div>|<\/li>/i', "\n", $text) ?? $text; return trim(html_entity_decode(strip_tags($text), ENT_QUOTES | ENT_HTML5, 'UTF-8')); } function PADashReviewSample(string $text): string { $values = ['TRACKERUSERFIRST'=>'Jordan', 'TRACKERUSERLAST'=>'Example', 'TRACKERUSERNAME'=>'Jordan Example', 'TRACKERUSER'=>'Jordan Example', 'TRACKERUSERPHONE'=>'202-555-0140', 'TRACKERUSERADDRESS'=>'123 Example Street, Example City, TX', 'TRACKERUSERADDRESSSTATE'=>'TX', 'TRACKERUSERLASTGPS'=>'29.4241, -98.4936 (fictional sample)', 'TRACKERUSERLASTALERTTIME'=>'2026-10-11 12:00:00 UTC (sample)', 'TRACKERUSERPROFILEPICTURE'=>'[Tracker user photo]', 'TRACKERUSERCURRENTMAP'=>'[Location map]', 'PIFIRSTNAME'=>'Alex', 'PILASTNAME'=>'Example', 'PIPHONE'=>'202-555-0141', 'PIEMAIL'=>'detective@example.invalid', 'PAFIRSTNAME'=>'Case', 'PALASTNAME'=>'Admin', 'PCFIRSTNAME'=>'Taylor', 'PCLASTNAME'=>'Example', 'SCFIRSTNAME'=>'Sam', 'SCLASTNAME'=>'Example', 'ECFIRSTNAME'=>'Taylor', 'ECLASTNAME'=>'Example', 'ECPHONE'=>'202-555-0142', 'PCPHONE'=>'202-555-0142', 'SCPHONE'=>'202-555-0143', 'PAPHONEPISERVICE'=>'202-555-0144', 'PAPHONECUSTOMERSERVICE'=>'202-555-0144', 'CASEID'=>'999', 'CASENAME'=>'PA-20261011-0000999', 'ALERTSOURCE'=>'Tracker Button', 'LASTPAKIDNAPNOTEPRIVATEPI'=>'Sample Admin instructions will appear here.', 'LASTECKIDNAPINFO'=>'Sample family information will appear here.', 'RESOLUTION'=>'Sample resolution', 'STATUS_MESSAGE'=>'Sample case update']; $replace = static function (array $match) use ($values): string { $key = strtoupper($match[1]); if (isset($values[$key])) return $values[$key]; if (str_contains($key, 'EMAIL')) return 'contact@example.invalid'; if (str_contains($key, 'PHONE')) return '202-555-0144'; if (str_contains($key, 'NAME')) return 'Alex Example'; if (str_contains($key, 'URL') || str_contains($key, 'MAP')) return '[Sample link]'; return '[Sample ' . strtolower(str_replace('_', ' ', $key)) . ']'; }; $text = preg_replace_callback('/\{\{\s*([A-Za-z0-9_]+)\s*\}\}/', $replace, $text) ?? $text; return preg_replace_callback('/\*\|([A-Za-z0-9_]+)\|\*/', $replace, $text) ?? $text; } function PADashReviewVersion(array $entry): string { return hash('sha256', json_encode($entry['source'], JSON_THROW_ON_ERROR)); } function PADashReviewInventory(PDO $db): array { $templates = $db->query('SELECT * FROM PART_DashStepTemplates WHERE RecordStatus=0 ORDER BY DashStepTemplateID')->fetchAll(PDO::FETCH_ASSOC); $questions = $db->query('SELECT * FROM PART_DashStepQuestions WHERE RecordStatus=0 ORDER BY DashStepTemplateID,SortOrder,DashStepQuestionID')->fetchAll(PDO::FETCH_ASSOC); $answers = $db->query('SELECT * FROM PART_DashStepAnswers WHERE RecordStatus=0 ORDER BY DashStepQuestionID,SortOrder,DashStepAnswerID')->fetchAll(PDO::FETCH_ASSOC); $mappings = $db->query('SELECT * FROM PART_DashStepsMapping WHERE RecordStatus=0 ORDER BY DashStepTemplateID,DashStepsMappingID')->fetchAll(PDO::FETCH_ASSOC); $emails = $db->query('SELECT EmailTemplateID,DashStepTemplateID,RecipientUserType FROM PART_DashStepEmailTemplates WHERE RecordStatus=0 ORDER BY EmailTemplateID')->fetchAll(PDO::FETCH_ASSOC); $sms = $db->query('SELECT SMSTemplateID,DashStepTemplateID,RecipientUserType FROM PART_DashStepSMSTemplates WHERE RecordStatus=0 ORDER BY SMSTemplateID')->fetchAll(PDO::FETCH_ASSOC); $clean = static function (array $row): array { unset($row['Insert_DateTime'], $row['Update_DateTime']); return $row; }; $form = __DIR__ . '/PA_WEB_FORM_ADMIN_DASHSTEP_RECORD_FORM.php'; $formHash = is_file($form) ? hash_file('sha256', $form) : null; $result = []; $titles = array_column($templates, 'Title', 'DashStepTemplateID'); foreach ($templates as $template) { $id = (int)$template['DashStepTemplateID']; $stepQuestions = []; foreach ($questions as $question) { if ((int)$question['DashStepTemplateID'] !== $id) continue; $question['answers'] = array_map($clean, array_values(array_filter($answers, static fn($answer) => (int)$answer['DashStepQuestionID'] === (int)$question['DashStepQuestionID']))); $stepQuestions[] = $clean($question); } $stepMappings = array_map($clean, array_values(array_filter($mappings, static fn($row) => (int)$row['DashStepTemplateID'] === $id))); $stepEmails = array_values(array_filter($emails, static fn($row) => (int)$row['DashStepTemplateID'] === $id)); $stepSMS = array_values(array_filter($sms, static fn($row) => (int)$row['DashStepTemplateID'] === $id)); $result[$id] = ['id'=>$id, 'title'=>(string)$template['Title'], 'role'=>PADashReviewRole($template['DashStepUserType']), 'info'=>(bool)$template['AutoComplete'], 'questions'=>$stepQuestions, 'source'=>['template'=>$clean($template), 'questions'=>$stepQuestions, 'mappings'=>$stepMappings, 'emailReferences'=>$stepEmails, 'smsReferences'=>$stepSMS, 'adminFormHash'=>$formHash], 'priority'=>in_array($id, [1,5,6,8,7,11,21], true) ? 1 : ((bool)$template['AutoComplete'] ? 3 : 2), 'nextTitles'=>$titles]; } return $result; } function PADashReviewSync(PDO $db, array $entries): void { if (!$entries) return; $values = []; $params = []; foreach ($entries as $entry) { $values[] = '(?,?)'; array_push($params, $entry['id'], PADashReviewVersion($entry)); } $db->prepare('INSERT INTO PART_DashStepReview (DashStepTemplateID,CurrentHash) VALUES ' . implode(',', $values) . ' ON DUPLICATE KEY UPDATE CurrentHash=VALUES(CurrentHash)')->execute($params); } function PADashReviewString(array $post, string $key, int $max, bool $required = false): string { if (!is_string($post[$key] ?? '')) throw new DomainException('Invalid review field: ' . $key); $value = trim($post[$key] ?? ''); if (($required && $value === '') || mb_strlen($value, 'UTF-8') > $max) { throw new DomainException('Enter valid review details within the field length limits.'); } return $value; } function PADashReviewAction(PDO $db, array $post, int $adminID, string $sessionID): array { if ($adminID < 1 || $sessionID === '' || !is_string($post['csrf'] ?? null) || !hash_equals(hash('sha256', 'dash-review:' . $sessionID), $post['csrf'])) { throw new DomainException('Your session needs a refresh before saving.'); } $id = filter_var($post['template'] ?? null, FILTER_VALIDATE_INT); if (!$id || $id < 1) throw new DomainException('Choose a valid DashStep.'); $version = PADashReviewString($post, 'version', 64, true); $action = PADashReviewString($post, 'action', 32, true); $db->beginTransaction(); try { $stmt = $db->prepare('SELECT CurrentHash,AcceptedHash FROM PART_DashStepReview WHERE DashStepTemplateID=? FOR UPDATE'); $stmt->execute([$id]); $review = $stmt->fetch(PDO::FETCH_ASSOC); $entry = PADashReviewInventory($db)[$id] ?? null; if (!$review || !$entry || !hash_equals($review['CurrentHash'], $version) || !hash_equals(PADashReviewVersion($entry), $version)) { throw new DomainException('This DashStep changed since the page loaded. Refresh and review the current version.'); } $accepted = $review['AcceptedHash'] !== null && hash_equals($review['CurrentHash'], $review['AcceptedHash']); $changeID = null; $details = ['step_title'=>$entry['title'], 'role'=>$entry['role']]; if ($action === 'add') { if ($accepted) throw new DomainException('Reopen this accepted DashStep before adding changes.'); $area = PADashReviewString($post, 'area', 32, true); if (!isset(PADashReviewAreas()[$area])) throw new DomainException('Choose a change area.'); $reference = PADashReviewString($post, 'step_reference', 255); $current = PADashReviewString($post, 'current_text', 4000); $requested = PADashReviewString($post, 'requested_change', 8000, true); $db->prepare('INSERT INTO PART_DashStepReviewChange (DashStepTemplateID,Area,StepReference,CurrentText,RequestedChange,SourceHash,CreatedByAdminID) VALUES (?,?,?,?,?,?,?)') ->execute([$id,$area,$reference,$current,$requested,$version,$adminID]); $changeID = (int)$db->lastInsertId(); $details += ['area'=>$area,'reference'=>$reference,'current_text'=>$current,'requested_change'=>$requested]; } elseif (in_array($action, ['complete','reopen_change','withdraw'], true)) { if ($accepted) throw new DomainException('Reopen this accepted DashStep before changing its requests.'); $changeID = filter_var($post['change_id'] ?? null, FILTER_VALIDATE_INT); if (!$changeID || $changeID < 1) throw new DomainException('Choose a valid change request.'); $stmt = $db->prepare('SELECT Status FROM PART_DashStepReviewChange WHERE ReviewChangeID=? AND DashStepTemplateID=? FOR UPDATE'); $stmt->execute([$changeID,$id]); $status = $stmt->fetchColumn(); $newStatus = match ($action) {'complete'=>'Completed','reopen_change'=>'Open','withdraw'=>'Withdrawn'}; if (!(($status === 'Open' && in_array($action,['complete','withdraw'],true)) || ($status === 'Completed' && $action === 'reopen_change'))) { throw new DomainException('That change is unavailable or has moved to another state. Refresh the page.'); } $db->prepare('UPDATE PART_DashStepReviewChange SET Status=?,CompletedByAdminID=?,CompletedAt=IF(?=1,NOW(),NULL) WHERE ReviewChangeID=? AND DashStepTemplateID=?') ->execute([$newStatus,$action === 'complete' ? $adminID : null,$action === 'complete' ? 1 : 0,$changeID,$id]); $details += ['before_status'=>$status,'after_status'=>$newStatus]; } elseif ($action === 'accept') { if ($accepted) throw new DomainException('This DashStep is already accepted.'); $stmt = $db->prepare("SELECT COUNT(*) FROM PART_DashStepReviewChange WHERE DashStepTemplateID=? AND Status='Open'"); $stmt->execute([$id]); if ((int)$stmt->fetchColumn() > 0) throw new DomainException('Complete or withdraw every open change before acceptance.'); $db->prepare('UPDATE PART_DashStepReview SET AcceptedHash=CurrentHash,AcceptedByAdminID=?,AcceptedAt=NOW() WHERE DashStepTemplateID=?') ->execute([$adminID,$id]); } elseif ($action === 'reopen_template') { if (!$accepted) throw new DomainException('This DashStep is already awaiting review.'); $db->prepare('UPDATE PART_DashStepReview SET AcceptedHash=NULL,AcceptedByAdminID=NULL,AcceptedAt=NULL WHERE DashStepTemplateID=?')->execute([$id]); } else { throw new DomainException('Unknown review action.'); } $db->prepare('INSERT INTO PART_DashStepReviewActivity (DashStepTemplateID,ReviewChangeID,Action,AdminID,SourceHash,DetailsJSON) VALUES (?,?,?,?,?,?)') ->execute([$id,$changeID,$action,$adminID,$version,json_encode($details,JSON_THROW_ON_ERROR)]); $db->commit(); return ['id'=>$id,'action'=>$action]; } catch (Throwable $error) { if ($db->inTransaction()) $db->rollBack(); throw $error; } } function PADashReviewState(array $entries, array $reviews, array $changes): array { $groups = ['review'=>[], 'accepted'=>[]]; $openCounts = []; $updated = []; $totalOpen = 0; foreach ($entries as $id => $entry) { $row = $reviews[$id] ?? null; if (!$row) continue; $openCounts[$id] = count(array_filter($changes[$id] ?? [], static fn($change) => $change['Status'] === 'Open')); $totalOpen += $openCounts[$id]; $updated[$id] = $row['AcceptedHash'] !== null && !hash_equals($row['CurrentHash'], $row['AcceptedHash']); $accepted = $row['AcceptedHash'] !== null && hash_equals($row['CurrentHash'], $row['AcceptedHash']) && !$openCounts[$id]; $groups[$accepted ? 'accepted' : 'review'][] = $id; } foreach ($groups as &$ids) { usort($ids, static function ($a,$b) use ($entries,$openCounts,$updated): int { $aState = $openCounts[$a] ? 0 : ($updated[$a] ? 1 : 2); $bState = $openCounts[$b] ? 0 : ($updated[$b] ? 1 : 2); return ($aState <=> $bState) ?: ($entries[$a]['priority'] <=> $entries[$b]['priority']) ?: ($openCounts[$b] <=> $openCounts[$a]) ?: ($a <=> $b); }); } unset($ids); $total = count($groups['review']) + count($groups['accepted']); return ['groups'=>$groups,'openCounts'=>$openCounts,'updated'=>$updated,'totalOpen'=>$totalOpen, 'total'=>$total,'percent'=>$total ? (int)round(count($groups['accepted']) * 100 / $total) : 0]; }