<?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;
}

/*
|--------------------------------------------------------------------------
| Ensure table / columns
|--------------------------------------------------------------------------
*/
if (!tableExists($mysqli, 'student_verifications')) {
    $mysqli->query("
        CREATE TABLE student_verifications (
            id INT AUTO_INCREMENT PRIMARY KEY,
            student_id INT NOT NULL UNIQUE,
            student_ref_no VARCHAR(64) NULL,
            first_name VARCHAR(120) NULL,
            last_name VARCHAR(120) NULL,
            certificate_name VARCHAR(200) NULL,
            verified TINYINT(1) NOT NULL DEFAULT 0,
            otp_hash VARCHAR(255) NULL,
            otp_code VARCHAR(10) NULL,
            verified_on DATETIME NULL,
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
} else {
    if (!colExists($mysqli, 'student_verifications', 'otp_hash')) {
        $mysqli->query("ALTER TABLE student_verifications ADD COLUMN otp_hash VARCHAR(255) NULL AFTER verified");
    }
    if (!colExists($mysqli, 'student_verifications', 'otp_code')) {
        $mysqli->query("ALTER TABLE student_verifications ADD COLUMN otp_code VARCHAR(10) NULL AFTER otp_hash");
    }
    if (!colExists($mysqli, 'student_verifications', 'verified_on')) {
        $mysqli->query("ALTER TABLE student_verifications ADD COLUMN verified_on DATETIME NULL AFTER otp_code");
    }
    if (!colExists($mysqli, 'student_verifications', 'created_at')) {
        $mysqli->query("ALTER TABLE student_verifications ADD COLUMN created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP");
    }
    if (!colExists($mysqli, 'student_verifications', 'updated_at')) {
        $mysqli->query("ALTER TABLE student_verifications ADD COLUMN updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP");
    }
}

$student_id = (int)($_POST['student_id'] ?? 0);
$first      = trim((string)($_POST['first_name'] ?? ''));
$last       = trim((string)($_POST['last_name'] ?? ''));
$cert_name  = trim((string)($_POST['certificate_name'] ?? ''));
$ref        = trim((string)($_POST['student_ref_no'] ?? ''));

if ($student_id <= 0 || $first === '' || $last === '' || $cert_name === '') {
    json_out([
        'ok' => false,
        'message' => 'Missing required fields',
    ], 400);
}

/*
|--------------------------------------------------------------------------
| Optional student existence check
|--------------------------------------------------------------------------
*/
if (tableExists($mysqli, 'studentss')) {
    $sql = "SELECT id FROM studentss WHERE id=? LIMIT 1";
    $st  = $mysqli->prepare($sql);
    if (!$st) {
        throw new RuntimeException('Prepare failed (studentss check): ' . $mysqli->error);
    }
    $st->bind_param('i', $student_id);
    $st->execute();
    $st->store_result();
    $existsStudent = $st->num_rows > 0;
    $st->free_result();
    $st->close();

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

/*
|--------------------------------------------------------------------------
| Generate OTP
|--------------------------------------------------------------------------
*/
$otp  = (string)random_int(100000, 999999);
$hash = password_hash($otp, PASSWORD_BCRYPT);

/*
|--------------------------------------------------------------------------
| Upsert
|--------------------------------------------------------------------------
*/
$sqlCheck = "SELECT id FROM student_verifications WHERE student_id=? LIMIT 1";
$check = $mysqli->prepare($sqlCheck);
if (!$check) {
    throw new RuntimeException('Prepare failed (verification check): ' . $mysqli->error);
}
$check->bind_param('i', $student_id);
$check->execute();
$check->store_result();
$hasRow = $check->num_rows > 0;
$check->free_result();
$check->close();

if ($hasRow) {
    $sqlUpdate = "
        UPDATE student_verifications
        SET student_ref_no   = ?,
            first_name       = ?,
            last_name        = ?,
            certificate_name = ?,
            verified         = 0,
            otp_hash         = ?,
            otp_code         = ?,
            verified_on      = NULL,
            updated_at       = NOW()
        WHERE student_id     = ?
    ";
    $st = $mysqli->prepare($sqlUpdate);
    if (!$st) {
        throw new RuntimeException('Prepare failed (verification update): ' . $mysqli->error);
    }
    $st->bind_param('ssssssi', $ref, $first, $last, $cert_name, $hash, $otp, $student_id);
    $st->execute();
    $st->close();
} else {
    $sqlInsert = "
        INSERT INTO student_verifications
            (student_id, student_ref_no, first_name, last_name, certificate_name, verified, otp_hash, otp_code, verified_on, created_at, updated_at)
        VALUES
            (?, ?, ?, ?, ?, 0, ?, ?, NULL, NOW(), NOW())
    ";
    $st = $mysqli->prepare($sqlInsert);
    if (!$st) {
        throw new RuntimeException('Prepare failed (verification insert): ' . $mysqli->error);
    }
    $st->bind_param('issssss', $student_id, $ref, $first, $last, $cert_name, $hash, $otp);
    $st->execute();
    $st->close();
}

json_out([
    'ok'      => true,
    'message' => 'Verification data saved successfully. OTP generated.',
    'otp'     => $otp
]);