<?php

require_once __DIR__ . '/../db/db.php';

function e(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}

function old(string $key, string $default = ''): string
{
    return $_SESSION['old'][$key] ?? $default;
}

function flash(string $key, ?string $value = null): ?string
{
    if ($value !== null) {
        $_SESSION['flash'][$key] = $value;
        return null;
    }

    if (!isset($_SESSION['flash'][$key])) {
        return null;
    }

    $value = $_SESSION['flash'][$key];
    unset($_SESSION['flash'][$key]);

    return $value;
}

function redirect(string $path): void
{
    header('Location: ' . $path);
    exit;
}

function app_root_prefix(): string
{
    $scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
    $dir = trim(dirname($scriptName), '/\\');

    if ($dir === '' || $dir === '.') {
        return '';
    }

    $segments = array_values(array_filter(explode('/', str_replace('\\', '/', $dir)), static fn(string $part): bool => $part !== ''));

    if (count($segments) <= 1) {
        return '';
    }

    return str_repeat('../', count($segments) - 1);
}

function asset_url(string $path): string
{
    return app_root_prefix() . ltrim($path, '/');
}

function page_url(string $page, string $suffix = ''): string
{
    $page = trim($page, "/\\");
    $suffix = ltrim($suffix, '/\\');

    $url = app_root_prefix() . $page . '/' . $page . '.php';

    if ($suffix !== '') {
        $url .= '?' . $suffix;
    }

    return $url;
}

function route_url(string $path): string
{
    $path = ltrim($path, "/\\");

    return app_root_prefix() . $path;
}

function bind_params(mysqli_stmt $stmt, string $types, array &$params): void
{
    $bind = [$types];

    foreach ($params as $key => $value) {
        $bind[] = &$params[$key];
    }

    call_user_func_array([$stmt, 'bind_param'], $bind);
}

function fetch_one(string $sql, string $types = '', array $params = []): ?array
{
    $stmt = db()->prepare($sql);
    if (!$stmt) {
        return null;
    }

    if ($types !== '' && $params !== []) {
        bind_params($stmt, $types, $params);
    }

    if (!$stmt->execute()) {
        $stmt->close();
        return null;
    }

    $result = $stmt->get_result();
    $row = $result ? $result->fetch_assoc() : null;
    $stmt->close();

    return $row ?: null;
}

function fetch_all(string $sql, string $types = '', array $params = []): array
{
    $stmt = db()->prepare($sql);
    if (!$stmt) {
        return [];
    }

    if ($types !== '' && $params !== []) {
        bind_params($stmt, $types, $params);
    }

    if (!$stmt->execute()) {
        $stmt->close();
        return [];
    }

    $result = $stmt->get_result();
    $rows = [];

    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }
    }

    $stmt->close();
    return $rows;
}

function execute_query(string $sql, string $types = '', array $params = []): int
{
    $stmt = db()->prepare($sql);
    if (!$stmt) {
        return -1;
    }

    if ($types !== '' && $params !== []) {
        bind_params($stmt, $types, $params);
    }

    if (!$stmt->execute()) {
        $stmt->close();
        return -1;
    }

    $result = $stmt->insert_id > 0 ? $stmt->insert_id : $stmt->affected_rows;
    $stmt->close();

    return $result;
}

function current_user_id(): int
{
    $sessionUserId = (int) ($_SESSION['user_id'] ?? 0);
    if ($sessionUserId > 0) {
        return $sessionUserId;
    }

    $email = trim((string) ($_SESSION['user_email'] ?? $_SESSION['user'] ?? ''));
    $company = trim((string) ($_SESSION['user_company'] ?? ''));
    if ($email === '' && $company === '') {
        return 0;
    }

    $row = null;
    if ($email !== '') {
        $row = fetch_one(
            'SELECT id, email, business_name
             FROM users
             WHERE email = ? OR business_name = ? OR phone_number = ?
             ORDER BY id DESC
             LIMIT 1',
            'sss',
            [$email, $company, $email]
        );
    } elseif ($company !== '') {
        $row = fetch_one(
            'SELECT id, email, business_name
             FROM users
             WHERE business_name = ?
             ORDER BY id DESC
             LIMIT 1',
            's',
            [$company]
        );
    }

    if (!$row) {
        return 0;
    }

    $_SESSION['user_id'] = (int) $row['id'];

    if (trim((string) ($_SESSION['user_email'] ?? '')) === '' && trim((string) ($row['email'] ?? '')) !== '') {
        $_SESSION['user_email'] = (string) $row['email'];
    }

    if (trim((string) ($_SESSION['user_company'] ?? '')) === '' && trim((string) ($row['business_name'] ?? '')) !== '') {
        $_SESSION['user_company'] = (string) $row['business_name'];
    }

    return (int) $row['id'];
}
