<?php
// ─── Helper Functions ────────────────────────────────────────────────────────
if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME'])) {
    header('HTTP/1.0 403 Forbidden', true, 403);
    exit;
}

if (!function_exists('encode')) {
    /**
     * Custom XOR-based string encoding (legacy compatibility)
     */
    function encode($string, $key) {
        $key    = sha1($key);
        $strLen = strlen($string);
        $keyLen = strlen($key);
        $j      = 0;
        $hash   = '';
        for ($i = 0; $i < $strLen; $i++) {
            $ordStr = ord(substr($string, $i, 1));
            if ($j == $keyLen) { $j = 0; }
            $ordKey = ord(substr($key, $j, 1));
            $j++;
            $hash .= strrev(base_convert(dechex($ordStr + $ordKey), 16, 36));
        }
        return $hash;
    }
}

if (!function_exists('decode')) {
    /**
     * Custom XOR-based string decoding (legacy compatibility)
     */
    function decode($string, $key) {
        $key    = sha1($key);
        $strLen = strlen($string);
        $keyLen = strlen($key);
        $j      = 0;
        $hash   = '';
        for ($i = 0; $i < $strLen; $i += 2) {
            $ordStr = hexdec(base_convert(strrev(substr($string, $i, 2)), 36, 16));
            if ($j == $keyLen) { $j = 0; }
            $ordKey = ord(substr($key, $j, 1));
            $j++;
            $hash .= chr($ordStr - $ordKey);
        }
        return $hash;
    }
}

if (!function_exists('json_response')) {
    /**
     * Send JSON response with proper headers
     */
    function json_response($data, $statusCode = 200) {
        http_response_code($statusCode);
        header('Content-Type: application/json');
        echo json_encode($data);
        exit;
    }
}

if (!function_exists('error_response')) {
    /**
     * Send error JSON response
     */
    function error_response($message, $statusCode = 400) {
        json_response(['success' => false, 'message' => $message], $statusCode);
    }
}

if (!function_exists('success_response')) {
    /**
     * Send success JSON response
     */
    function success_response($data = [], $message = 'Success') {
        json_response(['success' => true, 'message' => $message, 'data' => $data]);
    }
}

if (!function_exists('require_login')) {
    /**
     * Require authenticated user
     */
    function require_login() {
        if (session_status() === PHP_SESSION_NONE) session_start();
        if (!isset($_SESSION['idx'])) {
            error_response('Authentication required', 401);
        }
        return (int) decode($_SESSION['idx'], KEY_TWO);
    }
}

if (!function_exists('is_admin')) {
    /**
     * Role-based admin check against h_user.role — the single source of
     * truth for admin access, replacing the old hardcoded uid===1 rule.
     */
    function is_admin($uid) {
        global $conn;
        $uid = (int)$uid;
        $result = mysqli_query($conn, "SELECT role FROM h_user WHERE id='$uid'");
        if (!$result) return false; // e.g. h_user.role not migrated yet — fail safe, not fatal
        $row = mysqli_fetch_assoc($result);
        return ($row['role'] ?? 'user') === 'admin';
    }
}

if (!function_exists('require_admin')) {
    /**
     * Require an admin-role user
     */
    function require_admin() {
        $uid = require_login();
        if (!is_admin($uid)) {
            error_response('Admin access required', 403);
        }
        return $uid;
    }
}

if (!function_exists('check_password')) {
    /**
     * Verify a plaintext password against a stored hash. Falls back to the
     * legacy XOR encode() scheme for accounts created before password_hash()
     * was adopted, and transparently re-hashes them with password_hash() on
     * successful legacy verification so the DB migrates itself over time.
     */
    function check_password($plain, $stored, $uid = null) {
        if (password_verify($plain, $stored)) return true;
        if (encode($plain, KEY_TWO) === $stored) {
            if ($uid !== null) {
                global $conn;
                $newHash = mysqli_real_escape_string($conn, password_hash($plain, PASSWORD_DEFAULT));
                mysqli_query($conn, "UPDATE h_user SET pass='$newHash' WHERE id='" . (int)$uid . "'");
            }
            return true;
        }
        return false;
    }
}

if (!function_exists('sanitize')) {
    /**
     * Sanitize input string
     */
    function sanitize($str) {
        return htmlspecialchars(strip_tags(trim($str)), ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('get_pagination_params')) {
    /**
     * Extract pagination parameters from request
     */
    function get_pagination_params() {
        $start   = isset($_GET['start'])   ? max(0, (int)$_GET['start']) : 0;
        $perpage = isset($_GET['perpage'])  ? max(1, min(100, (int)$_GET['perpage'])) : PER_PAGE_DEFAULT;
        return [$start, $perpage];
    }
}