<?php
/**
 * Admin helper functions
 */

/**
 * Get order status CSS class
 * 
 * @param string $status Order status
 * @return string CSS class
 */
function get_order_status_class($status) {
    switch ($status) {
        case 'pending':
            return 'warning';
        case 'processing':
            return 'info';
        case 'shipped':
            return 'primary';
        case 'delivered':
            return 'success';
        case 'canceled':
            return 'danger';
        default:
            return 'secondary';
    }
}

/**
 * Get product status CSS class
 * 
 * @param string $status Product status
 * @return string CSS class
 */
function get_product_status_class($status) {
    switch ($status) {
        case 'active':
            return 'success';
        case 'inactive':
            return 'warning';
        case 'draft':
            return 'secondary';
        default:
            return 'info';
    }
}

/**
 * Format date
 * 
 * @param string $date Date string
 * @param string $format Date format
 * @return string Formatted date
 */
function format_date($date, $format = 'd.m.Y.') {
    return date($format, strtotime($date));
}

/**
 * Generate random password
 * 
 * @param int $length Password length
 * @return string Random password
 */
function generate_password($length = 12) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+';
    $password = '';
    
    for ($i = 0; $i < $length; $i++) {
        $password .= $chars[rand(0, strlen($chars) - 1)];
    }
    
    return $password;
}

/**
 * Check if current user has permission
 * 
 * @param string $permission Permission to check
 * @return bool True if user has permission, false otherwise
 */
function has_permission($permission) {
    // For now, all admin users have all permissions
    return is_admin();
}

/**
 * Process image upload
 * 
 * @param array $file File array from $_FILES
 * @param string $destination Destination directory
 * @return array Upload result
 */
function process_image_upload($file, $destination) {
    // Check if file was uploaded without errors
    if ($file['error'] !== UPLOAD_ERR_OK) {
        return [
            'success' => false,
            'message' => 'File upload error: ' . $file['error']
        ];
    }
    
    // Check file size (max 5MB)
    if ($file['size'] > 5242880) {
        return [
            'success' => false,
            'message' => 'File too large. Maximum size is 5MB.'
        ];
    }
    
    // Check file type
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    if (!in_array($file['type'], $allowed_types)) {
        return [
            'success' => false,
            'message' => 'Invalid file type. Allowed types: JPEG, PNG, GIF, WEBP.'
        ];
    }
    
    // Create destination directory if it doesn't exist
    if (!is_dir($destination)) {
        mkdir($destination, 0755, true);
    }
    
    // Generate unique filename
    $file_extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = uniqid() . '.' . $file_extension;
    $filepath = $destination . '/' . $filename;
    
    // Move uploaded file
    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        return [
            'success' => true,
            'filename' => $filename,
            'path' => $filepath
        ];
    } else {
        return [
            'success' => false,
            'message' => 'Failed to move uploaded file.'
        ];
    }
}

/**
 * Generate nested categories array
 * 
 * @param array $categories All categories
 * @param int $parent_id Parent category ID
 * @return array Nested categories
 */
function generate_nested_categories($categories, $parent_id = null) {
    $result = [];
    
    foreach ($categories as $category) {
        if ($category['parent_id'] == $parent_id) {
            $category['children'] = generate_nested_categories($categories, $category['id']);
            $result[] = $category;
        }
    }
    
    return $result;
}

/**
 * Parse specifications string into array
 * 
 * @param string $specifications Specifications string
 * @return array Specifications array
 */
function parse_specifications($specifications) {
    $specs = [];
    $lines = explode("\n", $specifications);
    
    foreach ($lines as $line) {
        $line = trim($line);
        if (empty($line)) {
            continue;
        }
        
        $parts = explode(':', $line, 2);
        if (count($parts) === 2) {
            $name = trim($parts[0]);
            $value = trim($parts[1]);
            
            $specs[] = [
                'name' => $name,
                'value' => $value
            ];
        }
    }
    
    return $specs;
}

