<?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");
    // header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    // header('Cache-Control: post-check=0, pre-check=0',false);
    // header('Pragma: no-cache');
    $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');
// Initialize the Magento application
//$bootstrap->run();

// 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;

// Create a new cart
// $quote = $quoteFactory->create();
// $quote->setStoreId(1); // Replace with the appropriate store ID

// if ($customerId) {
//     $quote->setCustomerId($customerId);
// }
$result=[];
// $quote->save();
//print_r($data); die();
$quoteId=(isset($data->quote_id))? $data->quote_id : 0; //"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->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= "Some Products are Out of Stock.";// . $e->getMessage();
             $itemSku[$sku]='Out Of Stock';
              $messageSuccess =false;
              continue;
            }
    
            // 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;
                  continue;
                //return false; // Quantity exceeds the limit
            }
             $minQuantity = $stockItem->getMinSaleQty(); // Set your maximum quantity limit
            if ($qty < $minQuantity) {
                 $itemSku[$sku]='Mini Qty-'.$minQuantity;
                  $messageSuccess =false;
                  continue;
                //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;
                        // echo json_encode($qty);
                    }
                    else if ($existingItem->getProduct()->getSku() === $sku && $existingItem->getQty()!=$qty && !isset($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;
                        }
                         
                    }
                     
                    
                }
                //  echo json_encode($sku). "\n";
                //  echo $qty < $minQuantity ? 'true' : 'false'. "\n";
                //if items is not  exist
                if(!isset($itemToUpdate[$sku])){
                    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;
                }
            }
           
        }
        }
        
        // 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!';
}
$result=[ "message"=> $message,"success"=> $messageSuccess,"outofstock"=>$itemSku];
echo json_encode($result);