<?php
// app/Helpers/general.php - General Utility Functions

// Redirect to URL
function redirect($url) {
    header("Location: " . $url);
    exit;
}

// Flash message helper
function flash($key, $message = null, $type = 'info') {
    if ($message !== null) {
        $_SESSION['flash'][$key] = ['message' => $message, 'type' => $type];
    } else {
        $flash = $_SESSION['flash'][$key] ?? null;
        unset($_SESSION['flash'][$key]);
        return $flash;
    }
}

// In general.php - Replace the existing has_flash function
if (!function_exists('has_flash')) {
    function has_flash($key = null) {
        if ($key) {
            return isset($_SESSION['flash'][$key]);
        }
        return !empty($_SESSION['flash']);
    }
}

// Get old input (after validation error)
function old($key, $default = '') {
    $value = $_SESSION['old'][$key] ?? $default;
    if (isset($_POST[$key])) {
        return Security::escapeOutput($_POST[$key]);
    }
    return $value;
}

// Clear old input
function clearOld() {
    unset($_SESSION['old']);
}

// Set old input
function setOld($data) {
    $_SESSION['old'] = $data;
}

// Generate random string
function generate_token($length = 32) {
    return bin2hex(random_bytes($length / 2));
}

// Asset URL helper
function asset($path) {
    return APP_URL . '/public/assets/' . ltrim($path, '/');
}

// Upload URL helper
function upload($path) {
    if (empty($path)) {
        return asset('images/placeholder.png');
    }
    return APP_URL . '/public/uploads/' . ltrim($path, '/');
}

// URL helper for generating full URLs
function url($path) {
    if (empty($path)) {
        return APP_URL . '/';
    }
    return APP_URL . '/' . ltrim($path, '/');
}

// Get current URL
function current_url() {
    return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . 
           "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}

// Check if current URL matches
function is_current($url) {
    return strpos(current_url(), $url) !== false;
}

// Dump and die
function dd($data) {
    echo '<pre>';
    var_dump($data);
    echo '</pre>';
    die();
}

// Dump variable
function dump($data) {
    echo '<pre>';
    var_dump($data);
    echo '</pre>';
}

// Get user IP address
function get_ip() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        return $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    }
}

// Get user agent
function get_user_agent() {
    return $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
}

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

// Check if request is POST
function is_post() {
    return $_SERVER['REQUEST_METHOD'] === 'POST';
}

// Check if request is GET
function is_get() {
    return $_SERVER['REQUEST_METHOD'] === 'GET';
}

// JSON response
function json_response($data, $status_code = 200) {
    http_response_code($status_code);
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}

// Success JSON response
function json_success($message, $data = null) {
    json_response([
        'success' => true,
        'message' => $message,
        'data' => $data
    ]);
}

// Error JSON response
function json_error($message, $status_code = 400) {
    json_response([
        'success' => false,
        'message' => $message
    ], $status_code);
}

// Pagination helper
function paginate($total_items, $items_per_page, $current_page = 1) {
    $total_pages = ceil($total_items / $items_per_page);
    $current_page = max(1, min($current_page, $total_pages));
    $offset = ($current_page - 1) * $items_per_page;
    
    return [
        'total_items' => $total_items,
        'items_per_page' => $items_per_page,
        'total_pages' => $total_pages,
        'current_page' => $current_page,
        'offset' => $offset,
        'has_prev' => $current_page > 1,
        'has_next' => $current_page < $total_pages,
        'prev_page' => $current_page - 1,
        'next_page' => $current_page + 1
    ];
}

