<?php
session_start();
$host   = "webdev.iyaserver.com";
$userid = "dhreid_guest";
$userpw = "tPTG;A+J{]Ze";
$db     = "dhreid_marketplace";

$mysql = new mysqli($host, $userid, $userpw, $db);
if($mysql->connect_errno){
    echo "db connection error : " . $mysql->connect_error;
    exit();
}

if (empty($_GET['item_id'])) {
    echo "Missing item_id.";
    exit();
}
$item_id = (int)$_GET['item_id'];

$sql = "
  SELECT 
      i.*,
      c.name AS category_name,
      cc.display_label AS condition_label,
      l.label AS location_label,
      u.full_name AS seller_name,
      u.usc_email AS seller_email
  FROM items i
  JOIN categories c ON i.category_id = c.category_id
  JOIN condition_codes cc ON i.condition_code_id = cc.condition_code_id
  LEFT JOIN locations l ON i.location_id = l.location_id
  JOIN users u ON i.seller_id = u.user_id
  WHERE i.item_id = $item_id
  LIMIT 1
";
$res = $mysql->query($sql);
if(!$res){ echo "SQL error: ".$mysql->error; exit(); }

$item = $res->fetch_assoc();
if(!$item){ echo "Item not found."; exit(); }

$img_sql = "
  SELECT url, is_primary, created_at
  FROM item_images
  WHERE item_id = $item_id
  ORDER BY is_primary DESC, created_at ASC, image_id ASC
";
$img_res = $mysql->query($img_sql);
if(!$img_res){ echo "SQL error (images): ".$mysql->error; exit(); }

$images = [];
while($r = $img_res->fetch_assoc()){
    $images[] = $r['url'];
}

$mainImg = count($images) ? $images[0] : "https://via.placeholder.com/800x600?text=No+Image";

// AI
$is_saved = false;
if (isset($_SESSION['user_id'])) {
    $chk = $mysql->prepare("SELECT save_id FROM saved_items WHERE user_id = ? AND item_id = ?");
    $chk->bind_param("ii", $_SESSION['user_id'], $item_id);
    $chk->execute();
    if ($chk->get_result()->num_rows > 0) {
        $is_saved = true;
    }
}

