<?php
// Function to check if user is logged in
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

// Function to check if user is admin
function isAdmin() {
    return isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
}

// Function to require admin access (redirects if not admin)
function requireAdmin() {
    if (!isLoggedIn()) {
        $_SESSION['redirect_after_login'] = $_SERVER['REQUEST_URI'];
        redirect(SITE_URL . '/auth/login.php');
    }
    
    if (!isAdmin()) {
        // Redirect to home page with access denied message
        $_SESSION['error_message'] = "Access denied. You do not have permission to access this page.";
        redirect(SITE_URL . '/index.php');
    }
}

// Function to redirect user
function redirect($url) {
    header("Location: $url");
    exit();
}

// Function to sanitize input
function sanitizeInput($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

// Function to hash password
function hashPassword($password) {
    return password_hash($password, PASSWORD_DEFAULT);
}

// Function to verify password
function verifyPassword($password, $hash) {
    return password_verify($password, $hash);
}

// Function to get user by email
function getUserByEmail($pdo, $email) {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->execute([$email]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

// Function to get user by ID
function getUserById($pdo, $id) {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$id]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

// Function to get all products
function getAllProducts($pdo) {
    $stmt = $pdo->query("SELECT * FROM products ORDER BY created_at DESC");
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Function to get product by ID
function getProductById($pdo, $id) {
    // Check if PDO is valid
    if (!$pdo) {
        return false;
    }
    
    try {
        $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        error_log("Error in getProductById: " . $e->getMessage());
        return false;
    }
}

// Function to get products by category
function getProductsByCategory($pdo, $category) {
    $stmt = $pdo->prepare("SELECT * FROM products WHERE category = ? ORDER BY created_at DESC");
    $stmt->execute([$category]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Function to get distinct categories with images
function getCategories($pdo) {
    try {
        // First try to get categories with images
        $stmt = $pdo->query("SELECT DISTINCT category, category_image FROM products WHERE category IS NOT NULL AND category != ''");
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        // If that fails, fall back to just categories
        $stmt = $pdo->query("SELECT DISTINCT category, NULL as category_image FROM products WHERE category IS NOT NULL AND category != ''");
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

// Function to translate category names to Arabic
function translateCategoryToArabic($category) {
    $translations = [
        'Electronics' => 'إلكترونيات',
        'Clothing' => 'ملابس',
        'Sports' => 'رياضة',
        'Books' => 'كتب',
        'Home & Garden' => 'المنزل والحديقة'
    ];
    
    return isset($translations[$category]) ? $translations[$category] : $category;
}

// Function to get favorite products for a user
function getFavoriteProducts($pdo, $user_id) {
    // Check if PDO is valid
    if (!$pdo) {
        return [];
    }
    
    try {
        $stmt = $pdo->prepare("
            SELECT p.* 
            FROM favorites f 
            JOIN products p ON f.product_id = p.id 
            WHERE f.user_id = ? 
            ORDER BY f.created_at DESC
        ");
        $stmt->execute([$user_id]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        // Return empty array if there's an error
        error_log("Error in getFavoriteProducts: " . $e->getMessage());
        return [];
    }
}

// Function to check if a product is favorited by a user
function isProductFavorited($pdo, $user_id, $product_id) {
    // Check if PDO is valid
    if (!$pdo) {
        return false;
    }
    
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM favorites WHERE user_id = ? AND product_id = ?");
        $stmt->execute([$user_id, $product_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result['count'] > 0;
    } catch (Exception $e) {
        // Return false if there's an error
        error_log("Error in isProductFavorited: " . $e->getMessage());
        return false;
    }
}

// Function to add product to favorites
function addFavorite($pdo, $user_id, $product_id) {
    // Check if PDO is valid
    if (!$pdo) {
        return false;
    }
    
    try {
        // Check if already favorited
        if (isProductFavorited($pdo, $user_id, $product_id)) {
            return true; // Already favorited
        }
        
        $stmt = $pdo->prepare("INSERT INTO favorites (user_id, product_id) VALUES (?, ?)");
        return $stmt->execute([$user_id, $product_id]);
    } catch (Exception $e) {
        // Return false if there's an error
        error_log("Error in addFavorite: " . $e->getMessage());
        return false;
    }
}

// Function to remove product from favorites
function removeFavorite($pdo, $user_id, $product_id) {
    // Check if PDO is valid
    if (!$pdo) {
        return false;
    }
    
    try {
        $stmt = $pdo->prepare("DELETE FROM favorites WHERE user_id = ? AND product_id = ?");
        return $stmt->execute([$user_id, $product_id]);
    } catch (Exception $e) {
        // Return false if there's an error
        error_log("Error in removeFavorite: " . $e->getMessage());
        return false;
    }
}

// Function to get favorite count for a product
function getFavoriteCount($pdo, $product_id) {
    // Check if PDO is valid
    if (!$pdo) {
        return 0;
    }
    
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM favorites WHERE product_id = ?");
        $stmt->execute([$product_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result['count'];
    } catch (Exception $e) {
        // Return 0 if there's an error
        error_log("Error in getFavoriteCount: " . $e->getMessage());
        return 0;
    }
}

// Function to add product to cart in database
function addToCartDB($pdo, $user_id, $product_id, $quantity = 1) {
    // Check if product already in cart
    $stmt = $pdo->prepare("SELECT * FROM cart WHERE user_id = ? AND product_id = ?");
    $stmt->execute([$user_id, $product_id]);
    $cart_item = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($cart_item) {
        // Update quantity
        $stmt = $pdo->prepare("UPDATE cart SET quantity = quantity + ? WHERE user_id = ? AND product_id = ?");
        return $stmt->execute([$quantity, $user_id, $product_id]);
    } else {
        // Add new item
        $stmt = $pdo->prepare("INSERT INTO cart (user_id, product_id, quantity) VALUES (?, ?, ?)");
        return $stmt->execute([$user_id, $product_id, $quantity]);
    }
}

// Function to get cart items for user
function getCartItems($pdo, $user_id) {
    $stmt = $pdo->prepare("
        SELECT c.*, p.name, p.price, p.image 
        FROM cart c 
        JOIN products p ON c.product_id = p.id 
        WHERE c.user_id = ? 
        ORDER BY c.created_at DESC
    ");
    $stmt->execute([$user_id]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Function to update cart item quantity
function updateCartItemQuantity($pdo, $user_id, $product_id, $quantity) {
    if ($quantity <= 0) {
        // Remove item if quantity is 0 or less
        $stmt = $pdo->prepare("DELETE FROM cart WHERE user_id = ? AND product_id = ?");
        return $stmt->execute([$user_id, $product_id]);
    } else {
        // Update quantity
        $stmt = $pdo->prepare("UPDATE cart SET quantity = ? WHERE user_id = ? AND product_id = ?");
        return $stmt->execute([$quantity, $user_id, $product_id]);
    }
}

// Function to remove item from cart
function removeCartItem($pdo, $user_id, $product_id) {
    $stmt = $pdo->prepare("DELETE FROM cart WHERE user_id = ? AND product_id = ?");
    return $stmt->execute([$user_id, $product_id]);
}

// Function to clear cart
function clearCart($pdo, $user_id) {
    $stmt = $pdo->prepare("DELETE FROM cart WHERE user_id = ?");
    return $stmt->execute([$user_id]);
}

// Function to calculate cart total
function calculateCartTotal($cart_items) {
    $total = 0;
    foreach ($cart_items as $item) {
        $total += $item['price'] * $item['quantity'];
    }
    return $total;
}

// Function to create order
function createOrder($pdo, $user_id, $total_amount, $shipping_address) {
    $pdo->beginTransaction();
    
    try {
        // Create order
        $stmt = $pdo->prepare("INSERT INTO orders (user_id, total_amount, shipping_address) VALUES (?, ?, ?)");
        $stmt->execute([$user_id, $total_amount, $shipping_address]);
        $order_id = $pdo->lastInsertId();
        
        // Get cart items
        $cart_items = getCartItems($pdo, $user_id);
        
        // Add order items
        foreach ($cart_items as $item) {
            $stmt = $pdo->prepare("INSERT INTO order_items (order_id, product_id, quantity, price) VALUES (?, ?, ?, ?)");
            $stmt->execute([$order_id, $item['product_id'], $item['quantity'], $item['price']]);
        }
        
        // Clear cart
        clearCart($pdo, $user_id);
        
        $pdo->commit();
        return $order_id;
    } catch (Exception $e) {
        $pdo->rollback();
        throw $e;
    }
}

// Function to get a random product
function getRandomProduct($pdo) {
    try {
        $stmt = $pdo->query("SELECT * FROM products ORDER BY RAND() LIMIT 1");
        return $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        error_log("Error in getRandomProduct: " . $e->getMessage());
        return false;
    }
}

// Function to get random products
function getRandomProducts($pdo, $limit = 5) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM products ORDER BY RAND() LIMIT ?");
        $stmt->execute([$limit]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        error_log("Error in getRandomProducts: " . $e->getMessage());
        return [];
    }
}

// Function to format time in a friendly way
function formatTimeAgo($datetime, $full = false) {
    $now = new DateTime();
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    // Calculate weeks manually since DateInterval doesn't have a $w property
    $weeks = floor($diff->d / 7);
    $diff->d = $diff->d - ($weeks * 7);

    $string = array(
        'y' => 'سنة',
        'm' => 'شهر',
        'w' => 'أسبوع',
        'd' => 'يوم',
        'h' => 'ساعة',
        'i' => 'دقيقة',
        's' => 'ثانية',
    );
    
    // Build the result array
    $result = array();
    
    if ($diff->y > 0) {
        $result[] = $diff->y . ' ' . $string['y'] . ($diff->y > 1 ? '' : '');
    }
    
    if ($weeks > 0) {
        $result[] = $weeks . ' ' . $string['w'] . ($weeks > 1 ? '' : '');
    }
    
    if ($diff->d > 0) {
        $result[] = $diff->d . ' ' . $string['d'] . ($diff->d > 1 ? '' : '');
    }
    
    if ($diff->h > 0) {
        $result[] = $diff->h . ' ' . $string['h'] . ($diff->h > 1 ? '' : '');
    }
    
    if ($diff->i > 0) {
        $result[] = $diff->i . ' ' . $string['i'] . ($diff->i > 1 ? '' : '');
    }
    
    if ($diff->s > 0) {
        $result[] = $diff->s . ' ' . $string['s'] . ($diff->s > 1 ? '' : '');
    }
    
    // If no differences, it's now
    if (empty($result)) {
        return 'الآن';
    }
    
    // Return only the first element if not full, otherwise all elements
    if (!$full) {
        return 'منذ ' . $result[0];
    }
    
    return 'منذ ' . implode(', ', $result);
}

// Function to add a product comment
function addProductComment($pdo, $product_id, $user_id, $comment) {
    // Validate comment length (using mb_strlen for proper UTF-8 support)
    $comment = trim($comment);
    if (empty($comment) || mb_strlen($comment, 'UTF-8') > 500) {
        return false;
    }
    
    // Check if user has commented recently (prevent spam)
    $stmt = $pdo->prepare("SELECT created_at FROM product_comments WHERE user_id = ? ORDER BY created_at DESC LIMIT 1");
    $stmt->execute([$user_id]);
    $last_comment = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($last_comment) {
        $last_comment_time = strtotime($last_comment['created_at']);
        $current_time = time();
        // Prevent commenting within 30 seconds of last comment
        if (($current_time - $last_comment_time) < 30) {
            return false;
        }
    }
    
    // Insert comment
    $stmt = $pdo->prepare("INSERT INTO product_comments (product_id, user_id, comment) VALUES (?, ?, ?)");
    return $stmt->execute([$product_id, $user_id, $comment]);
}

// Function to get product comments
function getProductComments($pdo, $product_id) {
    $stmt = $pdo->prepare("
        SELECT pc.*, u.username 
        FROM product_comments pc 
        JOIN users u ON pc.user_id = u.id 
        WHERE pc.product_id = ? 
        ORDER BY pc.created_at DESC
    ");
    $stmt->execute([$product_id]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Function to get a specific comment by ID
function getCommentById($pdo, $comment_id) {
    $stmt = $pdo->prepare("
        SELECT pc.*, u.username, u.role
        FROM product_comments pc 
        JOIN users u ON pc.user_id = u.id 
        WHERE pc.id = ?
    ");
    $stmt->execute([$comment_id]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

// Function to update a product comment
function updateProductComment($pdo, $comment_id, $user_id, $comment) {
    // Validate comment length (using mb_strlen for proper UTF-8 support)
    $comment = trim($comment);
    if (empty($comment) || mb_strlen($comment, 'UTF-8') > 500) {
        return false;
    }
    
    // Update comment
    $stmt = $pdo->prepare("UPDATE product_comments SET comment = ? WHERE id = ? AND user_id = ?");
    return $stmt->execute([$comment, $comment_id, $user_id]);
}

// Function to delete a product comment
function deleteProductComment($pdo, $comment_id, $user_id) {
    // Delete comment
    $stmt = $pdo->prepare("DELETE FROM product_comments WHERE id = ? AND user_id = ?");
    return $stmt->execute([$comment_id, $user_id]);
}
?>