<?php

/**
 * Helper Functions - دوال مساعدة
 */

use App\Core\CSRFProtection;

/**
 * Escape HTML output (XSS protection)
 */
function e(?string $value): string
{
    return htmlspecialchars($value ?? '', ENT_QUOTES, 'UTF-8');
}

/**
 * CSRF Token Field
 */
function csrf_field(): string
{
    return CSRFProtection::getTokenField();
}

/**
 * CSRF Token Value
 */
function csrf_token(): string
{
    return CSRFProtection::getTokenValue();
}

/**
 * Validate CSRF Token
 */
function csrf_validate(): bool
{
    return CSRFProtection::validatePostRequest();
}

/**
 * Tenant Condition Helper
 */
function tenant_condition(int $tenantId, string $tableAlias = 'o'): string
{
    return " AND {$tableAlias}.tenant_id = " . (int)$tenantId;
}

/**
 * Doctor Condition Helper
 */
function doctor_condition(int $doctorId, string $tableAlias = 'o'): string
{
    return " AND {$tableAlias}.doctor_id = " . (int)$doctorId;
}

/**
 * Format Currency
 */
function format_currency(float $amount, string $currency = 'IQD'): string
{
    $symbols = [
        'IQD' => 'د.ع',
        'USD' => '$',
        'EUR' => '€'
    ];
    
    $symbol = $symbols[$currency] ?? $currency;
    return number_format($amount, 2) . ' ' . $symbol;
}

/**
 * Format Date (Arabic)
 */
function format_date(?string $date, string $format = 'Y-m-d'): string
{
    if (empty($date)) {
        return '-';
    }
    
    try {
        $dt = new DateTime($date);
        return $dt->format($format);
    } catch (Exception $e) {
        return $date;
    }
}

/**
 * Format DateTime (Arabic)
 */
function format_datetime(?string $datetime, string $format = 'Y-m-d H:i'): string
{
    return format_date($datetime, $format);
}

/**
 * Time Ago (Arabic)
 */
function time_ago(?string $datetime): string
{
    if (empty($datetime)) {
        return '-';
    }
    
    try {
        $time = strtotime($datetime);
        $diff = time() - $time;
        
        if ($diff < 60) {
            return 'منذ لحظات';
        } elseif ($diff < 3600) {
            $minutes = floor($diff / 60);
            return "منذ {$minutes} دقيقة";
        } elseif ($diff < 86400) {
            $hours = floor($diff / 3600);
            return "منذ {$hours} ساعة";
        } elseif ($diff < 2592000) {
            $days = floor($diff / 86400);
            return "منذ {$days} يوم";
        } else {
            return format_date($datetime);
        }
    } catch (Exception $e) {
        return $datetime;
    }
}

/**
 * Sanitize Input
 */
function sanitize_input(string $input, int $flags = ENT_QUOTES): string
{
    return htmlspecialchars(trim($input), $flags, 'UTF-8');
}

/**
 * Sanitize URL
 */
function sanitize_url(string $url): string
{
    return filter_var($url, FILTER_SANITIZE_URL);
}

/**
 * Sanitize Email
 */
function sanitize_email(string $email): string
{
    return filter_var($email, FILTER_SANITIZE_EMAIL);
}

/**
 * Generate Random String
 */
function random_string(int $length = 32): string
{
    return bin2hex(random_bytes($length / 2));
}

/**
 * Check if request is AJAX
 */
function is_ajax(): bool
{
    return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
           strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
}

/**
 * JSON Response
 */
function json_response(array $data, int $statusCode = 200): void
{
    http_response_code($statusCode);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

/**
 * Redirect
 */
function redirect(string $url, int $statusCode = 302): void
{
    header("Location: {$url}", true, $statusCode);
    exit;
}

/**
 * Old Input (for form validation)
 */
function old(string $key, mixed $default = null): mixed
{
    return $_SESSION['_old_input'][$key] ?? $default;
}

/**
 * Flash Message
 */
function flash(string $key): ?string
{
    $message = $_SESSION["_flash_{$key}"] ?? null;
    if ($message !== null) {
        unset($_SESSION["_flash_{$key}"]);
    }
    return $message;
}

/**
 * Set Flash Message
 */
function flash_set(string $key, string $message): void
{
    $_SESSION["_flash_{$key}"] = $message;
}
