<?php
/**
 * ============================================================
 * HELPER FUNCTIONS
 * ============================================================
 * Common utility functions used throughout the application
 */

/**
 * Sanitize input string
 * @param string|null $input
 * @return string
 */
function sanitize(?string $input): string {
    if ($input === null) return '';
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

/**
 * Sanitize array of inputs
 * @param array $inputs
 * @return array
 */
function sanitizeArray(array $inputs): array {
    return array_map(function($value) {
        return is_string($value) ? sanitize($value) : $value;
    }, $inputs);
}

/**
 * Format price with Taka symbol (৳)
 * @param float|int $amount
 * @param bool $showSymbol
 * @return string
 */
function formatPrice($amount, bool $showSymbol = true): string {
    $formatted = number_format((float)$amount, 2);
    return $showSymbol ? CURRENCY_SYMBOL . ' ' . $formatted : $formatted;
}

/**
 * Format date for display
 * @param string $date
 * @param string $format
 * @return string
 */
function formatDate(string $date, string $format = 'd M, Y'): string {
    return date($format, strtotime($date));
}

/**
 * Format datetime for display
 * @param string $datetime
 * @param string $format
 * @return string
 */
function formatDateTime(string $datetime, string $format = 'd M, Y h:i A'): string {
    return date($format, strtotime($datetime));
}

/**
 * Generate a random string
 * @param int $length
 * @return string
 */
function generateRandomString(int $length = 32): string {
    return bin2hex(random_bytes($length / 2));
}

/**
 * Generate unique order number
 * Format: SMH-YYYYMMDD-XXXX
 * @return string
 */
function generateOrderNumber(): string {
    $date = date('Ymd');
    $random = strtoupper(substr(uniqid(), -4));
    return "SMH-{$date}-{$random}";
}

/**
 * Generate slug from string
 * @param string $string
 * @return string
 */
function generateSlug(string $string): string {
    // Convert to lowercase
    $slug = strtolower($string);
    // Replace non-alphanumeric with hyphens
    $slug = preg_replace('/[^a-z0-9\-]/', '-', $slug);
    // Remove multiple consecutive hyphens
    $slug = preg_replace('/-+/', '-', $slug);
    // Trim hyphens from ends
    return trim($slug, '-');
}

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

/**
 * Check if request method is POST
 * @return bool
 */
function isPost(): bool {
    return $_SERVER['REQUEST_METHOD'] === 'POST';
}

/**
 * Check if request method is GET
 * @return bool
 */
function isGet(): bool {
    return $_SERVER['REQUEST_METHOD'] === 'GET';
}

/**
 * Get POST value safely
 * @param string $key
 * @param mixed $default
 * @return mixed
 */
function post(string $key, $default = null) {
    return $_POST[$key] ?? $default;
}

/**
 * Get GET value safely
 * @param string $key
 * @param mixed $default
 * @return mixed
 */
function get(string $key, $default = null) {
    return $_GET[$key] ?? $default;
}

/**
 * Get session value safely
 * @param string $key
 * @param mixed $default
 * @return mixed
 */
function session(string $key, $default = null) {
    return $_SESSION[$key] ?? $default;
}

/**
 * Set session value
 * @param string $key
 * @param mixed $value
 */
function setSession(string $key, $value): void {
    $_SESSION[$key] = $value;
}

/**
 * Remove session value
 * @param string $key
 */
function unsetSession(string $key): void {
    unset($_SESSION[$key]);
}

/**
 * Check if user is logged in
 * @return bool
 */
function isLoggedIn(): bool {
    return !empty($_SESSION['user_id']);
}

/**
 * Check if admin is logged in
 * @return bool
 */
function isAdminLoggedIn(): bool {
    return !empty($_SESSION['admin_id']);
}

/**
 * Get logged in user ID
 * @return int|null
 */
function getUserId(): ?int {
    return $_SESSION['user_id'] ?? null;
}

/**
 * Get logged in admin ID
 * @return int|null
 */
function getAdminId(): ?int {
    return $_SESSION['admin_id'] ?? null;
}

/**
 * Get current session ID for cart
 * @return string
 */
function getCartSessionId(): string {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    return session_id();
}

/**
 * Redirect to URL
 * @param string $url
 */
function redirect(string $url): void {
    header("Location: {$url}");
    exit;
}

/**
 * Get primary product image or placeholder
 * @param array $images
 * @return string
 */
function getProductImage(array $images): string {
    foreach ($images as $img) {
        if (!empty($img['is_primary'])) {
            return UPLOADS_URL . '/products/' . $img['file_path'];
        }
    }
    // Return first image or placeholder
    if (!empty($images[0]['file_path'])) {
        return UPLOADS_URL . '/products/' . $images[0]['file_path'];
    }
    return ASSETS_URL . '/img/no-image.png';
}

/**
 * Get order status badge class
 * @param string $status
 * @return string
 */
function getOrderStatusBadge(string $status): string {
    $badges = [
        'Pending'    => 'bg-warning text-dark',
        'Processing' => 'bg-info text-white',
        'Shipped'    => 'bg-primary',
        'Delivered'  => 'bg-success',
        'Cancelled'  => 'bg-danger'
    ];
    return $badges[$status] ?? 'bg-secondary';
}

/**
 * Get payment status badge class
 * @param string $status
 * @return string
 */
function getPaymentStatusBadge(string $status): string {
    $badges = [
        'Unpaid'    => 'bg-danger',
        'Submitted' => 'bg-warning text-dark',
        'Verified'  => 'bg-success',
        'Rejected'  => 'bg-dark'
    ];
    return $badges[$status] ?? 'bg-secondary';
}

/**
 * Truncate text with ellipsis
 * @param string $text
 * @param int $length
 * @return string
 */
function truncate(string $text, int $length = 100): string {
    if (mb_strlen($text) <= $length) {
        return $text;
    }
    return mb_substr($text, 0, $length) . '...';
}

/**
 * Calculate cart totals
 * @param array $items Cart items with qty and unit_price
 * @param float|null $discountAmount
 * @return array
 */
function calculateCartTotals(array $items, ?float $discountAmount = 0): array {
    $subtotal = 0;
    foreach ($items as $item) {
        $subtotal += $item['qty'] * $item['unit_price'];
    }
    
    $vatAmount = $subtotal * (VAT_PERCENT / 100);
    $taxAmount = $subtotal * (TAX_PERCENT / 100);
    $discountAmount = $discountAmount ?? 0;
    $grandTotal = $subtotal + $vatAmount + $taxAmount - $discountAmount;
    
    return [
        'subtotal'        => round($subtotal, 2),
        'vat_percent'     => VAT_PERCENT,
        'vat_amount'      => round($vatAmount, 2),
        'tax_amount'      => round($taxAmount, 2),
        'discount_amount' => round($discountAmount, 2),
        'grand_total'     => round($grandTotal, 2)
    ];
}

/**
 * Log error to file
 * @param string $message
 * @param array $context
 */
function logError(string $message, array $context = []): void {
    $logFile = STORAGE_PATH . '/logs/error.log';
    $timestamp = date('Y-m-d H:i:s');
    $contextStr = !empty($context) ? json_encode($context) : '';
    $logMessage = "[{$timestamp}] {$message} {$contextStr}\n";
    
    // Create log directory if not exists
    $logDir = dirname($logFile);
    if (!is_dir($logDir)) {
        mkdir($logDir, 0755, true);
    }
    
    file_put_contents($logFile, $logMessage, FILE_APPEND | LOCK_EX);
}

/**
 * Flash message helpers
 */
function setFlash(string $type, string $message): void {
    $_SESSION['flash'] = ['type' => $type, 'message' => $message];
}

function getFlash(): ?array {
    $flash = $_SESSION['flash'] ?? null;
    unset($_SESSION['flash']);
    return $flash;
}

function hasFlash(): bool {
    return isset($_SESSION['flash']);
}

/**
 * Asset URL helper
 * @param string $path
 * @return string
 */
function asset(string $path): string {
    return ASSETS_URL . '/' . ltrim($path, '/');
}

/**
 * Public URL helper
 * @param string $path
 * @return string
 */
function url(string $path = ''): string {
    return SITE_URL . '/' . ltrim($path, '/');
}

/**
 * Admin URL helper
 * @param string $path
 * @return string
 */
function adminUrl(string $path = ''): string {
    return ADMIN_URL . '/' . ltrim($path, '/');
}
