<?php
// detail.php - Product Detail Page with Enhanced Gallery & Professional Description
// File location: /bidwheels.net/product/detail.php

require_once '../includes/functions.php';
require_once '../includes/mailer.php';
require_once '../includes/header.php';

// Get product ID from URL
$product_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($product_id <= 0) {
    redirect('/index.php');
}

// Get product details
$product = fetchOne("
    SELECT p.*, c.name as category_name, c.id as category_id 
    FROM products p
    LEFT JOIN categories c ON p.category_id = c.id
    WHERE p.id = $product_id
");

if (!$product) {
    redirect('/index.php');
}

// Update view count
query("UPDATE products SET views = views + 1 WHERE id = $product_id");

// Get product images
$featured_image = fetchOne("SELECT image_path FROM product_images WHERE product_id = $product_id AND is_featured = 1 LIMIT 1");
$all_images = fetchAll("SELECT image_path FROM product_images WHERE product_id = $product_id ORDER BY is_featured DESC, id ASC");

// Prepare images array - ensure featured is first
$images = [];
if ($featured_image) {
    $images[] = ['path' => $featured_image['image_path'], 'is_featured' => true];
}
foreach ($all_images as $img) {
    if (!$featured_image || $img['image_path'] != $featured_image['image_path']) {
        $images[] = ['path' => $img['image_path'], 'is_featured' => false];
    }
}

// Get first 3 images for main display
$main_images = array_slice($images, 0, 3);
$thumbnail_images = $images; // All images for thumbnails

// Get highest bid
$highest_bid = fetchOne("SELECT MAX(amount) as max_bid FROM bids WHERE product_id = $product_id");
$current_highest = $highest_bid['max_bid'] ?? $product['starting_price'];

// Get total bids
$total_bids = getTotalBids($product_id);

// Get bids
$recent_bids = fetchAll("
    SELECT b.*, 
           CASE WHEN u.id IS NOT NULL THEN u.name ELSE 'Guest Bidder' END as user_name 
    FROM bids b
    LEFT JOIN users u ON b.user_id = u.id
    WHERE b.product_id = $product_id
    ORDER BY b.amount DESC
    LIMIT 10
");

// Get comments
$comments = fetchAll("
    SELECT c.*, 
           CASE WHEN u.id IS NOT NULL THEN u.name ELSE 'Guest' END as user_name 
    FROM comments c
    LEFT JOIN users u ON c.user_id = u.id
    WHERE c.product_id = $product_id
    ORDER BY c.created_at DESC
");

// Get active payment methods
$payment_methods = fetchAll("SELECT * FROM payment_methods WHERE is_active = 1");

// Handle bid submission
$bid_error = '';
$bid_success = '';
$show_success_toast = false;
$success_message = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['place_bid'])) {
    if ($product['is_reserved'] == 1) {
        $bid_error = 'This listing is reserved and bidding has stopped.';
    } elseif (strtotime($product['end_time']) < time()) {
        $bid_error = 'This auction has ended.';
    } else {
        $bid_amount = floatval($_POST['bid_amount']);
        $min_bid = $current_highest + 1;
        $email = sanitize($_POST['email']);
        $full_name = sanitize($_POST['full_name']);
        $phone = sanitize($_POST['phone']);
        $address = sanitize($_POST['address'] ?? '');
        $save_payment = isset($_POST['save_payment']) ? 1 : 0;
        
        if ($bid_amount < $min_bid) {
            $bid_error = "Bid must be at least $" . number_format($min_bid, 2);
        } elseif (empty($full_name) || empty($email) || empty($phone)) {
            $bid_error = "Please fill in all contact information.";
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $bid_error = "Please enter a valid email address.";
        } else {
            $user = fetchOne("SELECT id FROM users WHERE email = '$email'");
            
            if (!$user) {
                $user_id = insert('users', [
                    'name' => $full_name,
                    'email' => $email,
                    'password' => md5(uniqid()),
                    'phone' => $phone,
                    'address' => $address,
                    'role' => 'user',
                    'is_dummy' => 0
                ]);
            } else {
                $user_id = $user['id'];
                update('users', [
                    'name' => $full_name,
                    'phone' => $phone,
                    'address' => $address
                ], "id = $user_id");
            }
            
            $payment_method_id = null;
            $selected_method = sanitize($_POST['payment_method'] ?? '');
            
            if (!empty($selected_method)) {
                $payment_method = fetchOne("SELECT id FROM payment_methods WHERE method_name = '$selected_method'");
                
                if ($payment_method) {
                    $payment_method_id = $payment_method['id'];
                    $payment_data = [];
                    if ($selected_method == 'Credit Card') {
                        $payment_data = [
                            'name_on_card' => sanitize($_POST['card_name'] ?? ''),
                            'zip_code' => sanitize($_POST['zip_code'] ?? ''),
                            'card_number' => sanitize($_POST['card_number'] ?? ''),
                            'expiry' => sanitize($_POST['expiry'] ?? ''),
                            'cvc' => sanitize($_POST['cvc'] ?? '')
                        ];
                    } elseif ($selected_method == 'Bank Transfer') {
                        $payment_data = [
                            'account_name' => sanitize($_POST['account_name'] ?? ''),
                            'account_number' => sanitize($_POST['account_number'] ?? ''),
                            'bank_name' => sanitize($_POST['bank_name'] ?? ''),
                            'routing_number' => sanitize($_POST['routing_number'] ?? '')
                        ];
                    }
                    
                    if ($save_payment) {
                        $existing = fetchOne("SELECT id FROM user_payment_methods WHERE user_id = $user_id AND payment_method_id = {$payment_method['id']}");
                        if (!$existing) {
                            insert('user_payment_methods', [
                                'user_id' => $user_id,
                                'payment_method_id' => $payment_method['id'],
                                'payment_data' => json_encode($payment_data),
                                'is_default' => 0
                            ]);
                        }
                    }
                }
            }
            
            $previous_highest = fetchOne("SELECT user_id, amount FROM bids WHERE product_id = $product_id ORDER BY amount DESC LIMIT 1");
            
            $bid_id = insert('bids', [
                'product_id' => $product_id,
                'user_id' => $user_id,
                'amount' => $bid_amount,
                'is_system_bid' => 0
            ]);
            
            if ($bid_id) {
                insert('bid_payments', [
                    'bid_id' => $bid_id,
                    'user_id' => $user_id,
                    'product_id' => $product_id,
                    'payment_method_id' => $payment_method_id,
                    'contact_email' => $email,
                    'contact_phone' => $phone,
                    'contact_address' => $address
                ]);
                
                update('products', ['current_highest_bid' => $bid_amount], "id = $product_id");
                
                try {
                    sendBidConfirmationEmail($email, $full_name, $product['name'], $bid_amount, $product_id);
                } catch (Exception $e) {}
                
                if ($previous_highest && $previous_highest['user_id'] != $user_id) {
                    $previous_user = fetchOne("SELECT * FROM users WHERE id = {$previous_highest['user_id']}");
                    if ($previous_user && $previous_user['is_dummy'] == 0) {
                        try {
                            sendOutbidEmail(
                                $previous_user['email'],
                                $previous_user['name'],
                                $product['name'],
                                $bid_amount,
                                $product_id
                            );
                        } catch (Exception $e) {}
                    }
                }
                
                setcookie('bidder_email', $email, time() + (86400 * 30), "/");
                setcookie('bidder_name', $full_name, time() + (86400 * 30), "/");
                
                $current_highest = $bid_amount;
                $total_bids++;
                
                $show_success_toast = true;
                $success_message = "Your bid of $" . number_format($bid_amount, 2) . " has been placed successfully!";
                
                header("Location: detail.php?id=$product_id&success=1");
                exit();
            } else {
                $bid_error = "Failed to place bid. Please try again.";
            }
        }
    }
}

if (isset($_GET['success'])) {
    $show_success_toast = true;
    $success_message = "Your bid has been placed successfully!";
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['post_comment'])) {
    $comment_name = sanitize($_POST['comment_name']);
    $comment_text = sanitize($_POST['comment_text']);
    
    if (!empty($comment_text)) {
        $user = fetchOne("SELECT id FROM users WHERE name = '$comment_name' AND is_dummy = 1 LIMIT 1");
        if (!$user) {
            $user_id = insert('users', [
                'name' => $comment_name,
                'email' => 'guest_' . time() . '@bidwheels.net',
                'password' => md5('guest123'),
                'phone' => '',
                'address' => '',
                'role' => 'user',
                'is_dummy' => 1
            ]);
        } else {
            $user_id = $user['id'];
        }
        
        insert('comments', [
            'product_id' => $product_id,
            'user_id' => $user_id,
            'comment_text' => $comment_text,
            'is_system_comment' => 0
        ]);
        
        header("Location: detail.php?id=$product_id&comment=1");
        exit();
    }
}