// Get pagination links
function pagination_links($pagination, $url) {
    if ($pagination['total_pages'] <= 1) {
        return '';
    }
    
    $html = '<ul class="pagination">';
    
    // Previous button
    if ($pagination['has_prev']) {
        $html .= '<li><a href="' . $url . '?page=' . $pagination['prev_page'] . '">&laquo; Previous</a></li>';
    } else {
        $html .= '<li class="disabled"><span>&laquo; Previous</span></li>';
    }
    
    // Page numbers
    for ($i = 1; $i <= $pagination['total_pages']; $i++) {
        if ($i == $pagination['current_page']) {
            $html .= '<li class="active"><span>' . $i . '</span></li>';
        } else {
            $html .= '<li><a href="' . $url . '?page=' . $i . '">' . $i . '</a></li>';
        }
    }
    
    // Next button
    if ($pagination['has_next']) {
        $html .= '<li><a href="' . $url . '?page=' . $pagination['next_page'] . '">Next &raquo;</a></li>';
    } else {
        $html .= '<li class="disabled"><span>Next &raquo;</span></li>';
    }
    
    $html .= '</ul>';
    
    return $html;
}

// Truncate string
function truncate($text, $length = 100, $suffix = '...') {
    if (strlen($text) <= $length) {
        return $text;
    }
    return substr($text, 0, $length) . $suffix;
}

// Slug generator
function generate_slug($text) {
    $text = preg_replace('~[^\pL\d]+~u', '-', $text);
    $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    $text = preg_replace('~[^-\w]+~', '', $text);
    $text = trim($text, '-');
    $text = preg_replace('~-+~', '-', $text);
    $text = strtolower($text);
    
    if (empty($text)) {
        return 'n-a';
    }
    
    return $text;
}

// Get config value
function config($key, $default = null) {
    return defined($key) ? constant($key) : $default;
}

// Check if development environment
function is_dev() {
    return defined('APP_DEBUG') && APP_DEBUG === true;
}

// Log message
function log_message($message, $type = 'info') {
    $log_file = STORAGE_PATH . '/logs/' . date('Y-m-d') . '.log';
    $timestamp = date('Y-m-d H:i:s');
    $log_entry = "[{$timestamp}] [{$type}] {$message}" . PHP_EOL;
    file_put_contents($log_file, $log_entry, FILE_APPEND);
}

// Get or set cache
function cache($key, $value = null, $ttl = 3600) {
    if (!ENABLE_CACHE) {
        return $value instanceof Closure ? $value() : $value;
    }
    
    $cache_file = STORAGE_PATH . '/cache/' . md5($key) . '.cache';
    
    // Get cache
    if ($value === null) {
        if (file_exists($cache_file)) {
            $data = unserialize(file_get_contents($cache_file));
            if (time() - $data['time'] < $ttl) {
                return $data['value'];
            }
            unlink($cache_file);
        }
        return null;
    }
    
    // Set cache
    $cache_data = [
        'time' => time(),
        'value' => $value instanceof Closure ? $value() : $value
    ];
    file_put_contents($cache_file, serialize($cache_data));
    return $cache_data['value'];
}

// Clear cache
function clear_cache($key = null) {
    $cache_dir = STORAGE_PATH . '/cache/';
    
    if ($key === null) {
        // Clear all cache
        $files = glob($cache_dir . '*.cache');
        foreach ($files as $file) {
            unlink($file);
        }
    } else {
        // Clear specific cache
        $cache_file = $cache_dir . md5($key) . '.cache';
        if (file_exists($cache_file)) {
            unlink($cache_file);
        }
    }
}


// =====================================================
// FLASH MESSAGE HELPERS
// =====================================================

/**
 * Escape output for HTML
 */
function esc($data) {
    if (is_array($data)) {
        return array_map('esc', $data);
    }
    return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
}


// =====================================================
// FORMATTING HELPERS
// =====================================================


/**
 * Format status badge
 */
function format_status_badge($status) {
    $badges = [
        'pending' => '<span class="badge bg-warning text-dark">Pending</span>',
        'confirmed' => '<span class="badge bg-info">Confirmed</span>',
        'approved' => '<span class="badge bg-success">Approved</span>',
        'rejected' => '<span class="badge bg-danger">Rejected</span>',
        'ongoing' => '<span class="badge bg-primary">Ongoing</span>',
        'completed' => '<span class="badge bg-success">Completed</span>',
        'cancelled' => '<span class="badge bg-secondary">Cancelled</span>',
        'active' => '<span class="badge bg-success">Active</span>',
        'inactive' => '<span class="badge bg-secondary">Inactive</span>',
        'suspended' => '<span class="badge bg-danger">Suspended</span>',
        'returned' => '<span class="badge bg-info">Returned</span>',
        'failed' => '<span class="badge bg-danger">Failed</span>'
    ];
    
    return $badges[strtolower($status)] ?? '<span class="badge bg-secondary">' . esc($status) . '</span>';
}

