<?php
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");
    header("Access-Control-Allow-Methods: POST");
    header("Access-Control-Max-Age: 0");
    header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
    $data = json_decode(file_get_contents("php://input"));
// Check if the Authorization header is present in the HTTP request
$message ='';
if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
    $authorizationHeader = $_SERVER['HTTP_AUTHORIZATION'];

    // You can now inspect the $authorizationHeader value
    // For example, you might extract and verify an access token
    // or perform other authentication or authorization checks here

    // Example: Verify an access token (replace with your own logic)
    $accessToken = extractAccessToken($authorizationHeader);

    if ($accessToken) {
        // Authorization header is present and valid
       // echo "Authorization header is present and valid. Access Token: $accessToken";
    } else {
        // Authorization header is present but invalid
        $message= "Authorization header is present but invalid";
    }
} else {
    // Authorization header is not present
    $message= "Authorization header is not present";
}

// Replace this function with your own logic to extract and verify an access token
function extractAccessToken($authorizationHeader) {
    // Your logic to extract and validate the access token goes here
    // For example, you might use regular expressions to extract the token
    // and then validate it against your authentication system

    // Replace this example with your actual validation logic
    $accessToken = null;

    // Example: Check if the Authorization header contains a Bearer token
    if (preg_match('/Bearer\s+(.*)$/i', $authorizationHeader, $matches)) {
        $accessToken = $matches[1];
        // You can add your validation logic here
    }

    return $accessToken;
}

use Magento\Framework\App\Bootstrap;
use Magento\Quote\Api\CartManagementInterface;
use Magento\Quote\Model\QuoteFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\DataObject;

require '../../app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get(\Magento\Framework\App\State::class);
$state->setAreaCode('frontend');


// Inject necessary dependencies
$cartManagement = $objectManager->get(CartManagementInterface::class);
$quoteFactory = $objectManager->get(QuoteFactory::class);
$productRepository = $objectManager->get(ProductRepositoryInterface::class);

// Replace with actual customer ID if you want to assign the cart to a specific customer
$customerId = null;

$result=[];
$quoteId=(isset($data->quote_id))? $data->quote_id : $_GET['quote_id']; //"61478"; 