// ===== Helpers =====
function h($s){ return htmlspecialchars($s ?? "", ENT_QUOTES, 'UTF-8'); }
function moneyFromCents($c){ return '$' . number_format(((int)$c)/100, 2); }
function fmtDate($ts){
    return date("M j, Y", strtotime($ts));
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-FEM3Q0G7NZ"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'G-FEM3Q0G7NZ');
    </script>
    <title>Product Details</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="stylesheet.css">

    <style>
        body {
            background: var(--bg);
            color: var(--text);
        }
        header{
            border-bottom: none !important;
        }

        /* Override to match search page hero/search dimensions exactly */
        main.wrap .hero,
        .wrap .hero {
            background: var(--panel);
            border: 1px solid var(--border);
            border-radius: var(--radius-lg);
            margin: 18px 0;
            padding: 22px;
            box-shadow: var(--shadow-sm);
        }

        .pageContainer{
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            border-radius: 10px;
            padding: 20px;
            margin: 50px;
            position: relative;
        }
        #backButton{
            position: absolute;
            top: 20px;
            left: 20px;
            width: 40px;
            height: 40px;
            background-color: rgb(161, 5, 5);
            color: white;
            border: none;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 20px;
            font-weight: bold;
            transition: background-color 0.2s ease, transform 0.2s ease;
            z-index: 10;
        }
        #backButton:hover{
            background-color: rgb(138, 0, 0);
            transform: scale(1.1);
        }
        #yellowLine{
            width: 100%;
            height: 4px;
            background-color: var(--gold);
        }

        .twoUp1Down{
            display:flex;
            flex-direction: column;
            background-color:rgb(255, 255, 255);
            width: 90%;
            height:fit-content;
            justify-content: center;
            align-items: center;
            padding:0;
            margin:0px auto;
            border-radius:15px;
            box-shadow: var(--shadow-md);
        }
        .leftRightContainer{
            width:100%;
            height:fit-content;
            display:flex;
            justify-content:center;
            align-items:center;
            flex-direction:row;
            padding:10px;
        }
        .rightContainer{
            background: var(--panel);
            border-radius: var(--radius-md);
            width:550px;
            height: fit-content;
            min-height:500px;
            border-radius: 10px;
            padding: 30px;
            margin: 10px;
            display:flex;
            align-items:flex-start;
            justify-content:center;
            flex-direction:column;
        }
        #dateList{
            color:rgb(170, 170, 170);
            width: 100%;
            text-align:left;
            margin: 0 0 5px 0;
        }
        #productName{
            width: 100%;
            overflow: hidden;
            text-align:start;
            margin-bottom:5px;
        }
        #productName h1{
            margin:0;
        }
        #blueDescription{
            width: 100%;
            margin-top:10px;
            margin-bottom:30px;
        }
        #contactSaveCon{
            display:flex;
            justify-content:center;
            align-items:center;
            width:100%;
            height:50px;
            gap:20px;
            margin: 10px 0px;
        }

        #contactSeller{
            width:230px;
            height:40px;
            background-color:rgb(161, 5, 5);
            border-radius: 5px;
            text-align: center;
            display:flex;
            justify-content:center;
            align-items:center;
            cursor: pointer;
            transition: background-color 0.2s ease;
        }
        #contactSeller:hover{
            background-color: rgb(138, 0, 0);
        }
        #contactSeller p{
            color:white;
        }
        #messageBox{
            width: 100%;
            margin-top: 20px;
            padding: 15px;
            border: 1px solid rgb(234, 234, 234);
            border-radius: 10px;
            background-color: rgb(255, 255, 255);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            max-height: 0;
            opacity: 0;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            gap: 10px;
            transition: max-height 0.4s ease, opacity 0.4s ease, margin-top 0.4s ease, padding 0.4s ease;
            margin-top: 0;
            padding-top: 0;
            padding-bottom: 0;
        }
        #messageBox.visible{
            max-height: 300px;
            opacity: 1;
            margin-top: 20px;
            padding-top: 15px;
            padding-bottom: 15px;
        }
        #messageTextarea{
            width: 100%;
            min-height: 100px;
            padding: 10px;
            border: 1px solid rgb(234, 234, 234);
            border-radius: 5px;
            font-family: inherit;
            font-size: 14px;
            resize: vertical;
            box-sizing: border-box;
        }
        #messageTextarea:focus{
            outline: none;
            border-color: rgb(161, 5, 5);
        }
        #sendMessageBtn{
            width: 120px;
            height: 35px;
            background-color: rgb(161, 5, 5);
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 600;
            transition: background-color 0.2s ease;
            align-self: flex-end;
        }
        #sendMessageBtn:hover{
            background-color: rgb(138, 0, 0);
        }

        #save{
            width:230px;
            height:40px;
            max-height: fit-content;
            border: 1px solid rgb(161, 5, 5);
            border-radius:5px;
            padding:5px;
            text-align: center;
            justify-content: center;
            align-items: center;
            display: flex;
            overflow-wrap:break-word;
            cursor: pointer;
            transition: background-color 0.2s ease, border-color 0.2s ease, color 0.2s ease;
        }
        #save:hover{
            background-color: rgb(161, 5, 5);
            border-color: rgb(138, 0, 0);
        }
        #save:hover p{
            color: white;
        }
        #save p{
            color:rgb(161, 5, 5);
            text-overflow: clip;
            transition: color 0.2s ease;
        }

        #save.saved-active {
            background-color: rgb(161, 5, 5);
            border-color: rgb(138, 0, 0);
        }
        #save.saved-active p {
            color: white;
        }

        #price{
            width:100px;
            height:50px;
            border-radius:5px;
            text-align: left;
            justify-content: flex-start;
            align-items: center;
            display: flex;
            overflow-wrap:break-word;
            margin-top:35px;
            margin-bottom:15px;
        }
        #price p{
            font-size: 1.7em;
            color:black;
            font-weight:bold;
        }
        #pickUpLoc{
            color:rgb(100, 100, 100);
            margin:0px;
        }
        #location{
            width:230px;
            height:40px;
            max-height: fit-content;
            border: 1px solid rgb(137, 137, 137);
            border-radius:5px;
            padding:5px;
            text-align: center;
            justify-content: center;
            align-items: center;
            display: flex;
            overflow-wrap:break-word;
            cursor: pointer;
            transition: background-color 0.2s ease, border-color 0.2s ease, color 0.2s ease;
        }
        #location:hover{
            background-color: rgb(225, 224, 224);
            border-color: rgb(161, 5, 5);
        }
        #location:hover p{
            color: rgb(161, 5, 5);
        }
        #location p{
            transition: color 0.2s ease;
        }
        #notesFromSellerCon{
            display:flex;
            width:90%;
            border: 1px solid rgb(234, 234, 234);
            border-radius:10px;
            max-height:100px;
            margin-bottom:60px;
            padding:10px;
            flex-direction:column;
            cursor: pointer;
            overflow: hidden;
            transition: max-height 0.3s ease, background-color 0.3s ease, border-color 0.3s ease, box-shadow 0.3s ease;
        }
        #notesFromSellerCon:hover{
            background-color: rgb(237, 237, 237);
            border-color: rgb(138, 0, 0);
            box-shadow: 0 2px 8px rgba(134, 0, 0, 0.1);
        }
        #notesFromSellerCon.expanded{
            max-height: 1000px;
        }
        .line {
            width: 13%;
            height: 2px;
            background-color: rgb(186, 186, 186);
            margin:0px;
            align-self: center;
            padding:0px;
        }

        #notesFromSellerCon p{
            color:rgb(102, 102, 102);
            margin:0px;
            padding:0px;
            font-weight: bold;
            text-align:center;
        }
        #notes{
            overflow:hidden;
            padding:10px;
        }
        #notesFromSellerCon.expanded #notes{
            overflow:visible;
        }
        #notes p{
            text-align:left;
            font-weight:lighter;
            color:black;
        }

        .leftContainer{
            display:flex;
            flex-direction:column;
            align-items: center;
            width:600px;
            height: 700px;
            border-radius: 10px;
            padding: 30px;
            margin: 20px;
        }
        #bigPicture{
            width:100%;
            height:80%;
            background-color:yellow;
            border-radius: 10px;
            margin-bottom:25px;
            overflow: hidden;
            position: relative;
        }
        #bigPicture img{
            width: 100%;
            height: 100%;
            object-fit: cover;
            display: block;
        }
        #smallPicsContainer{
            display: flex;
            justify-content:center;
            flex-direction:row;
            width:100%;
            height:20%;
            border-radius: 10px;
            gap:5px;
        }
        .smallPictures{
            width:90px;
            height:90px;
            margin:10px;
            border-radius: 10px;
            object-fit: cover;
            cursor: pointer;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
        }
        .smallPictures:hover{
            transform: scale(1.05);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
        }
        .smallPictures img{
            width: 100%;
            height: 100%;
            object-fit: cover;
            display: block;
            border-radius: 10px;
        }
    </style>
