<?php

declare(strict_types=1);

$options = getopt('', ['target::']);
$root = rtrim((string)($options['target'] ?? dirname(__DIR__)), "\\/");
$checks = [];
$failures = [];
$check = static function (bool $ok, string $code) use (&$checks, &$failures): void {
    $checks[] = $code;
    if (!$ok) { $failures[] = $code; }
};
$read = static function (string $relative) use ($root): string {
    $path = $root . DIRECTORY_SEPARATOR . str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $relative);
    return is_file($path) ? (string)file_get_contents($path) : '';
};

$files = [
    'app/Services/DiarWorkspaceNavigation.php',
    'app/Controllers/DiarWorkspaceController.php',
    'app/Controllers/DiarExecutiveOverviewController.php',
    'app/Views/layouts/main.php',
    'app/Views/diar_workspace/portal.php',
    'app/Views/diar_workspace/module.php',
    'app/Views/diar_command_center/executive_overview.php',
    'app/Views/diar_command_center/cases.php',
    'app/Views/diar_command_center/_tabs.php',
    'public/assets/css/diar-premium-shell.css',
    'public/assets/css/diar-workspace.css',
    'public/assets/css/diar-executive-overview.css',
    'public/assets/js/diar-premium-executive.js',
];
foreach ($files as $file) {
    $check(is_file($root . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $file)), 'FILE_' . strtoupper(str_replace(['/', '.', '-'], '_', $file)));
}

$service = $read('app/Services/DiarWorkspaceNavigation.php');
$layout = $read('app/Views/layouts/main.php');
$portal = $read('app/Views/diar_workspace/portal.php');
$module = $read('app/Views/diar_workspace/module.php');
$executive = $read('app/Views/diar_command_center/executive_overview.php');
$cases = $read('app/Views/diar_command_center/cases.php');
$tabs = $read('app/Views/diar_command_center/_tabs.php');
$premiumCss = $read('public/assets/css/diar-premium-shell.css');
$workspaceCss = $read('public/assets/css/diar-workspace.css');
$executiveCss = $read('public/assets/css/diar-executive-overview.css');
$executiveJs = $read('public/assets/js/diar-premium-executive.js');
$execRepo = $read('app/Repositories/DiarExecutiveOverviewRepository.php');
$casesRepo = $read('app/Repositories/DiarCasesRepository.php');

$check(substr_count($service, "'number' =>") === 6, 'SIX_MODULE_DEFINITIONS');
$check(substr_count($service, "'code' => 'DIAR_") === 6, 'SIX_ROLE_TEMPLATES');
$check(substr_count($service, "'code' => '") >= 19, 'REPORT_AND_MATRIX_CATALOGUES');
$check(strpos($service, 'public static function sidebarItems') !== false, 'ROLE_AWARE_SIDEBAR_SERVICE');
$check(strpos($service, 'public static function accessMatrixRoles') !== false, 'SEVEN_ROLE_ACCESS_MATRIX_SERVICE');
$check(substr_count($service, "'code' => 'ADMIN'") === 1, 'SYSTEM_ADMIN_DISPLAY_ROLE');
$check(strpos($service, 'public static function isPremiumPage') !== false, 'PREMIUM_PAGE_BOUNDARY');

$check(strpos($layout, 'DIAR_6B_2_R3_1_ROLE_AWARE_SIDEBAR') !== false, 'LAYOUT_ROLE_SIDEBAR_MARKER');
$check(strpos($layout, 'DIAR_6B_2_R3_1_PREMIUM_SHELL_CSS') !== false, 'LAYOUT_PREMIUM_CSS_MARKER');
$check(strpos($layout, 'elite-topbar--diar-premium') !== false, 'COMPACT_DIAR_TOPBAR');
$check(strpos($layout, '\'pages\' => $diarSidebarPages') !== false, 'SIDEBAR_GROUP_DYNAMIC_PAGES');
$check(strpos($layout, '\'active_pages\' => $diarActivePages') !== false, 'SIDEBAR_GROUP_DYNAMIC_ACTIVE');

