<?php
// functions.php - Core Functions
// File location: /bidwheels.net/includes/functions.php

// Start output buffering to prevent header issues
ob_start();

require_once __DIR__ . '/db.php';

/**
 * Redirect to URL
 */
function redirect($url) {
    // Clean output buffer before redirect
    while (ob_get_level()) {
        ob_end_clean();
    }
    header("Location: " . SITE_URL . $url);
    exit();
}

/**
 * Display success message
 */
function setSuccess($msg) {
    $_SESSION['success'] = $msg;
}

/**
 * Display error message
 */
function setError($msg) {
    $_SESSION['error'] = $msg;
}

/**
 * Get and clear message
 */
function getMessage() {
    $msg = '';
    if (isset($_SESSION['success'])) {
        $msg = '<div class="alert alert-success">' . $_SESSION['success'] . '</div>';
        unset($_SESSION['success']);
    }
    if (isset($_SESSION['error'])) {
        $msg = '<div class="alert alert-danger">' . $_SESSION['error'] . '</div>';
        unset($_SESSION['error']);
    }
    return $msg;
}

/**
 * Check if user is logged in
 */
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

/**
 * Check if user is admin
 */
function isAdmin() {
    return isset($_SESSION['user_role']) && $_SESSION['user_role'] == 'admin';
}

/**
 * Get current user data
 */
function getCurrentUser() {
    if (!isLoggedIn()) {
        return null;
    }
    return fetchOne("SELECT * FROM users WHERE id = '" . $_SESSION['user_id'] . "'");
}



/**
 * Sanitize input
 */
function sanitize($input) {
    global $conn;
    return htmlspecialchars(strip_tags(trim($input)));
}

/**
 * Generate random number between min and max
 */
function randomNum($min, $max) {
    return rand($min, $max);
}

/**
 * Format price
 */
function formatPrice($price) {
    return '$' . number_format($price, 2);
}

/**
 * Time ago function
 */
function timeAgo($timestamp) {
    $time_ago = strtotime($timestamp);
    $current_time = time();
    $time_difference = $current_time - $time_ago;
    $seconds = $time_difference;
    
    $minutes = round($seconds / 60);
    $hours = round($seconds / 3600);
    $days = round($seconds / 86400);
    $weeks = round($seconds / 604800);
    $months = round($seconds / 2629440);
    $years = round($seconds / 31553280);
    
    if ($seconds <= 60) {
        return "Just Now";
    } else if ($minutes <= 60) {
        return ($minutes == 1) ? "1 minute ago" : "$minutes minutes ago";
    } else if ($hours <= 24) {
        return ($hours == 1) ? "1 hour ago" : "$hours hours ago";
    } else if ($days <= 7) {
        return ($days == 1) ? "yesterday" : "$days days ago";
    } else if ($weeks <= 4.3) {
        return ($weeks == 1) ? "1 week ago" : "$weeks weeks ago";
    } else if ($months <= 12) {
        return ($months == 1) ? "1 month ago" : "$months months ago";
    } else {
        return ($years == 1) ? "1 year ago" : "$years years ago";
    }
}

/**
 * Get product images
 */
function getProductImages($product_id) {
    return fetchAll("SELECT * FROM product_images WHERE product_id = $product_id");
}

/**
 * Get featured image
 */
function getFeaturedImage($product_id) {
    $image = fetchOne("SELECT image_path FROM product_images WHERE product_id = $product_id AND is_featured = 1 LIMIT 1");
    if ($image) {
        return SITE_URL . '/uploads/products/' . $image['image_path'];
    }
    return SITE_URL . '/assets/images/no-image.jpg';
}

/**
 * Get total bids for product
 */
function getTotalBids($product_id) {
    $result = fetchOne("SELECT COUNT(*) as total FROM bids WHERE product_id = $product_id");
    return $result['total'];
}

/**
 * Get total comments for product
 */
function getTotalComments($product_id) {
    $result = fetchOne("SELECT COUNT(*) as total FROM comments WHERE product_id = $product_id");
    return $result['total'];
}

/**
 * Check if product is reserved
 */
function isReserved($product_id) {
    $product = fetchOne("SELECT is_reserved FROM products WHERE id = $product_id");
    return $product && $product['is_reserved'] == 1;
}

/**
 * Get remaining time for bidding
 */
function getRemainingTime($end_time) {
    $now = new DateTime();
    $end = new DateTime($end_time);
    $diff = $now->diff($end);
    
    if ($now > $end) {
        return "Ended";
    }
    
    if ($diff->d > 0) {
        return $diff->d . " days left";
    } elseif ($diff->h > 0) {
        return $diff->h . " hours left";
    } elseif ($diff->i > 0) {
        return $diff->i . " minutes left";
    } else {
        return "Ending soon";
    }
}

/**
 * Generate CSRF token
 */
function generateCsrfToken() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

/**
 * Validate CSRF token
 */
function validateCsrfToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

/**
 * Get user's saved payment methods
 */
function getUserPaymentMethods($user_id) {
    return fetchAll("
        SELECT upm.*, pm.method_name 
        FROM user_payment_methods upm
        JOIN payment_methods pm ON upm.payment_method_id = pm.id
        WHERE upm.user_id = $user_id
        ORDER BY upm.is_default DESC, upm.created_at DESC
    ");
}

/**
 * Save user payment method
 */
function saveUserPaymentMethod($user_id, $payment_method_id, $payment_data) {
    $existing = fetchOne("SELECT id FROM user_payment_methods WHERE user_id = $user_id AND payment_method_id = $payment_method_id");
    if (!$existing) {
        return insert('user_payment_methods', [
            'user_id' => $user_id,
            'payment_method_id' => $payment_method_id,
            'payment_data' => json_encode($payment_data),
            'is_default' => 0
        ]);
    }
    return $existing['id'];
}

// Flush output buffer at the end
ob_end_flush();
?>