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

if (isset($_POST['submit'])) {
    $vendorId = $_SESSION['vendor_id'];
    $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']);

    // Insert product
    $sql = mysqli_query($con, "INSERT INTO products(vendor_id, category, subCategory, productName, productCompany, 
                                                     productPrice, productPriceBeforeDiscount, productDescription, 
                                                     productAvailability, stock_quantity, sku, 
                                                     approval_status, postingDate, product_location) 
                               VALUES('$vendorId', '$category', '$subCategory', '$productName', '$productCompany', 
                                      '$productPrice', '$productPriceBeforeDiscount', '$productDescription', 
                                      '$productAvailability', '$stockQuantity', '$sku', 
                                      'pending', CURRENT_TIMESTAMP, '$productLocation')");

    $lastInsertId = mysqli_insert_id($con);

    if ($lastInsertId) {
        // Handle image uploads
        $productimage1 = $_FILES["productimage1"]["name"];
        $productimage2 = $_FILES["productimage2"]["name"];
        $productimage3 = $_FILES["productimage3"]["name"];

        // Create directory for product images
        $dir = "../../__admin__/productimages/$lastInsertId";
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }

        // Move uploaded files
        move_uploaded_file($_FILES["productimage1"]["tmp_name"], "$dir/" . $productimage1);
        move_uploaded_file($_FILES["productimage2"]["tmp_name"], "$dir/" . $productimage2);
        move_uploaded_file($_FILES["productimage3"]["tmp_name"], "$dir/" . $productimage3);

        // Update product with image names
        mysqli_query($con, "UPDATE products SET productImage1='$productimage1', productImage2='$productimage2', 
                           productImage3='$productimage3' WHERE id='$lastInsertId'");

        log_activity("Vendor Added Product", "Product Name: $productName, SKU: $sku", "vendor");

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

<!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>Add 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-plus me-2"></i> Add New Product</h1>
                            <p>Add a new product to your store</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 <span
                                                        class="text-danger">*</span></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)) {
                                                        echo "<option value='{$row['id']}'>" . htmlentities($row['categoryName']) . "</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>

                                            <!-- Sub Category -->
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label fw-semibold">Sub Category <span
                                                        class="text-danger">*</span></label>
                                                <select name="subcategory" id="subcategory" class="form-select"
                                                    required>
                                                    <option value="">Select Subcategory</option>
                                                </select>
                                            </div>

                                            <!-- Product Name -->
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label fw-semibold">Product Name <span
                                                        class="text-danger">*</span></label>
                                                <input type="text" name="productName" class="form-control" required>
                                            </div>

                                            <!-- SKU -->
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label fw-semibold">SKU (Stock Keeping Unit)</label>
                                                <input type="text" name="sku" class="form-control"
                                                    placeholder="e.g., PROD-12345">
                                            </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">
                                            </div>

                                            <!-- Stock Quantity -->
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label fw-semibold">Stock Quantity <span
                                                        class="text-danger">*</span></label>
                                                <input type="number" name="stock_quantity" class="form-control" min="0"
                                                    required>
                                            </div>

                                            <!-- Price -->
                                            <div class="col-md-3 mb-3">
                                                <label class="form-label fw-semibold">Original Price (₵) <span
                                                        class="text-danger">*</span></label>
                                                <input type="number" name="productpricebd" id="productpricebd"
                                                    class="form-control" step="0.01" required
                                                    oninput="calculateFinalPrice()">
                                            </div>

                                            <div class="col-md-3 mb-3">
                                                <label class="form-label fw-semibold">Discount (%)</label>
                                                <input type="number" name="productDiscount" id="productDiscount"
                                                    class="form-control" placeholder="0"
                                                    oninput="calculateFinalPrice()">
                                            </div>

                                            <div class="col-md-3 mb-3">
                                                <label class="form-label fw-semibold">Selling Price (₵) <span
                                                        class="text-danger">*</span></label>
                                                <input type="number" name="productprice" id="productprice"
                                                    class="form-control" step="0.01" readonly required>
                                            </div>

                                            <!-- Location -->
                                            <div class="col-md-3 mb-3">
                                                <label class="form-label fw-semibold">Location <span
                                                        class="text-danger">*</span></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)) {
                                                        echo "<option value='" . htmlentities($row_loc['city_name']) . "'>" . htmlentities($row_loc['city_name']) . "</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>

                                            <!-- Availability -->
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label fw-semibold">Availability <span
                                                        class="text-danger">*</span></label>
                                                <select name="productAvailability" class="form-select" required>
                                                    <option value="In Stock">In Stock</option>
                                                    <option value="Out of Stock">Out of Stock</option>
                                                </select>
                                            </div>

                                            <!-- Product Description -->
                                            <div class="col-md-12 mb-3">
                                                <label class="form-label fw-semibold">Product Description <span
                                                        class="text-danger">*</span></label>
                                                <textarea name="productDescription" class="form-control" rows="4"
                                                    required></textarea>
                                            </div>

                                            <!-- Product Images -->
                                            <div class="col-md-12 mb-3">
                                                <label class="form-label fw-semibold">Product Images <span
                                                        class="text-danger">*</span></label>
                                                <div class="row">
                                                    <div class="col-md-4 mb-2">
                                                        <label class="form-label">Image 1 (Main)</label>
                                                        <input type="file" name="productimage1" class="form-control"
                                                            required>
                                                    </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>
                                            </div>
                                        </div>

                                        <div class="alert alert-info">
                                            <i class="fas fa-info-circle me-2"></i>
                                            <strong>Note:</strong> Your product will be submitted for admin approval
                                            before appearing on the store.
                                        </div>

                                        <button type="submit" name="submit" class="btn btn-primary">
                                            <i class="fas fa-check me-2"></i>Add 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>
        // Get subcategories based on category selection
        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>