if ($quoteId) {
 
    // // Define an array of items to add in bulk
    try {
        // Load the quote using the QuoteRepository
       // Load the quote
        $quote = $objectManager->get(\Magento\Quote\Model\QuoteRepository::class)->get($quoteId);
        //$customerId = $quote->getCustomer()->getId();
                // Get the existing items in the quote
        $existingItems = $quote->getAllItems();
        $itemToUpdate = [];
        $itemSku = [];
        $itemsToRemove = [];
        $messageSuccess =true;
        $message=''; // 'Items added to cart successfully!';
        // Iterate through the items to add
        if($data && $data->cartItem):
            foreach ($data->cartItem as $itemData) {
                $sku = $itemData->sku;
                 // Load necessary classes for stock item checks
               
                $qty =(int)$itemData->qty;
                $stockItem = $objectManager->create(\Magento\CatalogInventory\Api\StockRegistryInterface::class)->getStockItemBySku($sku);
                 if (!$stockItem->getIsInStock()) {
                 //return false; // Product is out of stock
                 //$message= "Can't add: " . $e->getMessage();
                 $itemSku[$sku]='Out Of Stock';
                  $messageSuccess =false;
                }
        
                // Example: Check if item quantity exceeds a limit
                $maxQuantity = $stockItem->getMaxSaleQty(); // Set your maximum quantity limit
                if ($qty > $maxQuantity) {
                     $itemSku[$sku]='Qty Limit';
                      $messageSuccess =false;
                    //return false; // Quantity exceeds the limit
                }
                 $minQuantity = $stockItem->getMinSaleQty(); // Set your maximum quantity limit
                if ($qty < $minQuantity) {
                     $itemSku[$sku]='Mini Qty-'.$minQuantity;
                      $messageSuccess =false;
                    //return false; // Quantity exceeds the limit
                }
                 // Find the item in the quote by item ID
                //$itemToUpdate = $quote->getItemBySku($sku);
                 // Find the item in the quote by SKU
                //  if(!$customerId) {
                //     // Quote is associated with a guest
                //     $itemsToRemove[]= $sku;
                // }
                if (!empty($existingItems)) {
                    foreach ($existingItems as $existingItem) {
                        if($existingItem->getProduct()->getSku() === $sku && $existingItem->getQty()==$qty)
                        {
                            $itemToUpdate[$sku]=true;
                        }elseif ($existingItem->getProduct()->getSku() === $sku && $existingItem->getQty()!=$qty && !$itemSku[$sku] && $qty < $minQuantity && $qty < $minQuantity){
                            $itemToUpdate[$sku]=true;
                            try {
                              // Load the product by its ID
                                    $product = $productRepository->get($sku);
                                //Add the product to the quote
                                $quote->addProduct($product, $qty);
                                $quote->collectTotals();
                                // Save the quote to reflect the changes
                                $quote->save();
                            } catch (\Exception $e) {
                                $message= "Can't add: " . $e->getMessage();
                                $itemSku[$sku]='Out Of Stock';
                                $messageSuccess =false;
                            }
                             
                        }
                         
                        
                    }
                    //if items is not  exist
                    if(!isset($itemToUpdate[$sku]) && $qty < $minQuantity && $qty < $minQuantity){
                        try {
                          // Load the product by its ID
                                $product = $productRepository->get($sku);
                            //Add the product to the quote
                            $quote->addProduct($product, $qty);
                            $quote->collectTotals();
                            // Save the quote to reflect the changes
                            $quote->save();
                             
                        } catch (\Exception $e) {
                            $message= "Can't add: " . $e->getMessage();
                            $itemSku[$sku]='Out Of Stock';
                            $messageSuccess =false;
                        }
                     }
                    
                }else{
                    try {
                      // Load the product by its ID
                    $product = $productRepository->get($sku);
                    //Add the product to the quote
                    $quote->addProduct($product, $qty);
                    $quote->collectTotals();
                    // Save the quote to reflect the changes
                    $quote->save();
                    } catch (\Exception $e) {
                        $message= "Can't add: " . $e->getMessage();
                        $itemSku[$sku]='Out Of Stock';
                        $messageSuccess =false;
                    }
                }
               
            }
        else:
            // Initialize stock registry to check stock status
            $stockRegistry = $objectManager->get(\Magento\CatalogInventory\Api\StockRegistryInterface::class);

            // Iterate through the items in the quote
            foreach ($existingItems as $existingItem) {
                 $sku = $existingItem->getProduct()->getSku();
               
                 $cartqty = $existingItem->getQty();
                 
                // Retrieve stock item by SKU
                $stockItem = $stockRegistry->getStockItemBySku($sku);
                // Check if the item is out of stock
                if (!$stockItem->getIsInStock()) {
                     $itemSku[$sku] = 'Out of Stock';
                     $messageSuccess =false;
                } else {
                    // Optionally, you can check quantity limits
                    $maxQuantity = $stockItem->getMaxSaleQty();
                    $minQuantity = $stockItem->getMinSaleQty();
                    if ($cartqty > $maxQuantity) {
                        $itemSku[$sku] = 'Qty Limit Exceeded';
                        $messageSuccess =false;
                    } elseif ($cartqty < $minQuantity) {
                        $itemSku[$sku] = 'Qty Below Minimum';
                        $messageSuccess =false;
                    }
                }
            }
        endif;
        // if (!empty($existingItems)  && !$customerId && count($itemsToRemove)>0) {
        //     // Compare the cart items with the array and remove items not found in the array
        //     foreach ($existingItems as $existingItem) {
        //         if (!in_array($existingItem->getProduct()->getSku(), $itemsToRemove)) {
        //             $quote->deleteItem($existingItem)->save();
        //         }
        //     }
        // }
        $quote->collectTotals();
        // Save the quote to reflect the changes
        $quote->save();
       
        //$messageSuccess =true;
       
    } catch (\Exception $e) {
        $message= "Can't add:" . $e->getMessage();
        $messageSuccess =false;
    }

}else{
    http_response_code(500);
    //$message= "Can't add: ";
   // $message= 'exceed limit!';
}
//print_r($itemSku);
$result=[ "message"=> $message,"success"=> $messageSuccess,"outofstock"=>$itemSku];
echo json_encode($result);