</head>

<body>
<header>
    <!-- Google tag (gtag.js) -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-FEM3Q0G7NZ"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'G-FEM3Q0G7NZ');
    </script>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>USC Student Marketplace</title>
    <link rel="stylesheet" href="stylesheet.css">

    <?php include 'nav.php'; ?>
</header>


<main class="wrap">
    <section class="hero">
        <form class="search" method="get" action="search.php">
            <label class="sr-only" for="q">Search</label>
            <input
                    id="q"
                    name="q"
                    type="text"
                    placeholder="Search for laptops, bikes, furniture..."
            />
            <button type="submit">Search</button>
        </form>
    </section>
</main>


<div class="pageContainer">

    <button id="backButton">←</button>

    <div class="twoUp1Down">
        <div class="leftRightContainer">

            <div class="leftContainer">
                <div id="bigPicture">
                    <img id="mainImage" src="<?php echo h($mainImg); ?>">
                </div>

                <div id="smallPicsContainer">
                    <?php if(count($images)): ?>
                        <?php foreach($images as $url): ?>
                            <div class="smallPictures">
                                <img src="<?php echo h($url); ?>">
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <!-- if no images, still render 1 thumb -->
                        <div class="smallPictures">
                            <img src="<?php echo h($mainImg); ?>">
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="rightContainer">
                <div id="dateList">
                    <p><?php echo h(fmtDate($item['created_at'])); ?></p>
                </div>

                <div id="productName">
                    <h1><?php echo h($item['title']); ?></h1>
                </div>

                <div id="blueDescription">
                    <?php echo h($item['description']); ?>
                </div>

                <div id="contactSaveCon">
                    <div id="contactSeller">
                        <p>Contact Seller</p>
                    </div>
                    <div id="save" class="<?php echo $is_saved ? 'saved-active' : ''; ?>">
                        <p><?php echo $is_saved ? '♥ Saved' : '♡ Save'; ?></p>
                    </div>
                </div>

                <div id="messageBox">
                    <textarea id="messageTextarea" placeholder="Type your message here."></textarea>
                    <button id="sendMessageBtn">Send</button>
                </div>

                <div id="price">
                    <p><?php echo h(moneyFromCents($item['price_cents'])); ?></p>
                </div>

                <div id="pickUpLoc">
                    <p>Pick-up Location</p>
                </div>

                <div id="location">
                    <p><?php echo h($item['location_label'] ?? "Anywhere"); ?></p>
                </div>
            </div>
        </div>

        <div id="notesFromSellerCon">
            <p>Note from Seller</p>
            <div class="line"></div>
            <div id="notes">
                <p><?php echo nl2br(h($item['description'])); ?></p>
            </div>
        </div>
    </div>