/**
 * Format payment badge
 */
function format_payment_badge($status) {
    $badges = [
        'pending' => '<span class="badge bg-warning text-dark">Payment Pending</span>',
        'paid' => '<span class="badge bg-success">Paid</span>',
        'refunded' => '<span class="badge bg-info">Refunded</span>',
        'processing' => '<span class="badge bg-primary">Processing</span>',
        'failed' => '<span class="badge bg-danger">Payment Failed</span>'
    ];
    
    return $badges[strtolower($status)] ?? '<span class="badge bg-secondary">' . esc($status) . '</span>';
}

// =====================================================
// PAGINATION HELPER
// =====================================================

/**
 * Render pagination links
 */
function render_pagination($current_page, $total_pages, $base_url, $params = []) {
    if ($total_pages <= 1) return '';
    
    $html = '<nav aria-label="Page navigation"><ul class="pagination justify-content-center">';
    
    // Previous button
    if ($current_page > 1) {
        $prev_params = array_merge($params, ['page' => $current_page - 1]);
        $html .= '<li class="page-item"><a class="page-link" href="' . $base_url . '?' . http_build_query($prev_params) . '">Previous</a></li>';
    } else {
        $html .= '<li class="page-item disabled"><span class="page-link">Previous</span></li>';
    }
    
    // Page numbers
    $start = max(1, $current_page - 2);
    $end = min($total_pages, $current_page + 2);
    
    if ($start > 1) {
        $first_params = array_merge($params, ['page' => 1]);
        $html .= '<li class="page-item"><a class="page-link" href="' . $base_url . '?' . http_build_query($first_params) . '">1</a></li>';
        if ($start > 2) {
            $html .= '<li class="page-item disabled"><span class="page-link">...</span></li>';
        }
    }
    
    for ($i = $start; $i <= $end; $i++) {
        $page_params = array_merge($params, ['page' => $i]);
        if ($i == $current_page) {
            $html .= '<li class="page-item active"><span class="page-link">' . $i . '</span></li>';
        } else {
            $html .= '<li class="page-item"><a class="page-link" href="' . $base_url . '?' . http_build_query($page_params) . '">' . $i . '</a></li>';
        }
    }
    
    if ($end < $total_pages) {
        if ($end < $total_pages - 1) {
            $html .= '<li class="page-item disabled"><span class="page-link">...</span></li>';
        }
        $last_params = array_merge($params, ['page' => $total_pages]);
        $html .= '<li class="page-item"><a class="page-link" href="' . $base_url . '?' . http_build_query($last_params) . '">' . $total_pages . '</a></li>';
    }
    
    // Next button
    if ($current_page < $total_pages) {
        $next_params = array_merge($params, ['page' => $current_page + 1]);
        $html .= '<li class="page-item"><a class="page-link" href="' . $base_url . '?' . http_build_query($next_params) . '">Next</a></li>';
    } else {
        $html .= '<li class="page-item disabled"><span class="page-link">Next</span></li>';
    }
    
    $html .= '</ul></nav>';
    
    return $html;
}

// =====================================================
// FILE HELPERS
// =====================================================

/**
 * Format bytes to human readable
 */
function format_bytes($bytes, $precision = 2) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    $bytes /= (1 << (10 * $pow));
    return round($bytes, $precision) . ' ' . $units[$pow];
}

/**
 * Get file extension
 */
function get_file_extension($filename) {
    return strtolower(pathinfo($filename, PATHINFO_EXTENSION));
}

/**
 * Check if file is image
 */
function is_image($filename) {
    $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    return in_array(get_file_extension($filename), $allowed);
}

