<?php
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Enable error reporting for development
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors on page
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_errors.log');

require_once('../includes/admin-security.php');
include_once('includes/config.php');

// Access Check
if (!has_permission('manage_products')) {
    echo "<script>alert('Access Denied. Redirecting to Dashboard...'); window.location.href='dashboard.php';</script>";
    exit();
}

//For Adding Products (Actually Update in this file context)
if (isset($_POST['submit'])) {

    $pid = intval($_GET['id']);
    $category = db_prepare($con, $_POST['category']);
    $subcat = db_prepare($con, $_POST['subcategory']);
    $productname = db_prepare($con, $_POST['productName']);
    $productcompany = db_prepare($con, $_POST['productCompany']);
    $productprice = db_prepare($con, $_POST['productprice']);
    $productpricebd = db_prepare($con, $_POST['productpricebd']);
    $productdescription = db_prepare($con, $_POST['productDescription']);
    $productscharge = db_prepare($con, $_POST['productShippingcharge']);
    $productavailability = db_prepare($con, $_POST['productAvailability']);
    $productlocation = db_prepare($con, $_POST['productLocation']);
    $stockQuantity = intval($_POST['stock_quantity']);
    $sku = db_prepare($con, $_POST['sku']);
    $updatedby = $_SESSION['aid'];

    // Shipping Overrides (Only for Admin/Staff)
    $can_manage_shipping = has_permission('manage_shipping_overrides');
    if ($can_manage_shipping) {
        $shipping_pickup_fee = ($_POST['shipping_pickup_fee'] !== '') ? "'" . mysqli_real_escape_string(
            $con,
            $_POST['shipping_pickup_fee']
        ) . "'" : 'NULL';
        $shipping_door_fee = ($_POST['shipping_door_fee'] !== '') ? "'" . mysqli_real_escape_string(
            $con,
            $_POST['shipping_door_fee']
        ) . "'" : 'NULL';
        $shipping_days_min = ($_POST['shipping_days_min'] !== '') ? "'" . mysqli_real_escape_string(
            $con,
            $_POST['shipping_days_min']
        ) . "'" : 'NULL';
        $shipping_days_max = ($_POST['shipping_days_max'] !== '') ? "'" . mysqli_real_escape_string(
            $con,
            $_POST['shipping_days_max']
        ) . "'" : 'NULL';

        $sql = mysqli_query($con, "update products set
category='$category',subCategory='$subcat',productName='$productname',productCompany='$productcompany',productPrice='$productprice',productDescription='$productdescription',shippingCharge='$productscharge',productAvailability='$productavailability',productPriceBeforeDiscount='$productpricebd',product_location='$productlocation',lastUpdatedBy='$updatedby',stock_quantity='$stockQuantity',sku='$sku',
shipping_pickup_fee=$shipping_pickup_fee, shipping_door_fee=$shipping_door_fee, shipping_days_min=$shipping_days_min,
shipping_days_max=$shipping_days_max where id='$pid'");
    } else {
        $sql = mysqli_query($con, "update products set
category='$category',subCategory='$subcat',productName='$productname',productCompany='$productcompany',productPrice='$productprice',productDescription='$productdescription',shippingCharge='$productscharge',productAvailability='$productavailability',productPriceBeforeDiscount='$productpricebd',product_location='$productlocation',lastUpdatedBy='$updatedby',stock_quantity='$stockQuantity',sku='$sku'
where id='$pid'");
    }
    if ($sql) {
        log_activity("Updated Product", "Product ID: $pid, Name: $productname");
    }
    echo "
<script>alert('Product details updated successfully');</script>";
    echo "
<script>window.location.href = 'manage-products.php'</script>";
}
?>

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

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <meta name="description" content="" />
    <meta name="author" content="" />
    <title>Awesome Mall | Edit Product</title>
    <link href="css/styles.css" rel="stylesheet" />
    <link href="css/admin-professional.css" rel="stylesheet" />
    <script src="js/all.min.js" crossorigin="anonymous"></script>
    <script src="js/jquery-3.5.1.min.js"></script>
    <script>
        function getSubcat(val) {
            $.ajax({
                type: "POST",
                url: "get_subcat.php",
                data: 'cat_id=' + val,
                success: function (data) {
                    $("#subcategory").html(data);
                }
            });
        }

        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>

</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">
                    <!-- Page Header -->
                    <div class="page-header mt-4">
                        <div>
                            <h1><i class="fas fa-edit me-2"></i> Edit Product</h1>
                            <p>Modify existing product details</p>
                        </div>
                    </div>

                    <div class="table-card">
                        <div class="card-header">
                            <h5 class="mb-0"><i class="fas fa-edit me-2"></i>Product Information</h5>
                        </div>
                        <div class="card-body">


                            <?php
                            $pid = intval($_GET['id']);
                            $can_manage_shipping = has_permission('manage_shipping_overrides');
                            $query = mysqli_query($con, "select products.*,category.categoryName,subcategory.subcategory as subcatname,products.postingDate,products.updationDate,subcategory.id as subid,users.username,category.id as catid,products.productCompany,products.productPrice,products.productPriceBeforeDiscount,products.productAvailability,products.productDescription,products.shippingCharge,products.product_location,products.stock_quantity,products.sku from products join subcategory on products.subCategory=subcategory.id join category on products.category=category.id left join users on users.id=products.addedBy where products.id='$pid' order by id desc");
                            while ($row = mysqli_fetch_array($query)) {
                                ?>
                                    <form method="post" enctype="multipart/form-data">
                                        <!-- Row 1: Category & Subcategory -->
                                        <div class="row">
                                            <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"
                                                    onChange="getSubcat(this.value);" required>
                                                    <option value="<?php echo htmlentities($row['catid']); ?>">
                                                        <?php echo htmlentities($row['categoryName']); ?>
                                                    </option>
                                                    <?php $ret = mysqli_query($con, "select * from category");
                                                    while ($result = mysqli_fetch_array($ret)) {
                                                        if ($result['id'] != $row['catid']) { ?>
                                                                    <option value="<?php echo $result['id']; ?>">
                                                                        <?php echo $result['categoryName']; ?>
                                                                    </option>
                                                            <?php }
                                                    } ?>
                                                </select>
                                            </div>
                                            <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="<?php echo htmlentities($row['subid']); ?>">
                                                        <?php echo htmlentities($row['subcatname']); ?>
                                                    </option>
                                                </select>
                                            </div>
                                        </div>

                                        <!-- Row 2: Product Name & SKU -->
                                        <div class="row">
                                            <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"
                                                    value="<?php echo htmlentities($row['productName']); ?>"
                                                    class="form-control" required>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label fw-semibold">SKU (Stock Keeping Unit)</label>
                                                <input type="text" name="sku" value="<?php echo htmlentities($row['sku']); ?>"
                                                    class="form-control">
                                            </div>
                                        </div>

                                        <!-- Row 3: Brand & Stock -->
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label fw-semibold">Brand/Company</label>
                                                <input type="text" name="productCompany"
                                                    value="<?php echo htmlentities($row['productCompany']); ?>"
                                                    class="form-control">
                                            </div>
                                            <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"
                                                    value="<?php echo htmlentities($row['stock_quantity']); ?>"
                                                    class="form-control" required>
                                            </div>
                                        </div>

                                        <!-- Row 4: Pricing & Location -->
                                        <div class="row">
                                            <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"
                                                    value="<?php echo htmlentities($row['productPriceBeforeDiscount']); ?>"
                                                    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>
                                                <?php
                                                $disc = 0;
                                                if ($row['productPriceBeforeDiscount'] > 0 && $row['productPriceBeforeDiscount'] > $row['productPrice']) {
                                                    $disc = round((($row['productPriceBeforeDiscount'] - $row['productPrice']) / $row['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 (₵) <span
                                                        class="text-danger">*</span></label>
                                                <input type="number" name="productprice" id="productprice"
                                                    value="<?php echo htmlentities($row['productPrice']); ?>"
                                                    class="form-control bg-light" step="0.01" readonly required>
                                            </div>
                                            <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="<?php echo htmlentities($row['product_location']); ?>">
                                                        <?php echo htmlentities($row['product_location']); ?>
                                                    </option>
                                                    <?php
                                                    $loc_query = mysqli_query($con, "SELECT city_name FROM cities ORDER BY city_name ASC");
                                                    while ($loc_row = mysqli_fetch_array($loc_query)) {
                                                        if ($loc_row['city_name'] != $row['product_location']) {
                                                            echo "<option value='" . htmlentities($loc_row['city_name']) . "'>" . htmlentities($loc_row['city_name']) . "</option>";
                                                        }
                                                    }
                                                    ?>
                                                </select>
                                            </div>
                                        </div>

                                        <!-- Row 5: Availability & Shipping -->
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label fw-semibold">Availability <span
                                                        class="text-danger">*</span></label>
                                                <select name="productAvailability" id="productAvailability" class="form-select"
                                                    required>
                                                    <option value="In Stock" <?php echo ($row['productAvailability'] == 'In Stock' ? 'selected' : ''); ?>>In Stock</option>
                                                    <option value="Out of Stock" <?php echo ($row['productAvailability'] == 'Out of Stock' ? 'selected' : ''); ?>>Out of Stock</option>
                                                </select>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label fw-semibold">Shipping Charge <span
                                                        class="text-danger">*</span></label>
                                                <input type="text" name="productShippingcharge"
                                                    value="<?php echo htmlentities($row['shippingCharge']); ?>"
                                                    class="form-control" required>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-12 mb-3">
                                                <label class="form-label fw-semibold">Product Description</label>
                                                <textarea name="productDescription" placeholder="Enter Product Description"
                                                    rows="4"
                                                    class="form-control"><?php echo $row['productDescription']; ?></textarea>
                                            </div>
                                        </div>

                                        <?php if ($can_manage_shipping) { ?>
                                                <div class="card mb-4 border-0 shadow-sm">
                                                    <div class="card-header fw-bold bg-light">
                                                        <i class="fas fa-truck me-2"></i>Shipping Configuration Overrides
                                                    </div>
                                                    <div class="card-body">
                                                        <div class="row">
                                                            <div class="col-md-3 mb-3">
                                                                <label class="form-label small fw-bold">Pickup Fee</label>
                                                                <input type="number" name="shipping_pickup_fee" class="form-control"
                                                                    value="<?php echo htmlentities($row['shipping_pickup_fee']); ?>"
                                                                    step="0.01" min="0">
                                                            </div>
                                                            <div class="col-md-3 mb-3">
                                                                <label class="form-label small fw-bold">Door Delivery Fee</label>
                                                                <input type="number" name="shipping_door_fee" class="form-control"
                                                                    value="<?php echo htmlentities($row['shipping_door_fee']); ?>"
                                                                    step="0.01" min="0">
                                                            </div>
                                                            <div class="col-md-3 mb-3">
                                                                <label class="form-label small fw-bold">Min Days</label>
                                                                <input type="number" name="shipping_days_min" class="form-control"
                                                                    value="<?php echo htmlentities($row['shipping_days_min']); ?>"
                                                                    min="0">
                                                            </div>
                                                            <div class="col-md-3 mb-3">
                                                                <label class="form-label small fw-bold">Max Days</label>
                                                                <input type="number" name="shipping_days_max" class="form-control"
                                                                    value="<?php echo htmlentities($row['shipping_days_max']); ?>"
                                                                    min="0">
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                        <?php } ?>

                                        <div class="row mt-4">
                                            <div class="col-md-4 mb-3">
                                                <div class="card h-100 text-center p-3 border-0 shadow-sm">
                                                    <h6>Featured Image</h6>
                                                    <img src="productimages/<?php echo $pid; ?>/<?php echo htmlentities($row['productImage1']); ?>"
                                                        class="img-fluid rounded mb-2"
                                                        style="max-height: 150px; object-fit: contain;">
                                                    <a href="change-image1.php?id=<?php echo $row['id']; ?>"
                                                        class="btn btn-sm btn-outline-secondary">Change</a>
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <div class="card h-100 text-center p-3 border-0 shadow-sm">
                                                    <h6>Image 2</h6>
                                                    <img src="productimages/<?php echo $pid; ?>/<?php echo htmlentities($row['productImage2']); ?>"
                                                        class="img-fluid rounded mb-2"
                                                        style="max-height: 150px; object-fit: contain;">
                                                    <a href="change-image2.php?id=<?php echo $row['id']; ?>"
                                                        class="btn btn-sm btn-outline-secondary">Change</a>
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <div class="card h-100 text-center p-3 border-0 shadow-sm">
                                                    <h6>Image 3</h6>
                                                    <img src="productimages/<?php echo $pid; ?>/<?php echo htmlentities($row['productImage3']); ?>"
                                                        class="img-fluid rounded mb-2"
                                                        style="max-height: 150px; object-fit: contain;">
                                                    <a href="change-image3.php?id=<?php echo $row['id']; ?>"
                                                        class="btn btn-sm btn-outline-secondary">Change</a>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row mt-4">
                                            <div class="col-12 text-end">
                                                <button type="submit" name="submit" class="btn btn-primary btn-lg px-5">Update
                                                    Product</button>
                                            </div>
                                        </div>

                                    </form>

                            <?php } ?>
                        </div>
                    </div>
                </div>
            </main>
            <?php include_once('includes/footer.php'); ?>
        </div>
    </div>
    <script src="js/bootstrap.bundle.min.js"></script>
    <script src="js/scripts.js"></script>
</body>

</html>
<?php ?>