<?php
session_start();
require_once('../includes/vendor-security.php');
include_once('../../includes/config.php');

$vendorId = $_SESSION['vendor_id'];
$productId = intval($_GET['id']);

// Verify ownership
$ownerCheck = mysqli_query($con, "SELECT * FROM products WHERE id='$productId' AND vendor_id='$vendorId'");
if (mysqli_num_rows($ownerCheck) == 0) {
    echo "<script>alert('Unauthorized access!'); window.location.href='manage-products.php';</script>";
    exit;
}

if (isset($_POST['submit'])) {
    $category = db_prepare($con, $_POST['category']);
    $subCategory = db_prepare($con, $_POST['subcategory']);
    $productName = db_prepare($con, $_POST['productName']);
    $productCompany = db_prepare($con, $_POST['productCompany']);
    $productPrice = db_prepare($con, $_POST['productprice']);
    $productPriceBeforeDiscount = db_prepare($con, $_POST['productpricebd']);
    $productDescription = db_prepare($con, $_POST['productDescription']);
    $productLocation = db_prepare($con, $_POST['productLocation']);
    $productAvailability = db_prepare($con, $_POST['productAvailability']);
    $stockQuantity = intval($_POST['stock_quantity']);
    $sku = db_prepare($con, $_POST['sku']);

    // Update product - reset approval status if major changes
    $sql = mysqli_query($con, "UPDATE products SET 
                               category='$category',
                               subCategory='$subCategory',
                               productName='$productName',
                               productCompany='$productCompany',
                               productPrice='$productPrice',
                               productPriceBeforeDiscount='$productPriceBeforeDiscount',
                               productDescription='$productDescription',
                               productAvailability='$productAvailability',
                               stock_quantity='$stockQuantity',
                               product_location='$productLocation',
                               sku='$sku'
                               WHERE id='$productId' AND vendor_id='$vendorId'");

    // Handle image uploads if new images provided
    $dir = "../../__admin__/productimages/$productId";

    if (!empty($_FILES["productimage1"]["name"])) {
        $productimage1 = $_FILES["productimage1"]["name"];
        
        // Fetch old image to delete it from disk
        $oldImgQuery = mysqli_query($con, "SELECT productImage1 FROM products WHERE id='$productId'");
        $oldImgRow = mysqli_fetch_assoc($oldImgQuery);
        $oldImageName = $oldImgRow['productImage1'];
        if (!empty($oldImageName) && file_exists("$dir/" . $oldImageName)) {
            unlink("$dir/" . $oldImageName);
        }

        move_uploaded_file($_FILES["productimage1"]["tmp_name"], "$dir/" . $productimage1);
        mysqli_query($con, "UPDATE products SET productImage1='$productimage1' WHERE id='$productId'");
    }

    if (!empty($_FILES["productimage2"]["name"])) {
        $productimage2 = $_FILES["productimage2"]["name"];

        // Fetch old image to delete it from disk
        $oldImgQuery = mysqli_query($con, "SELECT productImage2 FROM products WHERE id='$productId'");
        $oldImgRow = mysqli_fetch_assoc($oldImgQuery);
        $oldImageName = $oldImgRow['productImage2'];
        if (!empty($oldImageName) && file_exists("$dir/" . $oldImageName)) {
            unlink("$dir/" . $oldImageName);
        }

        move_uploaded_file($_FILES["productimage2"]["tmp_name"], "$dir/" . $productimage2);
        mysqli_query($con, "UPDATE products SET productImage2='$productimage2' WHERE id='$productId'");
    }

    if (!empty($_FILES["productimage3"]["name"])) {
        $productimage3 = $_FILES["productimage3"]["name"];

        // Fetch old image to delete it from disk
        $oldImgQuery = mysqli_query($con, "SELECT productImage3 FROM products WHERE id='$productId'");
        $oldImgRow = mysqli_fetch_assoc($oldImgQuery);
        $oldImageName = $oldImgRow['productImage3'];
        if (!empty($oldImageName) && file_exists("$dir/" . $oldImageName)) {
            unlink("$dir/" . $oldImageName);
        }

        move_uploaded_file($_FILES["productimage3"]["tmp_name"], "$dir/" . $productimage3);
        mysqli_query($con, "UPDATE products SET productImage3='$productimage3' WHERE id='$productId'");
    }

    if ($sql) {
        log_activity("Vendor Updated Product", "Product ID: $productId, Name: $productName", "vendor");
    }

    echo "<script>alert('Product updated successfully!');</script>";
    echo "<script>window.location.href='manage-products.php'</script>";
}

// Get product data
$product = mysqli_fetch_array($ownerCheck);
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Edit Product - Vendor Portal</title>
    <link href="../../__admin__/css/styles.css" rel="stylesheet" />
    <link href="../../__admin__/css/admin-professional.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"></script>
</head>

<body class="sb-nav-fixed">
    <?php include_once('../includes/header.php'); ?>

    <div id="layoutSidenav">
        <?php include_once('../includes/sidebar.php'); ?>

        <div id="layoutSidenav_content">
            <main>
                <div class="container-fluid px-4">
                    <div class="page-header mt-4">
                        <div>
                            <h1><i class="fas fa-edit me-2"></i> Edit Product</h1>
                            <p>Update product information</p>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="table-card">
                                <div class="card-header">
                                    <h5 class="mb-0">Product Information</h5>
                                </div>
                                <div class="card-body">
                                    <form method="post" enctype="multipart/form-data">
                                        <div class="row">
                                            <!-- Category -->
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label fw-semibold">Category</label>
                                                <select name="category" id="category" class="form-select" required
                                                    onChange="getSubCat(this.value);">
                                                    <option value="">Select Category</option>
                                                    <?php
                                                    $query = mysqli_query($con, "SELECT * FROM category");
                                                    while ($row = mysqli_fetch_array($query)) {
                                                        $selected = ($row['id'] == $product['category']) ? 'selected' : '';
                                                        echo "<option value='{$row['id']}' $selected>" . htmlentities($row['categoryName']) . "</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>

                                            <!-- Sub Category -->
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label fw-semibold">Sub Category</label>
                                                <select name="subcategory" id="subcategory" class="form-select"
                                                    required>
                                                    <?php
                                                    $subQuery = mysqli_query($con, "SELECT * FROM subcategory WHERE categoryid='{$product['category']}'");
                                                    while ($subRow = mysqli_fetch_array($subQuery)) {
                                                        $selected = ($subRow['id'] == $product['subCategory']) ? 'selected' : '';
                                                        echo "<option value='{$subRow['id']}' $selected>" . htmlentities($subRow['subcategory']) . "</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>

                                            <!-- Product Name -->
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label fw-semibold">Product Name</label>
                                                <input type="text" name="productName" class="form-control"
                                                    value="<?php echo htmlentities($product['productName']); ?>"
                                                    required>
                                            </div>

                                            <!-- SKU -->
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label fw-semibold">SKU</label>
                                                <input type="text" name="sku" class="form-control"
                                                    value="<?php echo htmlentities($product['sku']); ?>">
                                            </div>

                                            <!-- Company/Brand -->
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label fw-semibold">Brand/Company</label>
                                                <input type="text" name="productCompany" class="form-control"
                                                    value="<?php echo htmlentities($product['productCompany']); ?>">
                                            </div>

                                            <!-- Stock Quantity -->
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label fw-semibold">Stock Quantity</label>
                                                <input type="number" name="stock_quantity" class="form-control"
                                                    value="<?php echo $product['stock_quantity']; ?>" min="0" required>
                                            </div>

                                            <!-- Price -->
                                            <div class="col-md-3 mb-3">
                                                <label class="form-label fw-semibold">Original Price (₵)</label>
                                                <input type="number" name="productpricebd" id="productpricebd"
                                                    class="form-control"
                                                    value="<?php echo $product['productPriceBeforeDiscount']; ?>"
                                                    step="0.01" oninput="calculateFinalPrice()">
                                            </div>

                                            <div class="col-md-3 mb-3">
                                                <label class="form-label fw-semibold">Discount (%)</label>
                                                <?php
                                                $disc = 0;
                                                if ($product['productPriceBeforeDiscount'] > 0 && $product['productPriceBeforeDiscount'] > $product['productPrice']) {
                                                    $disc = round((($product['productPriceBeforeDiscount'] - $product['productPrice']) / $product['productPriceBeforeDiscount']) * 100);
                                                }
                                                ?>
                                                <input type="number" name="productDiscount" id="productDiscount"
                                                    class="form-control" value="<?php echo $disc; ?>"
                                                    oninput="calculateFinalPrice()">
                                            </div>

                                            <div class="col-md-3 mb-3">
                                                <label class="form-label fw-semibold">Selling Price (₵)</label>
                                                <input type="number" name="productprice" id="productprice"
                                                    class="form-control" value="<?php echo $product['productPrice']; ?>"
                                                    step="0.01" readonly required>
                                            </div>

                                            <!-- Location -->
                                            <div class="col-md-3 mb-3">
                                                <label class="form-label fw-semibold">Location (City)</label>
                                                <select name="productLocation" class="form-select" required>
                                                    <option value="">Select Location</option>
                                                    <?php
                                                    $query_loc = mysqli_query($con, "SELECT city_name FROM cities ORDER BY city_name ASC");
                                                    while ($row_loc = mysqli_fetch_array($query_loc)) {
                                                        $selected = ($row_loc['city_name'] == $product['product_location']) ? 'selected' : '';
                                                        echo "<option value='" . htmlentities($row_loc['city_name']) . "' $selected>" . htmlentities($row_loc['city_name']) . "</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>

                                            <!-- Availability -->
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label fw-semibold">Availability</label>
                                                <select name="productAvailability" class="form-select" required>
                                                    <option value="In Stock" <?php echo ($product['productAvailability'] == 'In Stock') ? 'selected' : ''; ?>
                                                        >In Stock</option>
                                                    <option value="Out of Stock" <?php echo ($product['productAvailability'] == 'Out of Stock') ? 'selected' : ''; ?>>Out of Stock</option>
                                                </select>
                                            </div>

                                            <!-- Product Description -->
                                            <div class="col-md-12 mb-3">
                                                <label class="form-label fw-semibold">Product Description</label>
                                                <textarea name="productDescription" class="form-control" rows="4"
                                                    required><?php echo htmlentities($product['productDescription']); ?></textarea>
                                            </div>

                                            <!-- Current Images -->
                                            <div class="col-md-12 mb-3">
                                                <label class="form-label fw-semibold">Current Images</label>
                                                <div class="row">
                                                    <?php if ($product['productImage1']): ?>
                                                        <div class="col-md-2">
                                                            <img src="../../__admin__/productimages/<?php echo $product['id']; ?>/<?php echo $product['productImage1']; ?>"
                                                                class="img-thumbnail" alt="Image 1">
                                                        </div>
                                                    <?php endif; ?>
                                                    <?php if ($product['productImage2']): ?>
                                                        <div class="col-md-2">
                                                            <img src="../../__admin__/productimages/<?php echo $product['id']; ?>/<?php echo $product['productImage2']; ?>"
                                                                class="img-thumbnail" alt="Image 2">
                                                        </div>
                                                    <?php endif; ?>
                                                    <?php if ($product['productImage3']): ?>
                                                        <div class="col-md-2">
                                                            <img src="../../__admin__/productimages/<?php echo $product['id']; ?>/<?php echo $product['productImage3']; ?>"
                                                                class="img-thumbnail" alt="Image 3">
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>

                                            <!-- Update Images -->
                                            <div class="col-md-12 mb-3">
                                                <label class="form-label fw-semibold">Update Images (Optional)</label>
                                                <div class="row">
                                                    <div class="col-md-4 mb-2">
                                                        <label class="form-label">Image 1</label>
                                                        <input type="file" name="productimage1" class="form-control">
                                                    </div>
                                                    <div class="col-md-4 mb-2">
                                                        <label class="form-label">Image 2</label>
                                                        <input type="file" name="productimage2" class="form-control">
                                                    </div>
                                                    <div class="col-md-4 mb-2">
                                                        <label class="form-label">Image 3</label>
                                                        <input type="file" name="productimage3" class="form-control">
                                                    </div>
                                                </div>
                                                <small class="text-muted">Leave empty to keep current images</small>
                                            </div>
                                        </div>

                                        <button type="submit" name="submit" class="btn btn-primary">
                                            <i class="fas fa-save me-2"></i>Update Product
                                        </button>
                                        <a href="manage-products.php" class="btn btn-secondary">
                                            <i class="fas fa-times me-2"></i>Cancel
                                        </a>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </main>
            <?php include_once('../includes/footer.php'); ?>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="../../__admin__/js/scripts.js"></script>

    <script>
        function getSubCat(val) {
            fetch('get-subcategory.php?catid=' + val)
                .then(response => response.text())
                .then(data => {
                    document.getElementById("subcategory").innerHTML = data;
                });
        }

        // Price calculation
        function calculateFinalPrice() {
            var originalPrice = parseFloat(document.getElementById('productpricebd').value) || 0;
            var discountPercent = parseFloat(document.getElementById('productDiscount').value) || 0;

            if (originalPrice > 0) {
                var discountAmount = (originalPrice * discountPercent) / 100;
                var finalPrice = originalPrice - discountAmount;
                document.getElementById('productprice').value = finalPrice.toFixed(2);
            } else {
                document.getElementById('productprice').value = '';
            }
        }
    </script>
</body>

</html>