<?php
/**
 * Doctor Profiles — hosting compatibility check (AskTam)
 * Upload this single file to the hosting account and open it in a browser.
 * It writes nothing and changes nothing. Add ?json=1 for machine output.
 */
declare(strict_types=1);
error_reporting(E_ALL);
ini_set('display_errors', '0');

const DP_MIN_PHP   = '8.0.0';
const DP_MIN_MYSQL = '5.7.0';

$R = [];
function chk(string $area, string $name, string $state, string $found = '', string $fix = ''): void {
    $GLOBALS['R'][] = ['area' => $area, 'name' => $name, 'state' => $state, 'found' => $found, 'fix' => $fix];
}
function to_bytes(string $v): int {
    $v = trim($v);
    if ($v === '' || $v === '-1' || $v === '0') return -1;
    $unit = strtolower(substr($v, -1));
    $n = (int) $v;
    if ($unit === 'g') return $n * 1024 * 1024 * 1024;
    if ($unit === 'm') return $n * 1024 * 1024;
    if ($unit === 'k') return $n * 1024;
    return $n;
}

/* ---------- PHP ---------- */
chk('PHP', 'PHP version', version_compare(PHP_VERSION, DP_MIN_PHP, '>=') ? 'pass' : 'fail', PHP_VERSION,
    'Switch the PHP version to 8.0 or newer in the hosting control panel.');
chk('PHP', '64-bit build', PHP_INT_SIZE >= 8 ? 'pass' : 'fail', PHP_INT_SIZE * 8 . '-bit',
    'A 64-bit PHP build is required.');

$req = ['pdo_mysql' => 'database', 'mbstring' => 'Arabic text', 'json' => 'data', 'openssl' => 'secure requests'];
foreach ($req as $ext => $why) {
    chk('PHP extensions', $ext, extension_loaded($ext) ? 'pass' : 'fail', extension_loaded($ext) ? 'loaded' : 'missing',
        "Enable the $ext extension (needed for $why).");
}
chk('PHP extensions', 'zip', extension_loaded('zip') ? 'pass' : 'warn', extension_loaded('zip') ? 'loaded' : 'missing — built-in reader will be used',
    'Optional. Excel files are read without it; with it, imports are slightly faster.');
chk('PHP extensions', 'gd or imagick', (extension_loaded('gd') || extension_loaded('imagick')) ? 'pass' : 'warn',
    extension_loaded('gd') ? 'gd' : (extension_loaded('imagick') ? 'imagick' : 'missing'),
    'Without it, doctor photos are stored at full size instead of being resized.');
chk('PHP extensions', 'sodium (signature check)', extension_loaded('sodium') ? 'pass' : 'warn',
    extension_loaded('sodium') ? 'loaded' : 'missing — bundled fallback will be used',
    'Preferred but not required; a bundled pure-PHP verifier is used when sodium is absent (slower, still secure).');

$curl = extension_loaded('curl');
$fopen = filter_var(ini_get('allow_url_fopen'), FILTER_VALIDATE_BOOLEAN);
chk('Outbound network', 'curl or allow_url_fopen', ($curl || $fopen) ? 'pass' : 'fail',
    $curl ? 'curl' : ($fopen ? 'allow_url_fopen' : 'neither'),
    'The system must be able to reach license.asktam.net to validate the licence.');

/* ---------- limits ---------- */
$mem = to_bytes((string) ini_get('memory_limit'));
chk('Limits', 'memory_limit', ($mem === -1 || $mem >= 128 * 1024 * 1024) ? 'pass' : 'warn', (string) ini_get('memory_limit'),
    'At least 128M is recommended. Lower values still work but Excel import runs in smaller chunks.');
$maxEx = (int) ini_get('max_execution_time');
chk('Limits', 'max_execution_time', ($maxEx === 0 || $maxEx >= 30) ? 'pass' : 'warn', $maxEx === 0 ? 'unlimited' : $maxEx . 's',
    'Imports and reports are processed in chunks, so short limits are handled — but under 30s makes them slower.');
