<?php

$GLOBALS['app_currency_code'] = isset($GLOBALS['app_currency_code']) ? $GLOBALS['app_currency_code'] : 'NGN';
$GLOBALS['app_site_base_url'] = isset($GLOBALS['app_site_base_url']) ? $GLOBALS['app_site_base_url'] : null;

function app_url($page, array $params = array())
{
    $query = array_merge(array('page' => $page), $params);

    return '?' . http_build_query($query);
}

function app_redirect($page, array $params = array())
{
    header('Location: ' . app_url($page, $params));
    exit;
}

function app_set_currency($code)
{
    $code = strtoupper(trim((string) $code));

    if (! in_array($code, array('USD', 'NGN'), true)) {
        $code = 'NGN';
    }

    $GLOBALS['app_currency_code'] = $code;
}

function app_currency_code()
{
    return isset($GLOBALS['app_currency_code']) ? $GLOBALS['app_currency_code'] : 'NGN';
}

function app_currency_symbol()
{
    return app_currency_code() === 'NGN' ? '₦' : '$';
}

function app_currency($amount)
{
    return app_currency_symbol() . number_format((int) $amount);
}

function app_currency_text($value)
{
    if (is_int($value) || is_float($value) || (is_string($value) && is_numeric(trim($value)))) {
        return app_currency((int) $value);
    }

    $text = trim((string) $value);

    if ($text === '') {
        return '';
    }

    $amount = (int) preg_replace('/[^\d]/', '', $text);

    if ($amount === 0 && strpos($text, '0') === false) {
        return $text;
    }

    $lastDigitOffset = -1;
    $length = strlen($text);

    for ($index = $length - 1; $index >= 0; $index--) {
        if (ctype_digit($text[$index])) {
            $lastDigitOffset = $index;
            break;
        }
    }

    $suffix = '';

    if ($lastDigitOffset >= 0 && $lastDigitOffset < $length - 1) {
        $suffix = trim(substr($text, $lastDigitOffset + 1));
    }

    return app_currency($amount) . ($suffix !== '' ? $suffix : '');
}

function app_require_login($user)
{
    if (! $user) {
        app_redirect('login');
    }
}

function app_require_admin($user)
{
    if (! $user || ! isset($user['role']) || $user['role'] !== 'admin') {
        app_redirect('login');
    }
}

function app_public_base_path()
{
    $scriptName = isset($_SERVER['SCRIPT_NAME']) ? (string) $_SERVER['SCRIPT_NAME'] : '';
    $basePath = str_replace('\\', '/', dirname($scriptName));
    $basePath = rtrim($basePath, '/.');

    return $basePath === '' ? '' : $basePath;
}

function app_base_url()
{
    if (isset($GLOBALS['app_site_base_url']) && is_string($GLOBALS['app_site_base_url']) && trim($GLOBALS['app_site_base_url']) !== '') {
        return rtrim(trim($GLOBALS['app_site_base_url']), '/');
    }

    $isHttps = (
        (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== '' && strtolower((string) $_SERVER['HTTPS']) !== 'off')
        || (isset($_SERVER['SERVER_PORT']) && (string) $_SERVER['SERVER_PORT'] === '443')
    );
    $scheme = $isHttps ? 'https' : 'http';
    $host = isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] !== ''
        ? (string) $_SERVER['HTTP_HOST']
        : 'localhost';

    return $scheme . '://' . $host . app_public_base_path();
}

function app_set_site_base_url($url)
{
    $url = trim((string) $url);

    if ($url === '') {
        $GLOBALS['app_site_base_url'] = null;

        return;
    }

    $GLOBALS['app_site_base_url'] = rtrim($url, '/');
}

function app_absolute_url($path = '')
{
    $path = (string) $path;

    if ($path === '') {
        return rtrim(app_base_url(), '/') . '/';
    }

    if (preg_match('#^https?://#i', $path)) {
        return $path;
    }

    if (strpos($path, '?') === 0) {
        return rtrim(app_base_url(), '/') . '/' . $path;
    }

    if (strpos($path, '/') === 0) {
        return preg_replace('#^(https?://[^/]+).*$#', '$1', app_base_url()) . $path;
    }

    return rtrim(app_base_url(), '/') . '/' . ltrim($path, '/');
}

