<?php
// api/leave_verify.php
// Public, tokenized QR verification page for Rockview University leave actions.
// No sensitive leave reason/contact information is exposed.

declare(strict_types=1);

require_once __DIR__ . '/leave_common.php';
leave_ensure_tables($pdo);

header('Cache-Control: no-store, no-cache, must-revalidate');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: no-referrer');
header('X-Frame-Options: DENY');

$token = leave_clean($_GET['token'] ?? '', 64);
$format = strtolower(leave_clean($_GET['format'] ?? '', 20));

function verify_html(string $value): string {
    return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function verify_date($value): string {
    if (!$value) return 'Not recorded';
    try {
        return (new DateTimeImmutable((string)$value))->format('d M Y, H:i');
    } catch (Throwable $e) {
        return (string)$value;
    }
}

if ($token === '' || !preg_match('/^[a-f0-9]{64}$/i', $token)) {
    if ($format === 'json') leave_json(['verified'=>false,'detail'=>'Invalid verification token.'], 400);
    http_response_code(400);
    echo '<!doctype html><html><body style="font-family:Arial;padding:40px"><h2>Invalid QR verification token</h2><p>This code is not a valid Rockview University leave verification record.</p></body></html>';
    exit;
}

try {
    $kind = '';
    $leave = null;
    $verified = null;

    $stmt = $pdo->prepare('SELECT * FROM leave_applications WHERE applicant_qr_token = ? LIMIT 1');
    $stmt->execute([$token]);
    $application = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($application) {
        $kind = 'submission';
        $leave = $application;
        $verified = [
            'actor_name' => $application['applicant_name'],
            'actor_position' => $application['position_title'],
            'actor_campus' => $application['campus'],
            'action' => 'SUBMITTED',
            'decision' => 'Leave application submitted',
            'remarks' => 'Official employee submission record.',
            'signed_at' => $application['submitted_at'],
        ];
    } else {
        $stmt = $pdo->prepare('SELECT lr.*, la.applicant_name, la.department, la.campus AS applicant_campus, la.leave_type, la.start_date, la.end_date, la.requested_days, la.status
                               FROM leave_routes lr
                               INNER JOIN leave_applications la ON la.id = lr.leave_id
                               WHERE lr.qr_token = ? LIMIT 1');
        $stmt->execute([$token]);
        $route = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($route) {
            $kind = 'workflow_action';
            $verified = $route;
            $leaveStmt = $pdo->prepare('SELECT * FROM leave_applications WHERE id = ? LIMIT 1');
            $leaveStmt->execute([(int)$route['leave_id']]);
            $leave = $leaveStmt->fetch(PDO::FETCH_ASSOC);
        }
    }

    if (!$leave || !$verified) {
        if ($format === 'json') leave_json(['verified'=>false,'detail'=>'No official leave record matches this QR code.'], 404);
        http_response_code(404);
        echo '<!doctype html><html><body style="font-family:Arial;padding:40px"><h2>Verification record not found</h2><p>This QR code does not match an active Rockview University leave record.</p></body></html>';
        exit;
    }

    $leaveId = (int)$leave['id'];
    $historyStmt = $pdo->prepare('SELECT actor_name, actor_position, actor_campus, action, decision, from_stage, to_stage, signed_at FROM leave_routes WHERE leave_id = ? ORDER BY signed_at ASC, id ASC');
    $historyStmt->execute([$leaveId]);
    $history = $historyStmt->fetchAll(PDO::FETCH_ASSOC);

    $payload = [
        'verified' => true,
        'record_type' => $kind,
        'leave_reference' => $leaveId,
        'leave_status' => $leave['status'],
        'employee' => [
            'name' => $leave['applicant_name'],
            'department' => $leave['department'],
            'campus' => $leave['campus'],
        ],
        'leave' => [
            'type' => $leave['leave_type'],
            'start_date' => $leave['start_date'],
            'end_date' => $leave['end_date'],
            'requested_days' => (float)$leave['requested_days'],
        ],
        'verified_action' => [
            'name' => $verified['actor_name'],
            'position' => $verified['actor_position'] ?? '',
            'campus' => $verified['actor_campus'] ?? '',
            'action' => $verified['action'],
            'decision' => $verified['decision'] ?? '',
            'timestamp' => $verified['signed_at'],
        ],
        'workflow_history' => $history,
    ];

    if ($format === 'json') leave_json($payload);

    $status = strtoupper((string)$leave['status']);
    $actorName = verify_html((string)$verified['actor_name']);
    $actorPosition = verify_html((string)($verified['actor_position'] ?? 'Staff'));
    $actorCampus = verify_html((string)($verified['actor_campus'] ?? $leave['campus']));
    $actionLabel = verify_html(strtoupper((string)$verified['action']));
    $decision = verify_html((string)($verified['decision'] ?? 'Recorded action'));
    $employeeName = verify_html((string)$leave['applicant_name']);
    $department = verify_html((string)$leave['department']);
    $campus = verify_html((string)$leave['campus']);
    $leaveType = verify_html(strtoupper((string)$leave['leave_type']));
    $requestedDays = number_format((float)$leave['requested_days'], 2);

    header('Content-Type: text/html; charset=UTF-8');
    echo '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">';
    echo '<title>Rockview University Leave Verification</title>';
    echo '<style>
        :root{--green:#026930;--gold:#cc7504;--ink:#18241e;--muted:#66736c;--line:#dce5df;--soft:#f5f8f6;}
        *{box-sizing:border-box}body{margin:0;background:#eef3f0;color:var(--ink);font-family:Inter,Segoe UI,Arial,sans-serif}
        .top{height:8px;background:linear-gradient(90deg,var(--green) 0 72%,var(--gold) 72%)}
        .page{max-width:920px;margin:28px auto;padding:0 16px 44px}.card{background:white;border:1px solid var(--line);border-radius:20px;box-shadow:0 14px 40px rgba(18,45,31,.08);overflow:hidden}
        .head{padding:24px 28px;border-bottom:1px solid var(--line);display:flex;gap:18px;align-items:center}.seal{width:62px;height:62px;border-radius:50%;background:var(--green);color:white;display:grid;place-items:center;font-weight:900;font-size:22px;border:4px solid #e8f1eb;box-shadow:0 0 0 2px var(--gold)}
        h1{font-size:22px;margin:0;color:var(--green);letter-spacing:.3px}.sub{color:var(--muted);font-size:13px;margin-top:4px}.verified{margin-left:auto;background:#eaf7ef;color:var(--green);border:1px solid #b9dfc7;padding:9px 12px;border-radius:999px;font-size:12px;font-weight:800;white-space:nowrap}
        .body{padding:26px 28px}.hero{display:grid;grid-template-columns:1.15fr .85fr;gap:16px}.panel{border:1px solid var(--line);border-radius:16px;padding:18px;background:var(--soft)}
        .eyebrow{font-size:10px;font-weight:900;letter-spacing:1px;color:var(--muted);text-transform:uppercase}.name{font-size:20px;font-weight:900;margin-top:7px}.role{color:var(--green);font-weight:800;font-size:13px;margin-top:4px}.action{font-size:17px;font-weight:900;color:var(--gold);margin-top:8px}.meta{margin-top:12px;display:grid;grid-template-columns:1fr 1fr;gap:10px}.kv{background:#fff;border:1px solid var(--line);border-radius:12px;padding:11px}.k{font-size:9px;color:var(--muted);font-weight:900;letter-spacing:.6px}.v{margin-top:4px;font-size:12px;font-weight:800;word-break:break-word}
        .trail{margin-top:22px}.trail h2{font-size:14px}.item{display:grid;grid-template-columns:18px 1fr;gap:10px;padding:12px 0;border-top:1px solid var(--line)}.dot{width:12px;height:12px;border-radius:50%;background:var(--green);margin-top:4px;border:3px solid #d9eddf}.who{font-weight:900;font-size:12px}.what{font-size:11px;color:var(--muted);margin-top:3px}.foot{padding:18px 28px;background:#fbfcfb;border-top:1px solid var(--line);font-size:11px;color:var(--muted);line-height:1.5}
        @media(max-width:700px){.page{margin:12px auto}.head{padding:18px;align-items:flex-start}.verified{font-size:10px}.body{padding:18px}.hero{grid-template-columns:1fr}.meta{grid-template-columns:1fr}.seal{width:52px;height:52px}.head h1{font-size:18px}}
    </style></head><body><div class="top"></div><main class="page"><section class="card">';
    echo '<header class="head"><div class="seal">RU</div><div><h1>ROCKVIEW UNIVERSITY</h1><div class="sub">Official Leave Workflow Verification</div></div><div class="verified">✓ VERIFIED RECORD</div></header>';
    echo '<div class="body"><div class="hero"><div class="panel"><div class="eyebrow">Verified person and action</div><div class="name">'.$actorName.'</div><div class="role">'.$actorPosition.' • '.$actorCampus.'</div><div class="action">'.$actionLabel.'</div><div class="sub">'.$decision.'</div><div class="meta"><div class="kv"><div class="k">VERIFIED AT</div><div class="v">'.verify_html(verify_date($verified['signed_at'])).'</div></div><div class="kv"><div class="k">LEAVE REFERENCE</div><div class="v">#'.$leaveId.'</div></div></div></div>';
    echo '<div class="panel"><div class="eyebrow">Leave record</div><div class="meta"><div class="kv"><div class="k">EMPLOYEE</div><div class="v">'.$employeeName.'</div></div><div class="kv"><div class="k">STATUS</div><div class="v">'.verify_html($status).'</div></div><div class="kv"><div class="k">DEPARTMENT</div><div class="v">'.$department.'</div></div><div class="kv"><div class="k">CAMPUS</div><div class="v">'.$campus.'</div></div><div class="kv"><div class="k">LEAVE TYPE</div><div class="v">'.$leaveType.'</div></div><div class="kv"><div class="k">DAYS</div><div class="v">'.$requestedDays.'</div></div></div></div></div>';
    echo '<div class="trail"><h2>Authenticated workflow record</h2>';
    foreach ($history as $event) {
        $who = verify_html((string)$event['actor_name']);
        $pos = verify_html((string)($event['actor_position'] ?? ''));
        $act = verify_html(strtoupper((string)$event['action']));
        $when = verify_html(verify_date($event['signed_at']));
        $from = verify_html((string)($event['from_stage'] ?? ''));
        $to = verify_html((string)($event['to_stage'] ?? ''));
        echo '<div class="item"><div class="dot"></div><div><div class="who">'.$who.($pos !== '' ? ' • '.$pos : '').'</div><div class="what">'.$act.($from !== '' ? ' • '.$from : '').($to !== '' ? ' → '.$to : '').' • '.$when.'</div></div></div>';
    }
    echo '</div></div><footer class="foot">This page confirms that the scanned QR token matches a server-side Rockview University leave workflow record. It shows audit information only; confidential leave reasons and personal contact information are intentionally not displayed.</footer></section></main></body></html>';
} catch (Throwable $e) {
    if ($format === 'json') leave_json(['verified'=>false,'detail'=>'Verification service error.'],500);
    http_response_code(500);
    echo '<!doctype html><html><body style="font-family:Arial;padding:40px"><h2>Verification service unavailable</h2><p>Please try again or contact Rockview University administration.</p></body></html>';
}
