<?php
declare(strict_types=1);

@date_default_timezone_set('Asia/Colombo');
ini_set('display_errors', '0');
ini_set('log_errors', '1');
error_reporting(E_ALL);

header('Content-Type: application/json; charset=utf-8');
ob_start();

function json_out(array $payload, int $status = 200): void {
    if (!headers_sent()) {
        http_response_code($status);
        header('Content-Type: application/json; charset=utf-8');
    }
    while (ob_get_level() > 0) {
        ob_end_clean();
    }
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

set_exception_handler(function (Throwable $e) {
    json_out([
        'ok' => false,
        'message' => 'Server error: ' . $e->getMessage(),
    ], 500);
});

set_error_handler(function ($severity, $message, $file, $line) {
    throw new ErrorException($message, 0, $severity, $file, $line);
});

register_shutdown_function(function () {
    $err = error_get_last();
    if ($err && in_array($err['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true)) {
        json_out([
            'ok' => false,
            'message' => 'Fatal error: ' . $err['message'],
        ], 500);
    }
});

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$mysqli = null;

if (is_file(__DIR__ . '/../includes/auth.php')) {
    require_once __DIR__ . '/../includes/auth.php';
    if (function_exists('ec_db')) {
        $db = ec_db();
        if ($db instanceof mysqli) {
            $mysqli = $db;
        }
    }
}

if (!$mysqli) {
    $mysqli = new mysqli('localhost', 'root', '', 'edencamp_edencampus');
}
$mysqli->set_charset('utf8mb4');

function tableExists(mysqli $db, string $t): bool {
    $st = $db->prepare("
        SELECT 1
        FROM INFORMATION_SCHEMA.TABLES
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = ?
        LIMIT 1
    ");
    if (!$st) {
        throw new RuntimeException('Prepare failed (tableExists): ' . $db->error);
    }
    $st->bind_param('s', $t);
    $st->execute();
    $st->store_result();
    $ok = $st->num_rows > 0;
    $st->free_result();
    $st->close();
    return $ok;
}

function colExists(mysqli $db, string $t, string $c): bool {
    $st = $db->prepare("
        SELECT 1
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = ?
          AND COLUMN_NAME = ?
        LIMIT 1
    ");
    if (!$st) {
        throw new RuntimeException('Prepare failed (colExists): ' . $db->error);
    }
    $st->bind_param('ss', $t, $c);
    $st->execute();
    $st->store_result();
    $ok = $st->num_rows > 0;
    $st->free_result();
    $st->close();
    return $ok;
}

if (!tableExists($mysqli, 'student_verifications')) {
    json_out([
        'ok' => false,
        'message' => 'Verification record not found',
    ], 404);
}

$student_id = (int)($_POST['student_id'] ?? 0);
$otp        = trim((string)($_POST['otp'] ?? ''));

if ($student_id <= 0 || $otp === '') {
    json_out([
        'ok' => false,
        'message' => 'Student ID and OTP are required',
    ], 400);
}

$hasOtpHash    = colExists($mysqli, 'student_verifications', 'otp_hash');
$hasOtpCode    = colExists($mysqli, 'student_verifications', 'otp_code');
$hasVerifiedOn = colExists($mysqli, 'student_verifications', 'verified_on');
$hasUpdatedAt  = colExists($mysqli, 'student_verifications', 'updated_at');

$selectCols = "id, student_id, verified";
if ($hasOtpHash) $selectCols .= ", otp_hash";
if ($hasOtpCode) $selectCols .= ", otp_code";

$sql = "SELECT $selectCols FROM student_verifications WHERE student_id=? LIMIT 1";
$st  = $mysqli->prepare($sql);
if (!$st) {
    throw new RuntimeException('Prepare failed (select verification): ' . $mysqli->error);
}
$st->bind_param('i', $student_id);
$st->execute();
$res = $st->get_result();
$row = $res ? $res->fetch_assoc() : null;
$st->close();

if (!$row) {
    json_out([
        'ok' => false,
        'message' => 'Verification record not found',
    ], 404);
}

$valid = false;

if ($hasOtpHash && !empty($row['otp_hash'])) {
    $valid = password_verify($otp, (string)$row['otp_hash']);
}

if (!$valid && $hasOtpCode && !empty($row['otp_code'])) {
    $valid = hash_equals((string)$row['otp_code'], $otp);
}

if (!$valid) {
    json_out([
        'ok' => false,
        'message' => 'Invalid OTP',
    ], 400);
}

/*
|--------------------------------------------------------------------------
| Valid OTP only -> mark verified
|--------------------------------------------------------------------------
*/
$set = ["verified=1"];
if ($hasVerifiedOn) $set[] = "verified_on=NOW()";
if ($hasOtpHash)    $set[] = "otp_hash=NULL";
if ($hasOtpCode)    $set[] = "otp_code=NULL";
if ($hasUpdatedAt)  $set[] = "updated_at=NOW()";

$updateSql = "UPDATE student_verifications SET " . implode(', ', $set) . " WHERE student_id=?";
$up = $mysqli->prepare($updateSql);
if (!$up) {
    throw new RuntimeException('Prepare failed (update verification): ' . $mysqli->error);
}
$up->bind_param('i', $student_id);
$up->execute();
$up->close();

json_out([
    'ok' => true,
    'message' => 'OTP verified successfully',
]);