<?php
session_start();
include('includes/config.php');
include('includes/settings.php');

$response = array('status' => 'error', 'message' => 'Invalid Request');

// Check if user is logged in for Wishlist
function checkLogin()
{
    return isset($_SESSION['login']) && strlen($_SESSION['login']) > 0;
}

if (isset($_POST['action'])) {
    $action = $_POST['action'];
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;

    // ===========================
    // ADD TO CART
    // ===========================
    if ($action == 'add_to_cart') {
        $qty = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1;
        if ($qty < 1)
            $qty = 1;

        if (isset($_SESSION['cart'][$id])) {
            // Check current stock before updating quantity
            $sql_s = "SELECT productAvailability, stock_quantity FROM products WHERE id={$id}";
            $res_s = mysqli_query($con, $sql_s);
            $row_s = mysqli_fetch_array($res_s);
            $newTotalQty = $_SESSION['cart'][$id]['quantity'] + $qty;

            if ($row_s['productAvailability'] != 'In Stock' || $row_s['stock_quantity'] < $newTotalQty) {
                $response = array('status' => 'error', 'message' => 'Insufficient stock available. Max available: ' . $row_s['stock_quantity']);
            } else {
                $_SESSION['cart'][$id]['quantity'] += $qty;
                $response = array('status' => 'success', 'message' => 'Product quantity updated in cart', 'cart_count' => count($_SESSION['cart']));
            }
        } else {
            $sql_p = "SELECT * FROM products WHERE id={$id} AND approval_status='approved' AND productAvailability='In Stock' AND stock_quantity >= $qty";
            $query_p = mysqli_query($con, $sql_p);
            if (mysqli_num_rows($query_p) != 0) {
                $row_p = mysqli_fetch_array($query_p);
                $_SESSION['cart'][$row_p['id']] = array("quantity" => $qty, "price" => $row_p['productPrice']);
                $response = array('status' => 'success', 'message' => 'Product added to cart', 'cart_count' => count($_SESSION['cart']));
            } else {
                // Check why it failed
                $sql_check = "SELECT productAvailability, stock_quantity FROM products WHERE id={$id}";
                $res_check = mysqli_query($con, $sql_check);
                $row_check = mysqli_fetch_array($res_check);
                if ($row_check && ($row_check['productAvailability'] != 'In Stock' || $row_check['stock_quantity'] < $qty)) {
                    $response = array('status' => 'error', 'message' => 'This product is out of stock or insufficient quantity.');
                } else {
                    $response = array('status' => 'error', 'message' => 'Product ID is invalid or not approved');
                }
            }
        }
    }

    // ===========================
    // ADD TO WISHLIST
    // ===========================
    elseif ($action == 'add_to_wishlist') {
        if (!checkLogin()) {
            $response = array('status' => 'redirect', 'message' => 'Please login first', 'url' => 'login.php');
        } else {
            // Check if already in wishlist
            $check = mysqli_query($con, "SELECT * FROM wishlist WHERE userId='" . $_SESSION['id'] . "' AND productId='$id'");
            if (mysqli_num_rows($check) > 0) {
                $response = array('status' => 'info', 'message' => 'Product already in wishlist');
            } else {
                mysqli_query($con, "insert into wishlist(userId,productId) values('" . $_SESSION['id'] . "','$id')");
                $response = array('status' => 'success', 'message' => 'Product added to wishlist');
            }
        }
    }

    // ===========================
    // REMOVE FROM WISHLIST (New)
    // ===========================
    elseif ($action == 'remove_wishlist') {
        error_log('Remove wishlist action triggered');
        if (!checkLogin()) {
            error_log('User not logged in');
            $response = array('status' => 'error', 'message' => 'Session expired');
        } else {
            $wid = intval($_POST['wid']); // Expecting wishlist ID, not product ID
            error_log('Wishlist ID: ' . $wid . ', User ID: ' . $_SESSION['id']);

            if ($wid > 0) {
                // Delete only if this wishlist item belongs to the current user (security)
                $query = mysqli_query($con, "DELETE FROM wishlist WHERE id='$wid' AND userId='" . $_SESSION['id'] . "'");
                error_log('Query executed. Affected rows: ' . mysqli_affected_rows($con));

                if ($query && mysqli_affected_rows($con) > 0) {
                    $response = array('status' => 'success', 'message' => 'Product removed from wishlist');
                } else if ($query) {
                    $response = array('status' => 'error', 'message' => 'Item not found or already removed');
                } else {
                    error_log('MySQL Error: ' . mysqli_error($con));
                    $response = array('status' => 'error', 'message' => 'Database error: ' . mysqli_error($con));
                }
            } else {
                error_log('Invalid wishlist ID');
                $response = array('status' => 'error', 'message' => 'Invalid wishlist item ID');
            }
        }
    }

    // ===========================
    // UPDATE CART QUANTITY
    // ===========================
    // ===========================
    // UPDATE CART QUANTITY
    // ===========================
    elseif ($action == 'update_cart_quantity') {
        $qty = intval($_POST['quantity']);
        if ($qty <= 0) {
            unset($_SESSION['cart'][$id]);
            $response = array('status' => 'success', 'message' => 'Product removed from cart', 'removed' => true);
        } else {
            if (isset($_SESSION['cart'][$id])) {
                // Check stock before allowing update
                $sql_s = "SELECT productAvailability, stock_quantity FROM products WHERE id={$id}";
                $res_s = mysqli_query($con, $sql_s);
                $row_s = mysqli_fetch_array($res_s);

                if ($row_s['productAvailability'] != 'In Stock' || $row_s['stock_quantity'] < $qty) {
                    $response = array('status' => 'error', 'message' => 'Requested quantity exceeds available stock (' . $row_s['stock_quantity'] . ')');
                } else {
                    $_SESSION['cart'][$id]['quantity'] = $qty;
                    // Reset errors if successful
                    $response = array('status' => 'success', 'message' => 'Cart updated'); // Placeholder, will be overwritten below
                }

                // Recalculate Totals
                $total_price = 0;
                $total_items = 0;
                $item_subtotal = 0;

                foreach ($_SESSION['cart'] as $key => $val) {
                    $quantity = $val['quantity'];
                    $sql_q = "SELECT * FROM products WHERE id=$key";
                    $res_q = mysqli_query($con, $sql_q);
                    if ($row_q = mysqli_fetch_array($res_q)) {
                        $sub = ($quantity * $row_q['productPrice']);
                        $total_price += $sub;
                        $total_items += $quantity;

                        if ($key == $id) {
                            $item_subtotal = $sub;
                        }
                    }
                }
                $grand_total = $total_price;

                // Only send success response if we haven't already set an error
                if (!isset($response['status']) || $response['status'] !== 'error') {
                    $response = array(
                        'status' => 'success',
                        'message' => 'Cart updated',
                        'removed' => false,
                        'item_subtotal' => number_format($item_subtotal, 2),
                        'total_price' => number_format($total_price, 2),
                        'grand_total' => number_format($grand_total, 2),
                        'total_items' => $total_items,
                        'cart_count' => count($_SESSION['cart'])
                    );
                }
            } else {
                $response = array('status' => 'error', 'message' => 'Product not in cart');
            }
        }
    }

    // ===========================
    // REMOVE SELECTED ITEMS
    // ===========================
    elseif ($action == 'remove_cart_item') {
        if (isset($_POST['ids']) && is_array($_POST['ids'])) {
            $ids = $_POST['ids'];
            $removed_count = 0;
            foreach ($ids as $key) {
                if (isset($_SESSION['cart'][$key])) {
                    unset($_SESSION['cart'][$key]);
                    $removed_count++;
                }
            }
            if ($removed_count > 0) {
                // Recalculate Totals to return accurate data even if we reload
                $total_price = 0;
                $total_items = 0;
                if (!empty($_SESSION['cart'])) {
                    foreach ($_SESSION['cart'] as $key => $val) {
                        $quantity = $val['quantity'];
                        $sql_q = "SELECT * FROM products WHERE id=$key";
                        $res_q = mysqli_query($con, $sql_q);
                        if ($row_q = mysqli_fetch_array($res_q)) {
                            $sub = ($quantity * $row_q['productPrice']);
                            $total_price += $sub;
                            $total_items += $quantity;
                        }
                    }
                }
                $grand_total = $total_price;

                $response = array(
                    'status' => 'success',
                    'message' => 'Selected products removed from cart',
                    'total_price' => number_format($total_price, 2),
                    'grand_total' => number_format($grand_total, 2),
                    'total_items' => $total_items,
                    'cart_count' => count($_SESSION['cart'])
                );
            } else {
                $response = array('status' => 'error', 'message' => 'No valid items found to remove');
            }
        } else {
            $response = array('status' => 'error', 'message' => 'No items selected');
        }
    }
    // ===========================
    // UPDATE ADDRESS (AJAX)
    // ===========================
    // ===========================
    // UPDATE ADDRESS (AJAX)
    // ===========================
    elseif ($action == 'update_address') {
        if (!checkLogin()) {
            $response = array('status' => 'error', 'message' => 'Session expired');
        } else {
            $type = $_POST['type']; // 'billing' or 'shipping'
            $uid = $_SESSION['id'];

            if ($type == 'billing') {
                $address = mysqli_real_escape_string($con, $_POST['billingaddress']);
                $city = mysqli_real_escape_string($con, $_POST['billingcity']);
                $state = $_POST['billingstate'];
                $pincode = mysqli_real_escape_string($con, $_POST['billingpincode']);

                // If state is numeric (ID from dropdown), convert to Name for DB storage
                if (is_numeric($state)) {
                    $st_res = mysqli_query($con, "SELECT state_name FROM states WHERE id=" . intval($state));
                    if ($st_row = mysqli_fetch_array($st_res))
                        $state = $st_row['state_name'];
                }
                $state = mysqli_real_escape_string($con, $state);

                // Check if user has details record
                $check = mysqli_query($con, "SELECT user_id FROM user_details WHERE user_id='$uid'");
                if (mysqli_num_rows($check) == 0) {
                    $query = mysqli_query($con, "INSERT INTO user_details (user_id, billingAddress, billingCity, billingState, billingPincode) VALUES ('$uid', '$address', '$city', '$state', '$pincode')");
                } else {
                    $query = mysqli_query($con, "UPDATE user_details SET billingAddress='$address', billingCity='$city', billingState='$state', billingPincode='$pincode' WHERE user_id='$uid'");
                }

                if ($query) {
                    $response = array('status' => 'success', 'message' => 'Billing Address updated successfully');
                } else {
                    $response = array('status' => 'error', 'message' => 'Failed to update billing address: ' . mysqli_error($con));
                }
            } elseif ($type == 'shipping') {
                $address = mysqli_real_escape_string($con, $_POST['shippingaddress']);
                $city = mysqli_real_escape_string($con, $_POST['shippingcity']);
                $state = $_POST['shippingstate'];
                $pincode = mysqli_real_escape_string($con, $_POST['shippingpincode']);

                // If state is numeric (ID from dropdown), convert to Name for DB storage
                if (is_numeric($state)) {
                    $st_res = mysqli_query($con, "SELECT state_name FROM states WHERE id=" . intval($state));
                    if ($st_row = mysqli_fetch_array($st_res))
                        $state = $st_row['state_name'];
                }
                $state = mysqli_real_escape_string($con, $state);

                // Check if user has details record
                $check = mysqli_query($con, "SELECT user_id FROM user_details WHERE user_id='$uid'");
                if (mysqli_num_rows($check) == 0) {
                    $query = mysqli_query($con, "INSERT INTO user_details (user_id, shippingAddress, shippingCity, shippingState, shippingPincode) VALUES ('$uid', '$address', '$city', '$state', '$pincode')");
                } else {
                    $query = mysqli_query($con, "UPDATE user_details SET shippingAddress='$address', shippingCity='$city', shippingState='$state', shippingPincode='$pincode' WHERE user_id='$uid'");
                }

                if ($query) {
                    $response = array('status' => 'success', 'message' => 'Shipping Address updated successfully');
                } else {
                    $response = array('status' => 'error', 'message' => 'Failed to update shipping address: ' . mysqli_error($con));
                }
            }
        }
    }

    // ===========================
    // PERSIST SAME AS BILLING FLAG
    // ===========================
    elseif ($action == 'toggle_same_as_billing') {
        if (!checkLogin()) {
            $response = array('status' => 'error', 'message' => 'Session expired');
        } else {
            $uid = $_SESSION['id'];
            $val = intval($_POST['value']); // 1 or 0
            $query = mysqli_query($con, "UPDATE user_details SET ship_same_as_billing = $val WHERE user_id = '$uid'");
            if ($query) {
                $response = array('status' => 'success', 'message' => 'Preference saved');
            } else {
                $response = array('status' => 'error', 'message' => 'Failed to save preference');
            }
        }
    }

    // ===========================
    // FETCH CITIES BY STATE
    // ===========================
    elseif ($action == 'get_cities_by_state') {
        $state_id = intval($_POST['state_id']);
        $query = mysqli_query($con, "SELECT city_name FROM cities WHERE state_id = $state_id ORDER BY city_name ASC");
        $cities = array();
        while ($row = mysqli_fetch_array($query)) {
            $cities[] = $row['city_name'];
        }
        $response = array('status' => 'success', 'cities' => $cities);
    }
}

echo json_encode($response);
?>