foreach ([$portal, $module, $executive, $cases] as $viewText) {
    $check(strpos($viewText, "require __DIR__ . '/_tabs.php'") === false && strpos($viewText, "require dirname(__DIR__) . '/diar_command_center/_tabs.php'") === false, 'NO_HORIZONTAL_TABS_' . count($checks));
}
$check(strpos($tabs, 'DIAR_6B_2_R3_1_NO_HORIZONTAL_TABS') !== false, 'LEGACY_TAB_SUPPRESSION');
$check(strpos($portal, 'diar-premium-module-grid') !== false, 'PREMIUM_PORTAL_MODULE_CARDS');
$check(strpos($portal, 'diar-access-matrix') !== false, 'PORTAL_ROLE_MATRIX');
$check(strpos($portal, 'showRoleMatrix') !== false, 'ROLE_MATRIX_ADMIN_BOUNDARY');
$check(strpos($executive, 'executive-kpi-strip') !== false, 'EXECUTIVE_KPI_STRIP');
$check(strpos($executive, 'decision-highlights-card') !== false, 'DECISION_HIGHLIGHTS');
$check(strpos($executive, 'priority-chart-card') !== false, 'PRIORITY_CHART');
$check(strpos($executive, 'readiness-card') !== false, 'HOSPITAL_READINESS');
$check(strpos($executive, 'daily-trend-card') !== false, 'DAILY_TREND');
$check(strpos($executive, 'decision-agenda-card') !== false, 'DECISION_AGENDA');
$check(strpos($executive, 'not confirmed financial loss') !== false || strpos($executive, 'ليست خسارة مالية مثبتة') !== false, 'LOSS_INTERPRETATION_BOUNDARY');
$check(strpos($executive, 'diar-executive-chart-data') !== false, 'CHART_DATA_BINDING');
$check(strpos($executiveJs, 'window.echarts.init') !== false, 'ECHARTS_RENDERING');
$check(strpos($executiveJs, 'renderPriority') !== false && strpos($executiveJs, 'renderTrend') !== false, 'TWO_EXECUTIVE_CHARTS');
$check(strpos($premiumCss, '.elite-topbar--diar-premium') !== false, 'PREMIUM_GLOBAL_SHELL');
$check(strpos($workspaceCss, '.diar-premium-module-grid') !== false, 'PREMIUM_PORTAL_CSS');
$check(strpos($executiveCss, '.executive-dashboard-grid') !== false, 'PREMIUM_EXECUTIVE_CSS');
$check(substr_count($premiumCss . $workspaceCss . $executiveCss, '@media') >= 8, 'RESPONSIVE_BREAKPOINTS');
$check(strpos($cases, 'DIAR_6B_2_R3_1_SIDEBAR_ONLY_NAV') !== false, 'CASES_SIDEBAR_ONLY_NAV');

foreach ([$execRepo, $casesRepo] as $repo) {
    $check(strpos($repo, 'Database::execute(') === false, 'READ_ONLY_NO_EXECUTE_' . count($checks));
    $check(strpos($repo, 'Database::executeTransaction(') === false, 'READ_ONLY_NO_TRANSACTION_' . count($checks));
    $check(!preg_match('/\b(INSERT|UPDATE|DELETE|MERGE|TRUNCATE)\s+(INTO|FROM|TABLE|DASH_)/i', $repo), 'READ_ONLY_NO_DML_' . count($checks));
}
$check(strpos($execRepo, "'database_link' => false") !== false, 'NO_DATABASE_LINK_CONTRACT');
$check(strpos($execRepo, "'primary_baseline_days' => 365") !== false, 'BASELINE_365');
$check(strpos($execRepo, "'excluded_stores' => [56, 57]") !== false, 'EXCLUDED_STORES_56_57');

$lintTargets = array_values(array_filter($files, static function (string $file): bool { return substr($file, -4) === '.php'; }));
foreach ($lintTargets as $relative) {
    $path = $root . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $relative);
    exec(escapeshellarg(PHP_BINARY) . ' -l ' . escapeshellarg($path) . ' 2>&1', $output, $code);
    $check($code === 0, 'PHP_LINT_' . strtoupper(str_replace(['/', '.', '-'], '_', $relative)));
}

if ($failures !== []) {
    fwrite(STDERR, 'DIAR_6B_2_R3_1_STATIC_QA|FAIL|CHECKS=' . count($checks) . '|FAILED=' . implode(',', $failures) . PHP_EOL);
    exit(1);
}

echo 'DIAR_6B_2_R3_1_STATIC_QA|PASS|CHECKS=' . count($checks) . '|SIDEBAR_ITEMS=7|MODULES=6|ACCESS_MATRIX_ROLES=7|CHARTS=2|READ_ONLY=PASS|RESPONSIVE=PASS' . PHP_EOL;