</div>

<script>
    document.getElementById('notesFromSellerCon').addEventListener('click', function() {
        this.classList.toggle('expanded');
    });

    const smallPictures = document.querySelectorAll('.smallPictures img');
    const mainImage = document.getElementById('mainImage');

    smallPictures.forEach(function(smallPic) {
        smallPic.addEventListener('click', function() {
            mainImage.src = this.src;
        });
    });

    const contactSellerBtn = document.getElementById('contactSeller');
    const messageBox = document.getElementById('messageBox');
    const sendMessageBtn = document.getElementById('sendMessageBtn');
    const messageTextarea = document.getElementById('messageTextarea');

    contactSellerBtn.addEventListener('click', function(e) {
        e.stopPropagation();
        messageBox.classList.toggle('visible');
    });

    sendMessageBtn.addEventListener('click', function() {
        const message = messageTextarea.value.trim();
        if (message) {
            alert('Message sent: ' + message);
            messageTextarea.value = '';
            messageBox.classList.remove('visible');
        } else {
            alert('Please enter a message before sending.');
        }
    });

    const locationContainer = document.getElementById('location');
    locationContainer.addEventListener('click', function() {
        const mapUrl = 'https://maps.app.goo.gl/abC24oSgsMeLEqQG7';
        window.open(mapUrl, '_blank');
    });

    const backButton = document.getElementById('backButton');
    backButton.addEventListener('click', function() {
        window.location.href = 'search.php';
    });

    const saveBtn = document.getElementById('save');
    const saveText = saveBtn.querySelector('p');

    saveBtn.addEventListener('click', function() {
        fetch('toggle_save.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ item_id: <?php echo $item_id; ?> })
        })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    if (data.status === 'saved') {
                        saveBtn.classList.add('saved-active');
                        saveText.textContent = '♥ Saved';
                    } else {
                        saveBtn.classList.remove('saved-active');
                        saveText.textContent = '♡ Save';
                    }
                } else if (data.error === 'not_logged_in') {
                    alert("Please log in to save items.");
                    window.location.href = 'loginPage.php';
                }
            })
            .catch(err => console.error(err));
    });
</script>

</body>
</html>