$up = to_bytes((string) ini_get('upload_max_filesize'));
chk('Limits', 'upload_max_filesize', ($up === -1 || $up >= 8 * 1024 * 1024) ? 'pass' : 'warn', (string) ini_get('upload_max_filesize'),
    'At least 8M is recommended for Excel files and photos.');

/* ---------- filesystem ---------- */
$dir = __DIR__;
chk('Files', 'writable directory', is_writable($dir) ? 'pass' : 'fail', is_writable($dir) ? $dir : 'not writable',
    'The folder must be writable so the installer can create config.php and the data folders.');
$free = @disk_free_space($dir);
chk('Files', 'free disk space', ($free === false) ? 'warn' : (($free > 500 * 1024 * 1024) ? 'pass' : 'warn'),
    $free === false ? 'unknown' : round($free / 1048576) . ' MB', 'At least 500 MB free is recommended.');

/* ---------- web server ---------- */
$sapi = PHP_SAPI;
$soft = $_SERVER['SERVER_SOFTWARE'] ?? 'unknown';
$apache = stripos($soft, 'apache') !== false || stripos($soft, 'litespeed') !== false;
chk('Web server', 'server software', 'info', $soft, '');
chk('Web server', 'clean URLs', $apache ? 'pass' : 'warn', $apache ? '.htaccess supported' : 'not Apache/LiteSpeed',
    'On Nginx or Plesk, the installer prints the rewrite rule to paste into the panel.');
$https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https';
chk('Web server', 'HTTPS', $https ? 'pass' : 'warn', $https ? 'enabled' : 'not detected',
    'Enable the free SSL certificate in the hosting panel before going live.');
chk('Web server', 'PHP SAPI', 'info', $sapi, '');