/**
 * Format specifications array as string
 * 
 * @param array $specifications Specifications array
 * @return string Specifications string
 */
function format_specifications($specifications) {
    if (empty($specifications)) {
        return '';
    }
    
    if (is_string($specifications)) {
        return $specifications;
    }
    
    if (is_array($specifications)) {
        $specs_array = json_decode($specifications, true);
        if (is_array($specs_array)) {
            $lines = [];
            foreach ($specs_array as $spec) {
                if (isset($spec['name']) && isset($spec['value'])) {
                    $lines[] = $spec['name'] . ': ' . $spec['value'];
                }
            }
            return implode("\n", $lines);
        }
    }
    
    return '';
}



if (!function_exists('get_order_status_name')) {
    /**
     * Get order status name
     * 
     * @param string $status Order status
     * @return string Status name
     */
    function get_order_status_name($status) {
        switch ($status) {
            case 'pending':
                return 'Na čekanju';
            case 'processing':
                return 'U obradi';
            case 'shipped':
                return 'Poslato';
            case 'delivered':
                return 'Isporučeno';
            case 'canceled':
                return 'Otkazano';
            default:
                return ucfirst($status);
        }
    }
}


if (!function_exists('format_price')) {
    /**
     * Format price
     * 
     * @param float $price Price
     * @param bool $with_currency Include currency symbol
     * @return string Formatted price
     */
    function format_price($price, $with_currency = true) {
        if ($with_currency) {
            return number_format($price, 2, ',', '.') . ' RSD';
        } else {
            return number_format($price, 2, ',', '.');
        }
    }
}


/**
 * Prikazuje sve flash poruke
 */
function display_flash_messages() {
    if (isset($_SESSION['flash_messages']) && !empty($_SESSION['flash_messages'])) {
        foreach ($_SESSION['flash_messages'] as $type => $messages) {
            foreach ($messages as $message) {
                echo '<div class="alert alert-' . $type . ' alert-dismissible">';
                echo '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
                echo $message;
                echo '</div>';
            }
        }
        // Obrišite poruke nakon prikazivanja
        unset($_SESSION['flash_messages']);
    }
}

/**
 * Postavlja flash poruku
 * 
 * @param string $type Tip poruke (success, error, warning, info)
 * @param string $message Tekst poruke
 */
function set_flash_message($type, $message) {
    if (!isset($_SESSION['flash_messages'])) {
        $_SESSION['flash_messages'] = [];
    }
    
    // Konvertujte 'error' u 'danger' za Bootstrap
    if ($type === 'error') {
        $type = 'danger';
    }
    
    if (!isset($_SESSION['flash_messages'][$type])) {
        $_SESSION['flash_messages'][$type] = [];
    }
    
    $_SESSION['flash_messages'][$type][] = $message;
}


/**
 * Vraća naziv načina plaćanja na srpskom
 * 
 * @param string $payment_method Kod načina plaćanja
 * @return string Naziv načina plaćanja na srpskom
 */
function get_payment_method_name($payment_method) {
    $payment_methods = [
        'cash' => 'Gotovinom',
        'bank' => 'Po predračunu',
        'card' => 'Platnom karticom',
        'paypal' => 'PayPal',
        'cod' => 'Pouzećem'
    ];
    
    return isset($payment_methods[$payment_method]) ? $payment_methods[$payment_method] : ucfirst($payment_method);
}


/**
 * Vraća naziv načina dostave na srpskom
 * 
 * @param string $shipping_method Kod načina dostave
 * @return string Naziv načina dostave na srpskom
 */
function get_shipping_method_name($shipping_method) {
    $shipping_methods = [
        'pickup' => 'Lično preuzimanje',
        'courier' => 'Kurirska služba',
        'post' => 'Poštom'
    ];
    
    return isset($shipping_methods[$shipping_method]) ? $shipping_methods[$shipping_method] : ucfirst($shipping_method);
}