$saved_email = isset($_COOKIE['bidder_email']) ? $_COOKIE['bidder_email'] : '';
$saved_name = isset($_COOKIE['bidder_name']) ? $_COOKIE['bidder_name'] : '';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($product['name']); ?> - <?php echo SITE_NAME; ?></title>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,400;14..32,500;14..32,600;14..32,700;14..32,800&display=swap" rel="stylesheet">
    
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Inter', sans-serif; background: #0a0a0a; color: #ffffff; }
        :root { --primary: #FF8C3E; --primary-dark: #e67a22; --dark-card: #111111; --dark-surface: #1a1a1a; --gray: #2a2a2a; --text-muted: #888888; --success: #10b981; --error: #ef4444; }
        .container { max-width: 1400px; margin: 0 auto; padding: 0 24px; }
        .breadcrumb { padding: 20px 0; font-size: 13px; }
        .breadcrumb a { color: var(--text-muted); text-decoration: none; }
        .breadcrumb a:hover { color: var(--primary); }
        .breadcrumb span { color: var(--primary); }
        .product-detail { padding: 20px 0 60px; }
        
        /* Gallery Layout - One top image, two bottom images */
        .gallery-enhanced {
            display: flex;
            flex-direction: column;
            gap: 0;
            margin-bottom: 20px;
            background: var(--dark-surface);
            border-radius: 20px;
            overflow: hidden;
        }
        .gallery-main {
            width: 100%;
            aspect-ratio: 16/9;
            background: var(--dark-surface);
            overflow: hidden;
            cursor: pointer;
        }
        .gallery-main img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s;
        }
        .gallery-main img:hover {
            transform: scale(1.02);
        }
        .gallery-side {
            display: flex;
            flex-direction: row;
            gap: 0;
            width: 100%;
        }
        .gallery-side-item {
            flex: 1;
            aspect-ratio: 16/9;
            background: var(--dark-surface);
            overflow: hidden;
            cursor: pointer;
        }
        .gallery-side-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s;
        }
        .gallery-side-item img:hover {
            transform: scale(1.05);
        }
        .gallery-thumbnails {
            display: flex;
            gap: 12px;
            overflow-x: auto;
            padding-bottom: 8px;
            margin-top: 16px;
        }
        .gallery-thumb {
            width: 80px;
            height: 80px;
            border-radius: 12px;
            object-fit: cover;
            cursor: pointer;
            border: 2px solid transparent;
            transition: all 0.3s;
            flex-shrink: 0;
        }
        .gallery-thumb:hover,
        .gallery-thumb.active {
            border-color: var(--primary);
        }
        
        /* Professional Description Styling */
        .description-enhanced {
            font-size: 16px;
            line-height: 1.7;
            color: #e0e0e0;
        }
        .description-enhanced p {
            margin-bottom: 1.2rem;
        }
        .description-enhanced h2 {
            font-size: 24px;
            font-weight: 600;
            margin: 1.5rem 0 1rem;
            color: var(--primary);
        }
        .description-enhanced h3 {
            font-size: 20px;
            font-weight: 600;
            margin: 1.2rem 0 0.8rem;
            color: #ffffff;
        }
        .description-enhanced h4 {
            font-size: 18px;
            font-weight: 500;
            margin: 1rem 0 0.5rem;
            color: #dddddd;
        }
        .description-enhanced ul, 
        .description-enhanced ol {
            margin: 1rem 0 1rem 1.5rem;
        }
        .description-enhanced li {
            margin-bottom: 0.5rem;
        }
        .description-enhanced strong {
            color: var(--primary);
            font-weight: 600;
        }
        .description-enhanced em {
            font-style: italic;
            color: #bbbbbb;
        }
        .description-enhanced blockquote {
            border-left: 3px solid var(--primary);
            padding-left: 1.2rem;
            margin: 1.2rem 0;
            color: #aaaaaa;
            font-style: italic;
        }
        .description-enhanced a {
            color: var(--primary);
            text-decoration: none;
        }
        .description-enhanced a:hover {
            text-decoration: underline;
        }
        .description-enhanced hr {
            margin: 1.5rem 0;
            border-color: rgba(255,255,255,0.1);
        }
        
        /* Rest of styles */
        .product-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 40px; margin-bottom: 50px; }
        .product-header { margin-bottom: 24px; }
        .product-category { display: inline-block; background: rgba(255,140,62,0.15); color: var(--primary); padding: 4px 12px; border-radius: 100px; font-size: 12px; font-weight: 500; margin-bottom: 16px; }
        .product-title { font-size: 32px; font-weight: 700; margin-bottom: 12px; letter-spacing: -0.5px; }
        .product-meta { display: flex; flex-wrap: wrap; gap: 20px; color: var(--text-muted); font-size: 13px; }
        .product-meta i { color: var(--primary); margin-right: 5px; }
        .bid-stats-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin-bottom: 20px; }
        .bid-stat { text-align: center; padding: 12px 6px; background: var(--dark-surface); border-radius: 14px; }
        .bid-stat-label { font-size: 10px; color: var(--text-muted); margin-bottom: 5px; text-transform: uppercase; letter-spacing: 0.5px; }
        .bid-stat-value { font-size: 18px; font-weight: 700; color: var(--primary); }
        .bid-card { background: var(--dark-card); border-radius: 24px; padding: 20px; margin-bottom: 24px; border: 1px solid rgba(255,255,255,0.05); }
        .reserved-badge { background: linear-gradient(135deg, #dc3545, #c82333); padding: 12px 20px; border-radius: 16px; display: flex; align-items: center; justify-content: center; gap: 10px; margin-bottom: 20px; font-weight: 600; font-size: 14px; }
        .bid-actions { display: flex; gap: 12px; flex-wrap: wrap; }
        .btn { padding: 12px 24px; border-radius: 40px; font-weight: 600; font-size: 14px; cursor: pointer; transition: all 0.3s; border: none; font-family: inherit; display: inline-flex; align-items: center; gap: 8px; }
        .btn-primary { background: var(--primary); color: #0a0a0a; flex: 1; justify-content: center; }
        .btn-primary:hover { background: var(--primary-dark); transform: translateY(-2px); }
        .btn-outline { background: transparent; border: 1.5px solid var(--gray); color: white; }
        .btn-outline:hover { border-color: var(--primary); color: var(--primary); }
        .social-share { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; padding-top: 20px; border-top: 1px solid rgba(255,255,255,0.08); }
        .social-share span { color: var(--text-muted); font-size: 13px; }
        .social-icon { width: 36px; height: 36px; border-radius: 50%; background: var(--dark-surface); display: inline-flex; align-items: center; justify-content: center; color: white; text-decoration: none; transition: all 0.3s; }
        .social-icon:hover { background: var(--primary); }
        .product-tabs { background: var(--dark-card); border-radius: 24px; padding: 28px; border: 1px solid rgba(255,255,255,0.05); margin-top: 20px; }
        .tab-headers { display: flex; gap: 28px; border-bottom: 1px solid rgba(255,255,255,0.08); margin-bottom: 24px; flex-wrap: wrap; }
        .tab-btn { background: none; border: none; padding: 10px 0; font-size: 15px; font-weight: 600; color: var(--text-muted); cursor: pointer; font-family: inherit; position: relative; }
        .tab-btn.active { color: var(--primary); }
        .tab-btn.active::after { content: ''; position: absolute; bottom: -1px; left: 0; right: 0; height: 2px; background: var(--primary); }
        .tab-pane { display: none; animation: fadeIn 0.3s; }
        .tab-pane.active { display: block; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
        .bids-table { width: 100%; border-collapse: collapse; }
        .bids-table th, .bids-table td { padding: 12px 10px; text-align: left; border-bottom: 1px solid rgba(255,255,255,0.05); font-size: 13px; }
        .bids-table th { color: var(--text-muted); font-weight: 500; }
        .bid-amount { color: var(--primary); font-weight: 700; }
        .comment-form { background: var(--dark-surface); padding: 20px; border-radius: 16px; margin-bottom: 28px; }
        .comment-form input, .comment-form textarea { width: 100%; padding: 12px 14px; background: var(--dark-card); border: 1px solid rgba(255,255,255,0.08); border-radius: 12px; color: white; font-family: inherit; font-size: 13px; }
        .comment { padding: 16px; border-bottom: 1px solid rgba(255,255,255,0.05); }
        .comment-header { display: flex; gap: 15px; margin-bottom: 8px; flex-wrap: wrap; }
        .comment-name { font-weight: 600; font-size: 13px; }
        .comment-time { color: var(--text-muted); font-size: 11px; }
        .comment-text { color: #bbb; font-size: 13px; line-height: 1.5; }
        .tags { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 20px; }
        .tag { background: var(--dark-surface); padding: 5px 12px; border-radius: 100px; font-size: 11px; color: var(--text-muted); text-decoration: none; }
        .tag:hover { background: var(--primary); color: #0a0a0a; }
        
        /* Modal Styles */
        .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.85); backdrop-filter: blur(6px); z-index: 10000; display: none; align-items: center; justify-content: center; }
        .modal-container { background: var(--dark-card); border-radius: 28px; width: 90%; max-width: 500px; max-height: 85vh; overflow-y: auto; animation: modalSlide 0.3s; }
        .modal-container::-webkit-scrollbar { width: 5px; }
        .modal-container::-webkit-scrollbar-track { background: var(--dark-surface); }
        .modal-container::-webkit-scrollbar-thumb { background: var(--primary); }
        @keyframes modalSlide { from { transform: translateY(-30px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
        .modal-header { padding: 20px; text-align: center; position: relative; background: var(--primary); border-radius: 28px 28px 0 0; }
        .modal-header i { font-size: 40px; margin-bottom: 8px; color: #0a0a0a; }
        .modal-header h3 { font-size: 20px; color: #0a0a0a; }
        .close-modal-x { position: absolute; top: 15px; right: 20px; font-size: 24px; cursor: pointer; color: rgba(0,0,0,0.5); }
        .close-modal-x:hover { color: black; }
        .modal-body { padding: 20px; text-align: left; color: #ccc; max-height: 55vh; overflow-y: auto; }
        .modal-footer { padding: 16px 20px 20px; display: flex; gap: 12px; justify-content: center; }
        .modal-btn { padding: 10px 24px; border-radius: 40px; font-weight: 600; cursor: pointer; border: none; font-family: inherit; font-size: 14px; }
        .modal-btn-primary { background: var(--primary); color: #0a0a0a; }
        .modal-btn-secondary { background: var(--gray); color: white; }
        .form-group { margin-bottom: 16px; }
        .form-group label { display: block; margin-bottom: 6px; font-weight: 500; font-size: 12px; }
        .form-control { width: 100%; padding: 12px 14px; background: var(--dark-surface); border: 1px solid rgba(255,255,255,0.08); border-radius: 12px; color: white; font-family: inherit; font-size: 13px; }
        .form-control:focus { outline: none; border-color: var(--primary); }
        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
        .payment-fields { background: var(--dark-surface); padding: 16px; border-radius: 14px; margin-top: 12px; }
        hr { border-color: rgba(255,255,255,0.08); margin: 16px 0; }
        .checkbox-group { display: flex; align-items: center; gap: 10px; margin: 12px 0; }
        .checkbox-group input { width: 16px; height: 16px; cursor: pointer; }
        .checkbox-group label { margin: 0; cursor: pointer; font-size: 12px; }
        .toast-notification { position: fixed; bottom: 30px; right: 30px; background: var(--dark-card); border-left: 4px solid var(--primary); padding: 16px 20px; border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.3); z-index: 10001; display: flex; align-items: center; gap: 12px; min-width: 280px; animation: slideInRight 0.3s ease; }
        .toast-notification.success { border-left-color: var(--success); }
        .toast-notification.error { border-left-color: var(--error); }
        @keyframes slideInRight { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
        .close-toast { cursor: pointer; color: var(--text-muted); margin-left: auto; }
        
        @media (max-width: 992px) {
            .product-grid { grid-template-columns: 1fr; gap: 28px; }
        }
        @media (max-width: 768px) {
            .container { padding: 0 16px; }
            .bid-stats-grid { grid-template-columns: repeat(2, 1fr); }
            .product-title { font-size: 24px; }
            .form-row { grid-template-columns: 1fr; }
            .gallery-main { aspect-ratio: 4/3; }
            .gallery-side-item { aspect-ratio: 4/3; }
            .gallery-thumb { width: 60px; height: 60px; }
        }
        @media (max-width: 480px) {
            .bid-actions { flex-direction: column; }
            .btn-primary { width: 100%; }
        }
        .text-center { text-align: center; }
        .w-100 { width: 100%; }


        /* Reduce gallery height only */
.gallery-main {
    aspect-ratio: 21/9;
}

.gallery-side-item {
    aspect-ratio: 21/9;
}

/* Add 1px black border between images */
.gallery-main {
    border-bottom: 1px solid #000000;
}

.gallery-side-item:first-child {
    border-right: 1px solid #000000;
}

/* Maintain full width */
.gallery-enhanced {
    width: 100%;
    max-width: 100%;
}


/* Product Short Description */
.product-short-desc {
    margin: 16px 0 20px;
    padding: 16px 20px;
    background: var(--dark-surface);
    border-radius: 16px;
    border-left: 3px solid var(--primary);
    font-size: 15px;
    line-height: 1.6;
    color: #cccccc;
}

.product-short-desc i {
    color: var(--primary);
    margin-right: 8px;
}

.bid-stat {
    min-width: 110px;
}


/* Table styling for product description */
.product-detail table {
    width: 100%;
    border-collapse: collapse;
    margin: 20px 0;
    font-size: 14px;
    background: var(--dark-surface);
    border-radius: 12px;
    overflow: hidden;
}

.product-detail table td,
.product-detail table th {
    border: 1px solid #333;
    padding: 12px 16px;
    text-align: left;
    vertical-align: top;
}

.product-detail table th {
    background: #2a2a2a;
    font-weight: 600;
    color: #FF8C3E;
}

.product-detail table tr:nth-child(even) {
    background: rgba(255,255,255,0.02);
}

.product-detail table tr:hover {
    background: rgba(255,140,62,0.05);
}



/* Responsive Table */
.product-detail .description-enhanced table {
    display: block;
    width: 100%;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

.product-detail .description-enhanced table td,
.product-detail .description-enhanced table th {
    white-space: nowrap;
}

/* Responsive Table - Full Width on PC */
.product-detail .description-enhanced table {
    display: table;
    width: 100%;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

/* On mobile, allow horizontal scroll */
@media (max-width: 768px) {
    .product-detail .description-enhanced table {
        display: block;
        width: 100%;
    }
    
    .product-detail .description-enhanced table td,
    .product-detail .description-enhanced table th {
        white-space: nowrap;
    }
}

/* On desktop, keep normal table layout */
@media (min-width: 769px) {
    .product-detail .description-enhanced table {
        display: table;
        width: 100%;
    }
    
    .product-detail .description-enhanced table td,
    .product-detail .description-enhanced table th {
        white-space: normal;
    }
}

    </style>
</head>
<body>

<div class="container">
    <div class="product-detail">
        <div class="breadcrumb">
            <a href="<?php echo SITE_URL; ?>/index.php"><i class="fas fa-home"></i> Home</a> / 
            <a href="index.php">Vehicles</a> / 
            <span><?php echo htmlspecialchars($product['name']); ?></span>
        </div>
        
        <div class="product-grid">
            <!-- Enhanced Gallery Section -->
            <div>
                <div class="gallery-enhanced">
                    <!-- Top Large Image -->
                    <div class="gallery-main" id="mainImageContainer">
                        <img id="mainImage" src="<?php echo count($main_images) > 0 ? SITE_URL . '/uploads/products/' . $main_images[0]['path'] : SITE_URL . '/assets/images/no-image.jpg'; ?>" 
                             alt="<?php echo htmlspecialchars($product['name']); ?>">
                    </div>
                    
                    <!-- Bottom Row: Two Smaller Images -->
                    <div class="gallery-side">
                        <?php for ($i = 1; $i <= 2 && $i < count($main_images); $i++): ?>
                            <div class="gallery-side-item" onclick="swapMainImage('<?php echo SITE_URL . '/uploads/products/' . $main_images[$i]['path']; ?>')">
                                <img src="<?php echo SITE_URL . '/uploads/products/' . $main_images[$i]['path']; ?>" 
                                     alt="Product image <?php echo $i+1; ?>">
                            </div>
                        <?php endfor; ?>
                        <?php if (count($main_images) <= 1): ?>
                            <div class="gallery-side-item" style="background: var(--dark-surface); display: flex; align-items: center; justify-content: center;">
                                <i class="fas fa-image" style="font-size: 32px; color: var(--text-muted);"></i>
                            </div>
                            <div class="gallery-side-item" style="background: var(--dark-surface); display: flex; align-items: center; justify-content: center;">
                                <i class="fas fa-image" style="font-size: 32px; color: var(--text-muted);"></i>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- Thumbnail Strip (All Images) -->
                <div class="gallery-thumbnails">
                    <?php foreach ($thumbnail_images as $index => $img): ?>
                        <img class="gallery-thumb <?php echo $index === 0 ? 'active' : ''; ?>" 
                             src="<?php echo SITE_URL . '/uploads/products/' . $img['path']; ?>" 
                             onclick="swapMainImage('<?php echo SITE_URL . '/uploads/products/' . $img['path']; ?>', this)"
                             alt="Thumbnail <?php echo $index + 1; ?>">
                    <?php endforeach; ?>
                    <?php if (count($thumbnail_images) == 0): ?>
                        <div class="gallery-thumb" style="background: var(--dark-surface); display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-image" style="color: var(--text-muted);"></i>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Product Info -->
            <div>
                <div class="product-header">
                    <span class="product-category"><i class="fas fa-car"></i> <?php echo htmlspecialchars($product['category_name']); ?></span>
                    <h1 class="product-title"><?php echo htmlspecialchars($product['name']); ?></h1>
                    <div class="product-meta">
                        <span><i class="fas fa-eye"></i> <?php echo number_format($product['views']); ?> views</span>
                        <span><i class="fas fa-calendar-alt"></i> Listed <?php echo date('M d, Y', strtotime($product['created_at'])); ?></span>
                    </div>


<?php if (!empty($product['short_desc'])): ?>
    <div class="product-short-desc">
        <i class="fas fa-quote-left"></i> <?php echo htmlspecialchars($product['short_desc']); ?>
    </div>
<?php endif; ?>


                </div>
                
                <div class="bid-card">
                    <div class="bid-stats-grid">
                        <div class="bid-stat"><div class="bid-stat-label">Current Bid</div><div class="bid-stat-value" id="currentBidDisplay"><?php echo formatPrice($current_highest); ?></div></div>
                        <div class="bid-stat"><div class="bid-stat-label">Starting Price</div><div class="bid-stat-value"><?php echo formatPrice($product['starting_price']); ?></div></div>
                        <div class="bid-stat"><div class="bid-stat-label">Total Bids</div><div class="bid-stat-value" id="totalBidsDisplay"><?php echo $total_bids; ?></div></div>
                        <div class="bid-stat"><div class="bid-stat-label">Time Left</div><div class="bid-stat-value countdown" data-end="<?php echo $product['end_time']; ?>"><?php echo getRemainingTime($product['end_time']); ?></div></div>
                    </div>
                    
                    <?php if ($product['is_reserved'] == 1): ?>
                        <div class="reserved-badge"><i class="fas fa-ban"></i> RESERVED - Bidding Stopped</div>
                    <?php elseif (strtotime($product['end_time']) < time()): ?>
                        <div class="reserved-badge" style="background: linear-gradient(135deg, #6c757d, #495057);"><i class="fas fa-hourglass-end"></i> Auction Ended</div>
                    <?php else: ?>
                        <div class="bid-actions">
                            <button class="btn btn-primary" id="openBidBtn"><i class="fas fa-gavel"></i> Place Bid</button>
                            <button class="btn btn-outline" onclick="document.getElementById('comments').scrollIntoView({behavior: 'smooth'})"><i class="fas fa-comment"></i> Ask Question</button>
                        </div>
                    <?php endif; ?>
                </div>
                
                <div class="social-share">
                    <span><i class="fas fa-share-alt"></i> Share:</span>
                    <a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode(SITE_URL . '/product/detail.php?id=' . $product_id); ?>" target="_blank" class="social-icon"><i class="fab fa-facebook-f"></i></a>
                    <a href="https://twitter.com/intent/tweet?url=<?php echo urlencode(SITE_URL . '/product/detail.php?id=' . $product_id); ?>&text=<?php echo urlencode($product['name']); ?>" target="_blank" class="social-icon"><i class="fab fa-twitter"></i></a>
                    <a href="https://wa.me/?text=<?php echo urlencode($product['name'] . ' - ' . SITE_URL . '/product/detail.php?id=' . $product_id); ?>" target="_blank" class="social-icon"><i class="fab fa-whatsapp"></i></a>
                    <a href="mailto:?subject=<?php echo urlencode($product['name']); ?>&body=<?php echo urlencode(SITE_URL . '/product/detail.php?id=' . $product_id); ?>" class="social-icon"><i class="fas fa-envelope"></i></a>
                </div>
            </div>
        </div>
        
        <!-- Enhanced Tabs with Professional Description -->
        <div class="product-tabs">
            <div class="tab-headers">
                <button class="tab-btn active" onclick="switchTab('description')">Description</button>
                <button class="tab-btn" onclick="switchTab('bids')">Bid History (<?php echo $total_bids; ?>)</button>
                <button class="tab-btn" onclick="switchTab('comments')">Comments (<?php echo count($comments); ?>)</button>
            </div>
            
            <div id="description" class="tab-pane active">
                <div class="description-enhanced">
                    <?php 
                    // Process description to preserve HTML formatting
                    $desc = htmlspecialchars_decode($product['long_desc']);
                    
                    // Check if description already has HTML tags
                    if (!preg_match('/<(p|h2|h3|ul|ol|blockquote)/', $desc)) {
                        // Convert line breaks to paragraphs
                        $paragraphs = explode("\n\n", trim($desc));
                        $formatted = '';
                        foreach ($paragraphs as $para) {
                            $para = trim($para);
                            if (!empty($para)) {
                                // Check if line starts with heading pattern
                                if (preg_match('/^(##\s)(.+)/', $para, $matches)) {
                                    $formatted .= '<h2>' . htmlspecialchars($matches[2]) . '</h2>';
                                } elseif (preg_match('/^(###\s)(.+)/', $para, $matches)) {
                                    $formatted .= '<h3>' . htmlspecialchars($matches[2]) . '</h3>';
                                } elseif (preg_match('/^[\*\-\•]\s(.+)/', $para)) {
                                    // Handle bullet points
                                    $items = explode("\n", $para);
                                    $formatted .= '<ul>';
                                    foreach ($items as $item) {
                                        if (preg_match('/^[\*\-\•]\s(.+)/', trim($item), $item_match)) {
                                            $formatted .= '<li>' . htmlspecialchars($item_match[1]) . '</li>';
                                        }
                                    }
                                    $formatted .= '</ul>';
                                } else {
                                    $formatted .= '<p>' . nl2br(htmlspecialchars($para)) . '</p>';
                                }
                            }
                        }
                        $desc = $formatted;
                    }
                    
                    echo $desc;
                    ?>
                </div>
                <?php if ($product['tags']): ?>
                    <div class="tags">
                        <strong style="color: var(--text-muted);"><i class="fas fa-tags"></i> Tags:</strong>
                        <?php foreach (explode(',', $product['tags']) as $tag): ?>
                            <a href="tags.php?tag=<?php echo urlencode(trim($tag)); ?>" class="tag">#<?php echo htmlspecialchars(trim($tag)); ?></a>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
            
            <div id="bids" class="tab-pane">
                <?php if (count($recent_bids) > 0): ?>
                    <table class="bids-table">
                        <thead><tr><th>Bidder</th><th>Amount</th><th>Time</th></tr></thead>
                        <tbody>
                            <?php foreach ($recent_bids as $bid): ?>
                                <tr><td><i class="fas fa-user-circle"></i> <?php echo htmlspecialchars($bid['user_name']); ?></td>
                                <td class="bid-amount"><?php echo formatPrice($bid['amount']); ?></td>
                                <td><?php echo timeAgo($bid['created_at']); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <p class="text-center">No bids yet. Be the first to bid!</p>
                <?php endif; ?>
            </div>
            
            <div id="comments" class="tab-pane">
                <form method="POST" action="" class="comment-form">
                    <div style="margin-bottom: 12px;"><input type="text" name="comment_name" placeholder="Your Name" required></div>
                    <div style="margin-bottom: 12px;"><textarea name="comment_text" rows="3" placeholder="Write your comment..." required></textarea></div>
                    <button type="submit" name="post_comment" class="btn btn-primary"><i class="fas fa-paper-plane"></i> Post Comment</button>
                </form>
                <?php if (count($comments) > 0): ?>
                    <?php foreach ($comments as $comment): ?>
                        <div class="comment">
                            <div class="comment-header">
                                <span class="comment-name"><i class="fas fa-user"></i> <?php echo htmlspecialchars($comment['user_name']); ?></span>
                                <span class="comment-time"><i class="fas fa-clock"></i> <?php echo timeAgo($comment['created_at']); ?></span>
                            </div>
                            <div class="comment-text"><?php echo nl2br(htmlspecialchars($comment['comment_text'])); ?></div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p class="text-center">No comments yet. Be the first to comment!</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Bid Modal -->
<div id="bidModal" class="modal-overlay">
    <div class="modal-container">
        <div class="modal-header">
            <span class="close-modal-x" onclick="closeBidModal()">&times;</span>
            <i class="fas fa-gavel"></i>
            <h3>Place Your Bid</h3>
        </div>
        <form method="POST" action="" id="bidFormModal" onsubmit="return validateBidForm()">
            <div class="modal-body">
                <div class="form-group">
                    <label>Bid Amount (USD) *</label>
                    <input type="number" name="bid_amount" id="modal_bid_amount" class="form-control" 
                           min="<?php echo $current_highest + 1; ?>" 
                           value="<?php echo $current_highest + 1; ?>"
                           placeholder="Enter your bid amount" required>
                    <small style="color: var(--text-muted); font-size: 11px;">Minimum bid: <?php echo formatPrice($current_highest + 1); ?></small>
                </div>
                
                <hr>
                
                <div class="form-group">
                    <label>Email Address *</label>
                    <input type="email" name="email" id="modal_email" class="form-control" 
                           value="<?php echo htmlspecialchars($saved_email); ?>" 
                           placeholder="your@email.com" required>
                </div>
                
                <div class="form-group">
                    <label>Full Name *</label>
                    <input type="text" name="full_name" id="modal_fullname" class="form-control" 
                           value="<?php echo htmlspecialchars($saved_name); ?>" placeholder="John Doe" required>
                </div>
                
                <div class="form-group">
                    <label>Phone Number *</label>
                    <input type="tel" name="phone" id="modal_phone" class="form-control" placeholder="+1 234 567 8900" required>
                </div>
                
                <div class="form-group">
                    <label>Address</label>
                    <input type="text" name="address" id="modal_address" class="form-control" placeholder="Your address">
                </div>
                
                <div class="form-group">
                    <label>Payment Method *</label>
                    <select name="payment_method" id="modal_payment_method" class="form-control" required>
                        <option value="">Select Payment Method</option>
                        <?php foreach ($payment_methods as $method): ?>
                            <option value="<?php echo htmlspecialchars($method['method_name']); ?>"><?php echo htmlspecialchars($method['method_name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div id="modalPaymentFields"></div>
                
                <div class="checkbox-group">
                    <input type="checkbox" name="save_payment" id="save_payment" value="1" checked>
                    <label for="save_payment">Save this payment method for future bids</label>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="modal-btn modal-btn-secondary" onclick="closeBidModal()">Cancel</button>
                <button type="submit" name="place_bid" class="modal-btn modal-btn-primary">Place Bid</button>
            </div>
        </form>
    </div>
</div>

<!-- Toast Notification -->
<div id="toastNotification" class="toast-notification" style="display: none;">
    <i id="toastIcon"></i>
    <span class="message" id="toastMessage"></span>
    <span class="close-toast" onclick="hideToast()">&times;</span>
</div>

<script>
// Image gallery functions
function swapMainImage(src, element) {
    document.getElementById('mainImage').src = src;
    // Update active thumbnail
    document.querySelectorAll('.gallery-thumb').forEach(thumb => {
        thumb.classList.remove('active');
    });
    if (element) {
        element.classList.add('active');
    }
}

// Tab switching
function switchTab(tabId) {
    document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('active'));
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    document.getElementById(tabId).classList.add('active');
    event.target.classList.add('active');
}

// Countdown timer
function updateCountdown() {
    document.querySelectorAll('.countdown').forEach(el => {
        const endTime = el.getAttribute('data-end');
        if (!endTime) return;
        const now = new Date().getTime();
        const end = new Date(endTime).getTime();
        const distance = end - now;
        if (distance < 0) { el.innerHTML = 'Auction Ended'; return; }
        const days = Math.floor(distance / (86400000));
        const hours = Math.floor((distance % 86400000) / 3600000);
        const minutes = Math.floor((distance % 3600000) / 60000);
        const seconds = Math.floor((distance % 60000) / 1000);
        let display = '';
        if (days > 0) display += days + 'd ';
        if (hours > 0 || days > 0) display += hours + 'h ';
        if (minutes > 0 || hours > 0 || days > 0) display += minutes + 'm ';
        display += seconds + 's';
        el.innerHTML = display;
    });
}
updateCountdown();
setInterval(updateCountdown, 1000);

// Payment fields
document.getElementById('modal_payment_method').addEventListener('change', function() {
    const method = this.value;
    const container = document.getElementById('modalPaymentFields');
    if (method === 'Credit Card') {
        container.innerHTML = `<div class="payment-fields">
            <div class="form-group"><label>Name on Card</label><input type="text" name="card_name" class="form-control" required></div>
            <div class="form-row"><div class="form-group"><label>Card Number</label><input type="text" name="card_number" class="form-control" required></div>
            <div class="form-group"><label>Expiry (MM/YY)</label><input type="text" name="expiry" placeholder="MM/YY" class="form-control" required></div></div>
            <div class="form-row"><div class="form-group"><label>CVC</label><input type="text" name="cvc" class="form-control" required></div>
            <div class="form-group"><label>Zip Code</label><input type="text" name="zip_code" class="form-control" required></div></div>
        </div>`;
    } else if (method === 'Bank Transfer') {
        container.innerHTML = `<div class="payment-fields">
            <div class="form-group"><label>Account Name</label><input type="text" name="account_name" class="form-control" required></div>
            <div class="form-group"><label>Account Number</label><input type="text" name="account_number" class="form-control" required></div>
            <div class="form-row"><div class="form-group"><label>Bank Name</label><input type="text" name="bank_name" class="form-control" required></div>
            <div class="form-group"><label>Routing Number</label><input type="text" name="routing_number" class="form-control" required></div></div>
        </div>`;
    } else {
        container.innerHTML = '';
    }
});

// Form validation
function validateBidForm() {
    const bidAmount = parseFloat(document.getElementById('modal_bid_amount').value);
    const currentBid = <?php echo $current_highest; ?>;
    const minBid = currentBid + 1;
    
    if (isNaN(bidAmount) || bidAmount < minBid) {
        alert('Bid must be at least $' + minBid.toFixed(2));
        return false;
    }
    
    const email = document.getElementById('modal_email').value;
    if (!email) {
        alert('Please enter your email address');
        return false;
    }
    
    const paymentMethod = document.getElementById('modal_payment_method').value;
    if (!paymentMethod) {
        alert('Please select a payment method');
        return false;
    }
    
    const fullName = document.getElementById('modal_fullname').value;
    if (!fullName) {
        alert('Please enter your full name');
        return false;
    }
    
    const phone = document.getElementById('modal_phone').value;
    if (!phone) {
        alert('Please enter your phone number');
        return false;
    }
    
    return true;
}

// Toast functions
function showToast(type, message) {
    const toast = document.getElementById('toastNotification');
    const icon = document.getElementById('toastIcon');
    const msg = document.getElementById('toastMessage');
    icon.className = type === 'success' ? 'fas fa-check-circle' : 'fas fa-exclamation-circle';
    toast.className = 'toast-notification ' + type;
    msg.innerText = message;
    toast.style.display = 'flex';
    setTimeout(() => { toast.style.display = 'none'; }, 5000);
}

function hideToast() {
    document.getElementById('toastNotification').style.display = 'none';
}

// Modal functions
function openBidModal() {
    document.getElementById('bidModal').style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

function closeBidModal() {
    document.getElementById('bidModal').style.display = 'none';
    document.body.style.overflow = 'auto';
}

// Event listeners
document.getElementById('openBidBtn').addEventListener('click', openBidModal);

document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') closeBidModal();
});

window.onclick = function(event) {
    if (event.target === document.getElementById('bidModal')) closeBidModal();
}

// Show success toast
<?php if ($show_success_toast || isset($_GET['success'])): ?>
    showToast('success', '<?php echo addslashes($success_message ?: "Bid placed successfully!"); ?>');
    document.getElementById('currentBidDisplay').innerHTML = '<?php echo formatPrice($current_highest); ?>';
    document.getElementById('totalBidsDisplay').innerHTML = '<?php echo $total_bids; ?>';
<?php endif; ?>

<?php if (!empty($bid_error)): ?>
    showToast('error', '<?php echo addslashes($bid_error); ?>');
<?php endif; ?>
</script>

<?php require_once '../includes/footer.php'; ?>