/* ---------- database (optional) ---------- */
$dbTried = false;
if (!empty($_POST['db_host'])) {
    $dbTried = true;
    try {
        $dsn = 'mysql:host=' . $_POST['db_host'] . ';dbname=' . ($_POST['db_name'] ?? '') . ';charset=utf8mb4';
        $pdo = new PDO($dsn, (string) ($_POST['db_user'] ?? ''), (string) ($_POST['db_pass'] ?? ''), [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_TIMEOUT => 5]);
        $ver = (string) $pdo->query('SELECT VERSION()')->fetchColumn();
        $isMaria = stripos($ver, 'mariadb') !== false;
        $num = preg_replace('/[^0-9.].*$/', '', $ver);
        $okVer = $isMaria ? version_compare($num, '10.3.0', '>=') : version_compare($num, DP_MIN_MYSQL, '>=');
        chk('Database', 'server version', $okVer ? 'pass' : 'fail', $ver, 'MySQL 5.7+ or MariaDB 10.3+ is required.');
        $pdo->exec('CREATE TABLE IF NOT EXISTS dp_probe_tmp (id INT PRIMARY KEY) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
        $pdo->exec('DROP TABLE dp_probe_tmp');
        chk('Database', 'create/drop tables', 'pass', 'permitted', '');
    } catch (Throwable $e) {
        chk('Database', 'connection', 'fail', $e->getMessage(), 'Check the database name, user, password and host in the hosting panel.');
    }
}

$fails = count(array_filter($R, fn($r) => $r['state'] === 'fail'));
$warns = count(array_filter($R, fn($r) => $r['state'] === 'warn'));
$verdict = $fails ? 'not compatible' : ($warns ? 'compatible with notes' : 'fully compatible');

if (isset($_GET['json'])) {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['verdict' => $verdict, 'fails' => $fails, 'warnings' => $warns, 'php' => PHP_VERSION, 'checks' => $R], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    exit;
}

$color = $fails ? '#dc2626' : ($warns ? '#d97706' : '#16a34a');
$dot = ['pass' => '#16a34a', 'warn' => '#d97706', 'fail' => '#dc2626', 'info' => '#64748b'];
header('Content-Type: text/html; charset=utf-8');
?><!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Doctor Profiles — hosting check</title>
<style>
*{box-sizing:border-box}body{font-family:system-ui,-apple-system,"Segoe UI",Tahoma,sans-serif;background:#f6f8fb;margin:0;padding:28px;color:#111827}
.w{max-width:860px;margin:0 auto}h1{font-size:21px;margin:0 0 4px}.sub{color:#6b7280;font-size:14px;margin-bottom:20px}
.v{background:#fff;border:1px solid #e5e7eb;border-left:5px solid <?= $color ?>;border-radius:12px;padding:16px 18px;margin-bottom:18px}
.v b{color:<?= $color ?>;font-size:17px;text-transform:capitalize}
table{width:100%;border-collapse:collapse;background:#fff;border:1px solid #e5e7eb;border-radius:12px;overflow:hidden;font-size:14px}
th{background:#f9fafb;text-align:left;padding:9px 12px;font-size:12px;color:#6b7280;text-transform:uppercase;letter-spacing:.03em}
td{padding:9px 12px;border-top:1px solid #f1f5f9;vertical-align:top}
.s{display:inline-block;width:9px;height:9px;border-radius:50%;margin-inline-end:7px}
.fix{color:#6b7280;font-size:12px;margin-top:3px}
.mono{font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12.5px;color:#374151;word-break:break-word}
form{background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:16px 18px;margin-top:18px}
input{padding:8px 10px;border:1px solid #d1d5db;border-radius:8px;font-size:14px;margin:4px 6px 4px 0;min-width:170px}
button{background:#2563eb;color:#fff;border:0;border-radius:8px;padding:9px 18px;font-size:14px;cursor:pointer}
.ft{color:#9ca3af;font-size:12px;margin-top:18px;text-align:center}
</style></head><body><div class="w">
<h1>Doctor Profiles — hosting compatibility check</h1>
<div class="sub">AskTam · this page reads your server settings only. Nothing is installed or changed.</div>
<div class="v">Result: <b><?= htmlspecialchars($verdict) ?></b><br>
<span style="color:#6b7280;font-size:13px"><?= $fails ?> blocking issue(s), <?= $warns ?> note(s).
<?= $fails ? 'This hosting account cannot run the system as it is.' : 'Send this page to AskTam and we will proceed.' ?></span></div>
<table><tr><th>Area</th><th>Check</th><th>Result</th></tr>
<?php $last = ''; foreach ($R as $r): ?>
<tr><td><?= $r['area'] === $last ? '' : htmlspecialchars($r['area']) ?><?php $last = $r['area']; ?></td>
<td><span class="s" style="background:<?= $dot[$r['state']] ?>"></span><?= htmlspecialchars($r['name']) ?></td>
<td><span class="mono"><?= htmlspecialchars($r['found']) ?></span>
<?= ($r['state'] === 'pass' || $r['state'] === 'info' || $r['fix'] === '') ? '' : '<div class="fix">' . htmlspecialchars($r['fix']) . '</div>' ?></td></tr>
<?php endforeach; ?>
</table>
<form method="post">
<div style="font-weight:600;margin-bottom:6px">Optional: test the database too</div>
<div style="color:#6b7280;font-size:13px;margin-bottom:10px">Create a MySQL database and user in the hosting panel, then enter them here. The details are used once and never stored.</div>
<input name="db_host" placeholder="Host (usually localhost)" value="<?= htmlspecialchars((string) ($_POST['db_host'] ?? 'localhost')) ?>">
<input name="db_name" placeholder="Database name" value="<?= htmlspecialchars((string) ($_POST['db_name'] ?? '')) ?>">
<input name="db_user" placeholder="Database user" value="<?= htmlspecialchars((string) ($_POST['db_user'] ?? '')) ?>">
<input name="db_pass" type="password" placeholder="Database password">
<div style="margin-top:10px"><button type="submit">Test database</button></div>
</form>
<div class="ft">Delete this file after the check. AskTam · license.asktam.net</div>
</div></body></html>
