<?php
include '_dbconnect.php';
session_start();

// Ensure user is logged in
if (!isset($_SESSION['userId'])) {
    die("<script>alert('Unauthorized Access! Please log in.'); window.location.href='login.php';</script>");
}

$userId = $_SESSION['userId'];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // Add to Cart
    if ($_SERVER["REQUEST_METHOD"] == "POST"  && isset($_POST['addToCart'])) 
	{
        $itemId = $_POST["itemId"];

        // Check if item exists
        $existSql = "SELECT * FROM `viewcart` WHERE `pId` = ? AND `userId` = ?";
        $stmt = $conn->prepare($existSql);
        $stmt->bind_param("ii", $itemId, $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            echo "<script>alert('Item Already Added.'); window.history.back();</script>";
        } else {
            $sql = "INSERT INTO `viewcart` (`pId`, `itemQuantity`, `userId`, `addedDate`) VALUES (?, 1, ?, current_timestamp())";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ii", $itemId, $userId);
            if ($stmt->execute()) {
                echo "<script>window.history.back();</script>";
            } else {
                echo "<script>alert('Error adding item: " . $conn->error . "');</script>";
            }
        }
        $stmt->close();
		header("Location: " . $_SERVER['HTTP_REFERER']);
		exit();
    }

    // Remove Single Item
    if (isset($_POST['removeItem'])) 
	{
        $itemId = $_POST["itemId"];
        $sql = "DELETE FROM `viewcart` WHERE `pId` = ? AND `userId` = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ii", $itemId, $userId);
        if ($stmt->execute()) 
		{
            echo "<script>alert('Item Removed'); window.history.back();</script>";
        }
        $stmt->close();
    }

    // Remove All Items
    if (isset($_POST['removeAllItem'])) {
        $sql = "DELETE FROM `viewcart` WHERE `userId` = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $userId);
        if ($stmt->execute()) {
            echo "<script>alert('All Items Removed'); window.history.back();</script>";
        }
        $stmt->close();
    }

    // Checkout Process
    if (isset($_POST['checkout'])) {
        $amount = $_POST["amount"];
        
		//$address1 = $_POST["address"];
        //$address2 = $_POST["address1"]; 
		
		//$address1 = $_POST["address1"]; // mgm
        //$address2 = $_POST["address2"];
		
		$address1 = preg_replace("/[^a-zA-Z0-9\s]/", "", $_POST["address"]);
		$address2 = preg_replace("/[^a-zA-Z0-9\s]/", "", $_POST["address1"]);
		
        $phone = $_POST["phone"];
        $zipcode = $_POST["zipcode"];
        $password = $_POST["password"];
        $fullAddress = $address1 . " and " . $address2;

        // Verify password
        $passSql = "SELECT `username`, `password` FROM `users` WHERE `id` = ?";
        $stmt = $conn->prepare($passSql);
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $passResult = $stmt->get_result();

        if ($passRow = $passResult->fetch_assoc()) {
            if (password_verify($password, $passRow['password'])) {
                // Insert into orders
                $orderSql = "INSERT INTO `orders` (`userId`, `address`, `zipCode`, `phoneNo`, `amount`, `paymentMode`, `orderStatus`, `orderDate`) 
                             VALUES (?, ?, ?, ?, ?, '0', '0', current_timestamp())";
                $stmt = $conn->prepare($orderSql);
                $stmt->bind_param("issis", $userId, $fullAddress, $zipcode, $phone, $amount);
                if ($stmt->execute()) {
                    $orderId = $conn->insert_id;

                    // Move items from cart to orderitems
                    $cartSql = "SELECT * FROM `viewcart` WHERE `userId` = ?";
                    $stmt = $conn->prepare($cartSql);
                    $stmt->bind_param("i", $userId);
                    $stmt->execute();
                    $cartResult = $stmt->get_result();

                    while ($row = $cartResult->fetch_assoc()) {
                        $pId = $row['pId'];
                        $itemQuantity = $row['itemQuantity'];
                        $itemSql = "INSERT INTO `orderitems` (`orderId`, `pId`, `itemQuantity`) VALUES (?, ?, ?)";
                        $stmt = $conn->prepare($itemSql);
                        $stmt->bind_param("iii", $orderId, $pId, $itemQuantity);
                        $stmt->execute();
                    }

                    // Clear cart after checkout
                    $deleteSql = "DELETE FROM `viewcart` WHERE `userId` = ?";
                    $stmt = $conn->prepare($deleteSql);
                    $stmt->bind_param("i", $userId);
                    $stmt->execute();

                    echo "<script>alert('Thanks for ordering with us. Your order ID is $orderId.');
                          window.location.href='http://localhost/enandini/index.php';</script>";
                    exit();
                }
            } else {
                echo "<script>alert('Incorrect Password! Please enter the correct password.'); window.history.back();</script>";
                exit();
            }
        }
        $stmt->close();
    }

    // Update Cart Quantity via AJAX
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        $pId = $_POST['pId'];
        $qty = $_POST['quantity'];

        $updatesql = "UPDATE `viewcart` SET `itemQuantity` = ? WHERE `pId` = ? AND `userId` = ?";
        $stmt = $conn->prepare($updatesql);
        $stmt->bind_param("iii", $qty, $pId, $userId);
        $stmt->execute();
        $stmt->close();
    }
}
?>
