<?php
declare(strict_types=1);

/**
 * Pure Chemical Admin - Common Functions
 *
 * File:
 * admin/includes/functions.php
 */


/*
|--------------------------------------------------------------------------
| Escape HTML
|--------------------------------------------------------------------------
*/

if (!function_exists('e')) {
    function e(mixed $value): string
    {
        return htmlspecialchars(
            (string) $value,
            ENT_QUOTES | ENT_SUBSTITUTE,
            'UTF-8'
        );
    }
}


/*
|--------------------------------------------------------------------------
| Redirect
|--------------------------------------------------------------------------
*/

if (!function_exists('redirect')) {
    function redirect(string $url): never
    {
        header('Location: ' . $url);
        exit;
    }
}


/*
|--------------------------------------------------------------------------
| Current Request Method
|--------------------------------------------------------------------------
*/

if (!function_exists('requestMethod')) {
    function requestMethod(): string
    {
        return strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
    }
}


/*
|--------------------------------------------------------------------------
| Is POST Request
|--------------------------------------------------------------------------
*/

if (!function_exists('isPost')) {
    function isPost(): bool
    {
        return requestMethod() === 'POST';
    }
}


/*
|--------------------------------------------------------------------------
| POST Value
|--------------------------------------------------------------------------
*/

if (!function_exists('post')) {
    function post(
        string $key,
        mixed $default = null
    ): mixed {
        return $_POST[$key] ?? $default;
    }
}


/*
|--------------------------------------------------------------------------
| GET Value
|--------------------------------------------------------------------------
*/

if (!function_exists('get')) {
    function get(
        string $key,
        mixed $default = null
    ): mixed {
        return $_GET[$key] ?? $default;
    }
}


/*
|--------------------------------------------------------------------------
| Integer Input
|--------------------------------------------------------------------------
*/

if (!function_exists('inputInt')) {
    function inputInt(
        mixed $value,
        int $default = 0
    ): int {
        if ($value === null || $value === '') {
            return $default;
        }

        return (int) $value;
    }
}


/*
|--------------------------------------------------------------------------
| String Input
|--------------------------------------------------------------------------
*/

if (!function_exists('inputString')) {
    function inputString(
        mixed $value,
        string $default = ''
    ): string {
        if ($value === null) {
            return $default;
        }

        return trim((string) $value);
    }
}


/*
|--------------------------------------------------------------------------
| Flash Message
|--------------------------------------------------------------------------
*/

if (!function_exists('setFlash')) {
    function setFlash(
        string $type,
        string $message
    ): void {

        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        $_SESSION['_flash'] = [
            'type'    => $type,
            'message' => $message,
        ];
    }
}


/*
|--------------------------------------------------------------------------
| Get Flash Message
|--------------------------------------------------------------------------
*/

if (!function_exists('getFlash')) {
    function getFlash(): ?array
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        if (empty($_SESSION['_flash'])) {
            return null;
        }

        $flash = $_SESSION['_flash'];

        unset($_SESSION['_flash']);

        return $flash;
    }
}


/*
|--------------------------------------------------------------------------
| Success Message
|--------------------------------------------------------------------------
*/

if (!function_exists('flashSuccess')) {
    function flashSuccess(string $message): void
    {
        setFlash('success', $message);
    }
}


/*
|--------------------------------------------------------------------------
| Error Message
|--------------------------------------------------------------------------
*/

if (!function_exists('flashError')) {
    function flashError(string $message): void
    {
        setFlash('error', $message);
    }
}


/*
|--------------------------------------------------------------------------
| Warning Message
|--------------------------------------------------------------------------
*/

if (!function_exists('flashWarning')) {
    function flashWarning(string $message): void
    {
        setFlash('warning', $message);
    }
}


/*
|--------------------------------------------------------------------------
| Info Message
|--------------------------------------------------------------------------
*/

if (!function_exists('flashInfo')) {
    function flashInfo(string $message): void
    {
        setFlash('info', $message);
    }
}


/*
|--------------------------------------------------------------------------
| Old Form Value
|--------------------------------------------------------------------------
*/

if (!function_exists('old')) {
    function old(
        string $key,
        mixed $default = ''
    ): mixed {

        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        return $_SESSION['_old'][$key]
            ?? $default;
    }
}


/*
|--------------------------------------------------------------------------
| Store Old Form Values
|--------------------------------------------------------------------------
*/

if (!function_exists('storeOldInput')) {
    function storeOldInput(array $data): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        $_SESSION['_old'] = $data;
    }
}


/*
|--------------------------------------------------------------------------
| Clear Old Form Values
|--------------------------------------------------------------------------
*/

if (!function_exists('clearOldInput')) {
    function clearOldInput(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        unset($_SESSION['_old']);
    }
}


/*
|--------------------------------------------------------------------------
| Status Badge Class
|--------------------------------------------------------------------------
*/

if (!function_exists('statusClass')) {
    function statusClass(
        mixed $status
    ): string {
        return ((int) $status === 1)
            ? 'status-active'
            : 'status-inactive';
    }
}


/*
|--------------------------------------------------------------------------
| Status Text
|--------------------------------------------------------------------------
*/

if (!function_exists('statusText')) {
    function statusText(
        mixed $status
    ): string {
        return ((int) $status === 1)
            ? 'Active'
            : 'Inactive';
    }
}


/*
|--------------------------------------------------------------------------
| Date Formatting
|--------------------------------------------------------------------------
*/

if (!function_exists('formatDate')) {
    function formatDate(
        mixed $date,
        string $format = 'd M Y'
    ): string {

        if (empty($date)) {
            return '-';
        }

        try {
            return (new DateTime((string) $date))
                ->format($format);
        } catch (Throwable) {
            return '-';
        }
    }
}


