<?php
// edit_item.php
require 'config/db.php';


// 1. Security Check using 'role'
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$user_id = $_SESSION['user_id'];

if (!isset($_GET['id'])) {
    header("Location: my_inventory.php");
    exit;
}

$product_id = $_GET['id'];

// 2. Fetch product and validate ownership
$stmt = $pdo->prepare("SELECT * FROM products WHERE id = ? AND seller_id = ?");
$stmt->execute([$product_id, $user_id]);
$product = $stmt->fetch();

if (!$product) {
    header("Location: my_inventory.php?error=notfound");
    exit;
}

// 3. Process Update Actions
if (isset($_POST['update_item'])) {
    $title = $_POST['title'];
    $price = $_POST['price'];
    $stock = $_POST['stock']; 
    $description = $_POST['description'];
    
    // Defensive check for 'image' column
    $image_path = isset($product['image']) ? $product['image'] : null; 

    // Image Upload Logic
    if (!empty($_FILES['image']['name'])) {
        $target_dir = "uploads/products/";
        if (!is_dir($target_dir)) {
            mkdir($target_dir, 0777, true);
        }
        
        $file_ext = strtolower(pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION));
        $new_file_name = "item_" . uniqid() . "." . $file_ext;
        $target_file = $target_dir . $new_file_name;

        $allowed = ['jpg', 'jpeg', 'png', 'webp'];
        if (in_array($file_ext, $allowed)) {
            if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
                // Delete old image if exists
                if ($image_path && file_exists($image_path)) {
                    unlink($image_path);
                }
                $image_path = $target_file;
            }
        }
    }

    try {
        // UPDATE including Stock
        $stmt = $pdo->prepare("UPDATE products SET title = ?, price = ?, stock = ?, description = ?, image = ? WHERE id = ? AND seller_id = ?");
        $stmt->execute([$title, $price, $stock, $description, $image_path, $product_id, $user_id]);
        header("Location: my_inventory.php?status=updated");
        exit;
    } catch (PDOException $e) {
        $error_msg = "Database Error: " . $e->getMessage();
    }
}

include 'includes/header.php';
?>