// =====================================================
// ARRAY HELPERS
// =====================================================

/**
 * Get array value with default
 */
function array_get($array, $key, $default = null) {
    return $array[$key] ?? $default;
}

/**
 * Check if array has key
 */
function array_has($array, $key) {
    return isset($array[$key]);
}

/**
 * Log error to file
 */
function log_error($message, $context = []) {
    $log_file = __DIR__ . '/../../storage/logs/error.log';
    $timestamp = date('Y-m-d H:i:s');
    $context_str = !empty($context) ? ' | Context: ' . json_encode($context) : '';
    $log_message = "[{$timestamp}] ERROR: {$message}{$context_str}\n";
    
    if (!file_exists(dirname($log_file))) {
        mkdir(dirname($log_file), 0755, true);
    }
    
    file_put_contents($log_file, $log_message, FILE_APPEND);
}

/**
 * Log info to file
 */
function log_info($message, $context = []) {
    $log_file = __DIR__ . '/../../storage/logs/app.log';
    $timestamp = date('Y-m-d H:i:s');
    $context_str = !empty($context) ? ' | Context: ' . json_encode($context) : '';
    $log_message = "[{$timestamp}] INFO: {$message}{$context_str}\n";
    
    if (!file_exists(dirname($log_file))) {
        mkdir(dirname($log_file), 0755, true);
    }
    
    file_put_contents($log_file, $log_message, FILE_APPEND);
}

// =====================================================
// CACHE HELPERS (Simple file-based cache)
// =====================================================

/**
 * Get cached value
 */
function cache_get($key) {
    if (!ENABLE_CACHE) return null;
    
    $cache_file = __DIR__ . '/../../storage/cache/' . md5($key) . '.cache';
    
    if (!file_exists($cache_file)) {
        return null;
    }
    
    $data = unserialize(file_get_contents($cache_file));
    
    if ($data['expires'] < time()) {
        unlink($cache_file);
        return null;
    }
    
    return $data['value'];
}

/**
 * Set cached value
 */
function cache_set($key, $value, $ttl = 3600) {
    if (!ENABLE_CACHE) return false;
    
    $cache_dir = __DIR__ . '/../../storage/cache/';
    if (!file_exists($cache_dir)) {
        mkdir($cache_dir, 0755, true);
    }
    
    $cache_file = $cache_dir . md5($key) . '.cache';
    
    $data = [
        'value' => $value,
        'expires' => time() + $ttl
    ];
    
    return file_put_contents($cache_file, serialize($data)) !== false;
}

/**
 * Delete cached value
 */
function cache_delete($key) {
    $cache_file = __DIR__ . '/../../storage/cache/' . md5($key) . '.cache';
    
    if (file_exists($cache_file)) {
        return unlink($cache_file);
    }
    
    return false;
}

/**
 * Clear all cache
 */
function cache_clear() {
    $cache_dir = __DIR__ . '/../../storage/cache/';
    
    if (!is_dir($cache_dir)) {
        return true;
    }
    
    $files = glob($cache_dir . '*.cache');
    foreach ($files as $file) {
        if (is_file($file)) {
            unlink($file);
        }
    }
    
    return true;
}

// =====================================================
// MISCELLANEOUS HELPERS
// =====================================================

/**
 * Get client IP address
 */
function get_client_ip() {
    $ip = '';
    
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'] ?? '';
    }
    
    return $ip;
}

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

/**
 * Check if request is POST
 */
function is_post_request() {
    return $_SERVER['REQUEST_METHOD'] === 'POST';
}

/**
 * Check if request is GET
 */
function is_get_request() {
    return $_SERVER['REQUEST_METHOD'] === 'GET';
}

// =====================================================
// NAVIGATION & PAGE HELPERS
// =====================================================

/**
 * Check if current page is active
 */
function is_active_page($page_name) {
    $current_page = basename($_SERVER['PHP_SELF'], '.php');
    return $current_page === $page_name;
}

/**
 * Get favorites count for current user
 */
