<?php
// ============================================================
//  config/db.php
// ============================================================

// ─── APNI DB DETAILS YAHAN BHARO ────────────────────────────
define('DB_HOST',    'localhost');
define('DB_USER',    'u427625983_schoolinmycity');        // cPanel pe: u427625983_schoolinmycity
define('DB_PASS',    'K#$%^tfvgyt657guvgGG');            // apna DB password
define('DB_NAME',    'u427625983_schoolinmycity');// cPanel pe: u427625983_schoolinmycity
define('DB_CHARSET', 'utf8mb4');
// ─────────────────────────────────────────────────────────────

define('UPLOAD_BASE',         rtrim(str_replace('\\', '/', __DIR__ . '/../uploads'), '/') . '/');
define('MAX_FILE_SIZE',       50 * 1024 * 1024);
define('ALLOWED_MANUSCRIPT',  ['doc','docx','tex','bib','pdf']);
define('ALLOWED_FIGURES',     ['tif','tiff','jpg','jpeg','png']);
define('ALLOWED_OTHER',       ['doc','docx','pdf','jpg','png','xlsx','mp4','mp3']);
define('SESSION_LIFETIME',    7200);

/* ── PDO singleton ── */
function db(): PDO {
    static $pdo = null;
    if ($pdo === null) {
        $dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET;
        try {
            $pdo = new PDO($dsn, DB_USER, DB_PASS, [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
            ]);
        } catch (PDOException $e) {
            http_response_code(500);
            die(json_encode(['success'=>false,'message'=>'DB error: '.$e->getMessage()]));
        }
    }
    return $pdo;
}

/* ── Session ── */
function startSession(): void {
    if (session_status() === PHP_SESSION_NONE) {
        session_set_cookie_params([
            'lifetime' => SESSION_LIFETIME,
            'path'     => '/',
            'secure'   => false,
            'httponly' => true,
            'samesite' => 'Lax',
        ]);
        session_start();
    }
}

/* ── JSON helper ── */
function jsonResponse(bool $success, string $message = '', array $data = []): void {
    header('Content-Type: application/json');
    echo json_encode(array_merge(['success'=>$success,'message'=>$message], $data));
    exit;
}

/* ── Remember-me cookie login ── */
function _loginFromRememberToken(string $token): void {
    $hash = hash('sha256', $token);
    try {
        $q = db()->prepare(
            "SELECT user_id FROM remember_tokens
             WHERE token_hash=? AND expires_at > NOW() LIMIT 1"
        );
        $q->execute([$hash]);
        $row = $q->fetch();
        if ($row) {
            $_SESSION['user_id']    = $row['user_id'];
            $_SESSION['logged_in']  = true;
            $_SESSION['login_time'] = time();
        }
    } catch(PDOException $e){}
}

/* ── isLoggedIn ── */
function isLoggedIn(): bool {
    startSession();
    if (!empty($_SESSION['user_id'])) return true;
    if (!empty($_COOKIE['remember_token'])) {
        _loginFromRememberToken($_COOKIE['remember_token']);
        return !empty($_SESSION['user_id']);
    }
    return false;
}

/* ── getCurrentUserId ── */
function getCurrentUserId(): int {
    startSession();

    if (empty($_SESSION['user_id']) && !empty($_COOKIE['remember_token'])) {
        _loginFromRememberToken($_COOKIE['remember_token']);
    }

    if (!empty($_SESSION['user_id'])) {
        return (int)$_SESSION['user_id'];
    }

    // Not logged in
    $isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) ||
              str_contains($_SERVER['CONTENT_TYPE'] ?? '', 'application/json') ||
              str_contains($_SERVER['REQUEST_URI']   ?? '', 'ajax/');
    if ($isAjax) {
        // jsonResponse(false, 'Session expired. Please log in.', ['redirect'=>'login.php']);
        jsonResponse(false, 'Session expired. Please log in.', ['redirect'=>'/reviewer/login.php']);

    }
    $current = urlencode($_SERVER['REQUEST_URI'] ?? '');
    // header("Location: login.php?msg=session_expired&redirect=$current");
    header("Location: /reviewer/login.php?msg=session_expired&redirect=$current");

    exit;
}

/* ── getCurrentUser ── */
function getCurrentUser(): array {
    $uid = getCurrentUserId();
    try {
        $stmt = db()->prepare("SELECT * FROM users WHERE user_id=?");
        $stmt->execute([$uid]);
        $u = $stmt->fetch();
        if ($u) return $u;
    } catch(PDOException $e){}
    session_destroy();
    header('Location: login.php?msg=session_expired');
    exit;
}