<style>
    /* VVAULT Global Colors */
    :root {
        --v-bg: #0d1117;
        --v-card: #161b22;
        --v-accent: #00ff88;
        --v-border: #30363d;
        --v-text-gray: #8b949e;
    }
    
    body { background-color: var(--v-bg); color: white; font-family: 'Inter', sans-serif; margin: 0; }
    
    /* Main Layout Container */
    .v-container { max-width: 900px; margin: 60px auto; padding: 0 20px; box-sizing: border-box; }
    
    /* Header Styles */
    .v-header-flex { display: flex; justify-content: space-between; align-items: center; margin-bottom: 35px; flex-wrap: wrap; gap: 15px; }
    .v-title { margin: 0; font-family: 'Syncopate', sans-serif; font-size: 22px; font-weight: 900; letter-spacing: -1px; text-transform: uppercase; }
    .v-title span { color: var(--v-accent); }
    
    /* Form Card */
    .v-card { background: var(--v-card); border: 1px solid var(--v-border); padding: 40px; border-radius: 16px; box-sizing: border-box; }
    
    /* Input Styles */
    .v-input-group { margin-bottom: 25px; }
    .v-input { 
        width: 100%; background: #0d1117; border: 1px solid var(--v-border); color: white; 
        padding: 14px 18px; border-radius: 8px; font-size: 14px; outline: none; transition: 0.3s; box-sizing: border-box; margin-top: 10px;
    }
    .v-input:focus { border-color: var(--v-accent); box-shadow: 0 0 10px rgba(0, 255, 136, 0.1); }

    /* Button Styles */
    .v-btn-primary { 
        background: var(--v-accent); color: #0d1117; border: none; padding: 16px; 
        border-radius: 8px; font-weight: 800; cursor: pointer; text-transform: uppercase; width: 100%; font-size: 13px; transition: 0.3s; letter-spacing: 1px;
    }
    .v-btn-primary:hover { transform: translateY(-2px); box-shadow: 0 5px 20px rgba(0, 255, 136, 0.3); }

    .btn-view { 
        background: rgba(56, 139, 253, 0.1); color: #388bfd; border: 1px solid rgba(56, 139, 253, 0.3); 
        padding: 10px 18px; border-radius: 8px; text-decoration: none; font-size: 11px; font-weight: 800; 
        text-transform: uppercase; display: inline-flex; align-items: center; gap: 8px; transition: 0.3s;
    }
    .btn-view:hover { background: #388bfd; color: white; }

    /* Image Section Styles */
    .image-upload-section { display: flex; gap: 30px; align-items: flex-start; margin-bottom: 30px; flex-wrap: wrap; }
    .img-box { width: 150px; height: 150px; border-radius: 12px; object-fit: cover; border: 1px solid var(--v-border); background: #0d1117; flex-shrink: 0; }
    
    /* Label Styles */
    .label-mini { font-size: 10px; font-weight: 800; color: var(--v-text-gray); text-transform: uppercase; letter-spacing: 1.5px; display: block; }
    
    /* Grid for Price/Stock - Prevents overlap */
    .v-grid-fields { display: grid; grid-template-columns: 1fr 1fr; gap: 25px; width: 100%; }

    /* Price input specific spacing */
    .price-input-wrapper { position: relative; width: 100%; }
    .currency-symbol { position: absolute; left: 15px; top: calc(50% + 5px); transform: translateY(-50%); color: var(--v-text-gray); font-size: 14px; }

    /* Responsive adjustments */
    @media (max-width: 600px) {
        .image-upload-section { justify-content: center; text-align: center; }
        .v-grid-fields { grid-template-columns: 1fr; gap: 15px; }
        .v-card { padding: 25px; }
    }
</style>

<div class="v-container">
    <?php if(isset($error_msg)): ?>
        <div style="background: rgba(255, 77, 77, 0.1); color: #ff4d4d; padding: 15px; border-radius: 8px; border: 1px solid #ff4d4d; margin-bottom: 25px; font-size: 13px;">
            <i class="fa-solid fa-triangle-exclamation"></i> <?= $error_msg ?>
        </div>
    <?php endif; ?>

    <div class="v-header-flex">
        <div>
            <h1 class="v-title">EDIT <span>VAULT ITEM</span></h1>
            <a href="my_inventory.php" style="color: var(--v-text-gray); font-size: 12px; text-decoration: none; margin-top: 8px; display: inline-block;">
                <i class="fa-solid fa-arrow-left"></i> RETURN TO INVENTORY
            </a>
        </div>
        
        <a href="product_view.php?id=<?= $product['id'] ?>" class="btn-view" target="_blank">
            <i class="fa-solid fa-up-right-from-square"></i> LIVE PREVIEW
        </a>
    </div>

    <div class="v-card">
        <form method="POST" enctype="multipart/form-data">
            
            <div class="image-upload-section">
                <div style="flex-shrink: 0; text-align: center; width: 150px;">
                    <span class="label-mini">Cover Image</span>
                    <div style="margin-top: 15px;">
                        <?php 
                            $display_img = (!empty($product['image']) && file_exists($product['image'])) ? $product['image'] : 'assets/img/no-image.png';
                        ?>
                        <img src="<?= $display_img ?>" class="img-box" id="preview">
                        <input type="file" name="image" id="file-upload" style="display:none" onchange="previewImage(this)">
                        <label for="file-upload" style="display: block; margin-top: 12px; font-size: 11px; color: var(--v-accent); cursor: pointer; font-weight: 700;">
                            <i class="fa-solid fa-camera"></i> CHANGE PHOTO
                        </label>
                    </div>
                </div>
                
                <div style="flex-grow: 1; min-width: 280px;">
                    <div class="v-input-group">
                        <label class="label-mini">Product Title</label>
                        <input type="text" name="title" value="<?= htmlspecialchars($product['title']) ?>" class="v-input" required placeholder="e.g. 1000 Gold Coins">
                    </div>
                    
                    <div class="v-grid-fields">
                        <div class="v-input-group">
                            <label class="label-mini">Price (USD)</label>
                            <div class="price-input-wrapper">
                                <span class="currency-symbol">$</span>
                                <input type="number" step="0.01" name="price" value="<?= $product['price'] ?>" class="v-input" style="padding-left: 35px;" required>
                            </div>
                        </div>
                        <div class="v-input-group">
                            <label class="label-mini">Available Stock</label>
                            <input type="number" name="stock" value="<?= isset($product['stock']) ? $product['stock'] : 1 ?>" class="v-input" required min="0" placeholder="0">
                        </div>
                    </div>
                </div>
            </div>

            <div class="v-input-group" style="margin-bottom: 15px;">
                <label class="label-mini">Description & Details</label>
                <textarea name="description" class="v-input" rows="8" required placeholder="Describe your item in detail..."><?= htmlspecialchars($product['description']) ?></textarea>
            </div>

            <button type="submit" name="update_item" class="v-btn-primary">Update Vault Entry</button>
        </form>
    </div>
</div>

<script>
    // Image preview before upload
    function previewImage(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('preview').src = e.target.result;
            }
            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

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