function get_favorites_count() {
    if (!Auth::check()) {
        return 0;
    }
    
    $db = Database::getInstance();
    $user_id = Auth::id();
    
    $sql = "SELECT COUNT(*) as count FROM favorites WHERE user_id = ?";
    $result = $db->fetch($sql, [$user_id]);
    
    return $result['count'] ?? 0;
}

/**
 * Get main categories for navigation
 */
function get_main_categories() {
    $db = Database::getInstance();
    
    $sql = "SELECT id, name, slug, icon, description 
            FROM categories 
            WHERE parent_id IS NULL 
            AND status = 'active' 
            ORDER BY sort_order ASC, name ASC 
            LIMIT 8";
    
    $categories = $db->fetchAll($sql);
    
    // If no categories in DB, return default ones
    if (empty($categories)) {
        return [
            ['id' => 1, 'name' => 'Electronics', 'slug' => 'electronics', 'icon' => 'fas fa-laptop', 'description' => 'Electronic devices and gadgets'],
            ['id' => 2, 'name' => 'Tools & Equipment', 'slug' => 'tools', 'icon' => 'fas fa-tools', 'description' => 'Professional tools and equipment'],
            ['id' => 3, 'name' => 'Furniture', 'slug' => 'furniture', 'icon' => 'fas fa-chair', 'description' => 'Home and office furniture'],
            ['id' => 4, 'name' => 'Party & Events', 'slug' => 'party', 'icon' => 'fas fa-birthday-cake', 'description' => 'Party supplies and equipment'],
            ['id' => 5, 'name' => 'Vehicles', 'slug' => 'vehicles', 'icon' => 'fas fa-car', 'description' => 'Cars, bikes and other vehicles'],
            ['id' => 6, 'name' => 'Photography', 'slug' => 'photography', 'icon' => 'fas fa-camera', 'description' => 'Cameras and photography equipment'],
            ['id' => 7, 'name' => 'Sports & Fitness', 'slug' => 'sports', 'icon' => 'fas fa-dumbbell', 'description' => 'Sports and fitness equipment'],
            ['id' => 8, 'name' => 'Home & Garden', 'slug' => 'home-garden', 'icon' => 'fas fa-home', 'description' => 'Home and garden items']
        ];
    }
    
    return $categories;
}


// app/Helpers/flash.php - Unified Flash Message System

if (!function_exists('flash')) {
    function flash($key, $message, $type = 'success') {
        if (!isset($_SESSION['flash'])) {
            $_SESSION['flash'] = [];
        }
        $_SESSION['flash'][$key] = [
            'message' => $message,
            'type' => $type
        ];
    }
}

if (!function_exists('has_flash')) {
    function has_flash($key = null) {
        if (!isset($_SESSION['flash'])) {
            return false;
        }
        if ($key !== null) {
            return isset($_SESSION['flash'][$key]);
        }
        return !empty($_SESSION['flash']);
    }
}

if (!function_exists('get_flash')) {
    function get_flash($key) {
        if (isset($_SESSION['flash'][$key])) {
            $flash = $_SESSION['flash'][$key];
            unset($_SESSION['flash'][$key]);
            return $flash;
        }
        return null;
    }
}

if (!function_exists('display_flash')) {
    function display_flash() {
        if (!empty($_SESSION['flash'])) {
            foreach ($_SESSION['flash'] as $key => $flash) {
                $type = $flash['type'];
                $message = $flash['message'];
                
                // Map alert types to Bootstrap classes
                $alertClass = [
                    'success' => 'alert-success',
                    'error' => 'alert-danger',
                    'warning' => 'alert-warning',
                    'info' => 'alert-info',
                    'danger' => 'alert-danger'
                ];
                
                $class = $alertClass[$type] ?? 'alert-info';
                
                echo "<div class='alert {$class} alert-dismissible fade show' role='alert'>";
                echo htmlspecialchars($message);
                echo "<button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>";
                echo "</div>";
            }
            // Clear all flash messages after displaying
            $_SESSION['flash'] = [];
        }
    }
}