/*
|--------------------------------------------------------------------------
| Date Time Formatting
|--------------------------------------------------------------------------
*/

if (!function_exists('formatDateTime')) {
    function formatDateTime(
        mixed $date
    ): string {
        return formatDate(
            $date,
            'd M Y, h:i A'
        );
    }
}


/*
|--------------------------------------------------------------------------
| Generate Slug
|--------------------------------------------------------------------------
*/

if (!function_exists('slugify')) {
    function slugify(string $text): string
    {
        $text = trim($text);

        if ($text === '') {
            return '';
        }

        $text = strtolower($text);

        $text = preg_replace(
            '/[^a-z0-9]+/',
            '-',
            $text
        ) ?? '';

        $text = trim(
            $text,
            '-'
        );

        return $text;
    }
}


/*
|--------------------------------------------------------------------------
| Ensure Unique Slug
|--------------------------------------------------------------------------
|
| $table and $column should only be passed from trusted
| application code, never directly from user input.
|
*/

if (!function_exists('uniqueSlug')) {
    function uniqueSlug(
        PDO $pdo,
        string $table,
        string $column,
        string $slug,
        ?int $excludeId = null
    ): string {

        $slug = slugify($slug);

        if ($slug === '') {
            $slug = 'item';
        }

        $original = $slug;
        $counter = 1;

        /*
         * Basic identifier validation.
         */
        if (
            !preg_match(
                '/^[a-zA-Z0-9_]+$/',
                $table
            )
            || !preg_match(
                '/^[a-zA-Z0-9_]+$/',
                $column
            )
        ) {
            throw new InvalidArgumentException(
                'Invalid database identifier.'
            );
        }

        while (true) {

            $sql = "
                SELECT COUNT(*)
                FROM `{$table}`
                WHERE `{$column}` = :slug
            ";

            $params = [
                ':slug' => $slug,
            ];

            if ($excludeId !== null) {
                $sql .= " AND id != :exclude_id";

                $params[':exclude_id'] = $excludeId;
            }

            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);

            $exists = (int) $stmt->fetchColumn();

            if ($exists === 0) {
                return $slug;
            }

            $counter++;

            $slug = $original . '-' . $counter;
        }
    }
}


/*
|--------------------------------------------------------------------------
| Safe JSON Decode
|--------------------------------------------------------------------------
*/

if (!function_exists('decodeJson')) {
    function decodeJson(
        mixed $value,
        mixed $default = null
    ): mixed {

        if (!is_string($value) || trim($value) === '') {
            return $default;
        }

        try {
            return json_decode(
                $value,
                true,
                512,
                JSON_THROW_ON_ERROR
            );
        } catch (JsonException) {
            return $default;
        }
    }
}


/*
|--------------------------------------------------------------------------
| JSON Response
|--------------------------------------------------------------------------
*/

if (!function_exists('jsonResponse')) {
    function jsonResponse(
        array $data,
        int $statusCode = 200
    ): never {

        http_response_code($statusCode);

        header(
            'Content-Type: application/json; charset=utf-8'
        );

        echo json_encode(
            $data,
            JSON_UNESCAPED_UNICODE
            | JSON_UNESCAPED_SLASHES
        );

        exit;
    }
}


/*
|--------------------------------------------------------------------------
| Success JSON Response
|--------------------------------------------------------------------------
*/

if (!function_exists('jsonSuccess')) {
    function jsonSuccess(
        string $message,
        array $extra = []
    ): never {

        jsonResponse(
            array_merge(
                [
                    'success' => true,
                    'message' => $message,
                ],
                $extra
            )
        );
    }
}


/*
|--------------------------------------------------------------------------
| Error JSON Response
|--------------------------------------------------------------------------
*/

if (!function_exists('jsonError')) {
    function jsonError(
        string $message,
        int $statusCode = 400,
        array $extra = []
    ): never {

        jsonResponse(
            array_merge(
                [
                    'success' => false,
                    'message' => $message,
                ],
                $extra
            ),
            $statusCode
        );
    }
}


/*
|--------------------------------------------------------------------------
| Checkbox Value
|--------------------------------------------------------------------------
*/

if (!function_exists('checkboxValue')) {
    function checkboxValue(
        mixed $value
    ): int {
        return (
            isset($value)
            && (
                $value === '1'
                || $value === 1
                || $value === true
                || $value === 'on'
            )
        ) ? 1 : 0;
    }
}


/*
|--------------------------------------------------------------------------
| Selected Helper
|--------------------------------------------------------------------------
*/

if (!function_exists('selected')) {
    function selected(
        mixed $current,
        mixed $value
    ): string {
        return ((string) $current === (string) $value)
            ? ' selected'
            : '';
    }
}


/*
|--------------------------------------------------------------------------
| Checked Helper
|--------------------------------------------------------------------------
*/

if (!function_exists('checked')) {
    function checked(
        mixed $value
    ): string {
        return (
            $value === true
            || $value === 1
            || $value === '1'
            || $value === 'on'
        )
            ? ' checked'
            : '';
    }
}


/*
|--------------------------------------------------------------------------
| Current Admin URL
|--------------------------------------------------------------------------
*/

if (!function_exists('currentAdminUrl')) {
    function currentAdminUrl(): string
    {
        $uri = $_SERVER['REQUEST_URI'] ?? '/admin/index.php';

        return htmlspecialchars(
            $uri,
            ENT_QUOTES | ENT_SUBSTITUTE,
            'UTF-8'
        );
    }
}


/*
|--------------------------------------------------------------------------
| Current Admin Page
|--------------------------------------------------------------------------
*/

if (!function_exists('currentAdminPage')) {
    function currentAdminPage(): string
    {
        return basename(
            $_SERVER['PHP_SELF'] ?? ''
        );
    }
}