function app_slug($value)
{
    $slug = strtolower(trim((string) $value));
    $slug = preg_replace('/[^a-z0-9]+/', '-', $slug);
    $slug = trim((string) $slug, '-');

    return $slug !== '' ? $slug : 'listing';
}

function app_property_url(array $listing)
{
    $slugSource = isset($listing['title']) ? $listing['title'] : 'listing';

    if (isset($listing['location']) && trim((string) $listing['location']) !== '') {
        $slugSource .= ' ' . $listing['location'];
    }

    return app_url('property', array(
        'id' => isset($listing['id']) ? (int) $listing['id'] : 0,
        'slug' => app_slug($slugSource),
    ));
}

function app_property_absolute_url(array $listing)
{
    return app_absolute_url(app_property_url($listing));
}

function app_property_share_text(array $listing)
{
    $parts = array();

    if (isset($listing['title']) && trim((string) $listing['title']) !== '') {
        $parts[] = trim((string) $listing['title']);
    }

    if (isset($listing['price']) && trim((string) $listing['price']) !== '') {
        $parts[] = trim((string) $listing['price']);
    }

    if (isset($listing['location']) && trim((string) $listing['location']) !== '') {
        $parts[] = trim((string) $listing['location']);
    }

    if ($parts === array()) {
        return 'Check out this Sandworth Homes property';
    }

    return 'Check out ' . implode(' | ', $parts) . ' on Sandworth Homes';
}

function app_share_button_markup(array $listing)
{
    $title = isset($listing['title']) ? (string) $listing['title'] : 'Property';
    $shareUrl = app_property_absolute_url($listing);
    $shareText = app_property_share_text($listing);

    return sprintf(
        '<button type="button" class="share-button" data-share-title="%s" data-share-text="%s" data-share-url="%s" aria-label="Share %s" title="Share %s"><span class="share-button-icon" aria-hidden="true"><svg viewBox="0 0 24 24" focusable="false"><circle cx="18" cy="5" r="2.5"></circle><circle cx="6" cy="12" r="2.5"></circle><circle cx="18" cy="19" r="2.5"></circle><path d="M8.25 11l7-4"></path><path d="M8.25 13l7 4"></path></svg></span><span class="sr-only">Share %s</span></button>',
        htmlspecialchars($title, ENT_QUOTES, 'UTF-8'),
        htmlspecialchars($shareText, ENT_QUOTES, 'UTF-8'),
        htmlspecialchars($shareUrl, ENT_QUOTES, 'UTF-8'),
        htmlspecialchars($title, ENT_QUOTES, 'UTF-8'),
        htmlspecialchars($title, ENT_QUOTES, 'UTF-8'),
        htmlspecialchars($title, ENT_QUOTES, 'UTF-8')
    );
}

function app_meta_description($value, $limit = 160)
{
    $text = html_entity_decode(strip_tags((string) $value), ENT_QUOTES, 'UTF-8');
    $text = trim((string) preg_replace('/\s+/', ' ', $text));
    $limit = max(80, (int) $limit);

    if ($text === '' || strlen($text) <= $limit) {
        return $text;
    }

    $snippet = substr($text, 0, $limit + 1);
    $lastSpace = strrpos($snippet, ' ');

    if ($lastSpace !== false && $lastSpace > (int) floor($limit * 0.6)) {
        $snippet = substr($snippet, 0, $lastSpace);
    } else {
        $snippet = substr($snippet, 0, $limit);
    }

    return rtrim($snippet, " \t\n\r\0\x0B,.!?:;") . '...';
}

/**
 * Build a JSON-safe payload of listing pins for the Leaflet map layer.
 *
 * @param array $listings
 * @return string
 */
function app_map_payload(array $listings)
{
    $pins = array();

    foreach ($listings as $listing) {
        if (! isset($listing['lat'], $listing['lng']) || $listing['lat'] === '' || $listing['lng'] === '') {
            continue;
        }

        $pins[] = array(
            'id' => (int) $listing['id'],
            'lat' => (float) $listing['lat'],
            'lng' => (float) $listing['lng'],
            'title' => (string) $listing['title'],
            'price' => (string) $listing['price'],
            'location' => (string) $listing['location'],
            'image' => (string) $listing['image'],
            'url' => app_property_url($listing),
        );
    }

    return htmlspecialchars(json_encode($pins), ENT_QUOTES, 'UTF-8');
}
