<?php
 ini_set('display_errors', '1');
  ini_set('display_startup_errors', '1');
    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"));
   
    $quoteId=(isset($data->quote_id) && $data->quote_id>0)? $data->quote_id : 0; //"61478"; 
  
// Check if the Authorization header is present in the HTTP request
$message ='';
$messageSuccess =true;
$accessToken='';
if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
    $authorizationHeader = $_SERVER['HTTP_AUTHORIZATION'];
    $accessToken = extractAccessToken($authorizationHeader);
    if ($accessToken) {
        // Authorization header is present and valid
       // echo "Authorization header is present and valid. Access Token: $accessToken";
       $messageSuccess=true;
    } else {
        // Authorization header is present but invalid
        $message= "Authorization header is present but invalid";
        $messageSuccess=false;
    }
} else {
    // Authorization header is not present
    $message= "Authorization header is not present";
    $messageSuccess=false;
}

// Replace this function with your own logic to extract and verify an access token
function extractAccessToken($authorizationHeader) {
    $accessToken = null;
    // Example: Check if the Authorization header contains a Bearer token
    if (preg_match('/Bearer\s+(.*)$/i', $authorizationHeader, $matches)) {
        $accessToken = $matches[1];
    }
    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;
use Magento\Framework\App\ResourceConnection;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Integration\Model\Oauth\Token as OAuthToken;
use Magento\Quote\Model\ResourceModel\Quote\CollectionFactory as QuoteCollectionFactory;
require '../../app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get(\Magento\Framework\App\State::class);
$state->setAreaCode('frontend');
$resource = $objectManager->get(ResourceConnection::class);
$connection = $resource->getConnection();
// Inject necessary dependencies
$cartManagement = $objectManager->get(CartManagementInterface::class);
$quoteFactory = $objectManager->get(QuoteFactory::class);
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
$cartRepository = $objectManager->get(CartRepositoryInterface::class);
$quoteCollectionFactory = $objectManager->get(QuoteCollectionFactory::class);
/** @var OAuthToken $oauthToken */
$oauthToken = $objectManager->get(OAuthToken::class);
$result=[];

$itemSku = [];
$totalAmount=0;

$result=[ "message"=> $message,"success"=> $messageSuccess,"outofstock"=>$itemSku,"quote_id"=>$quoteId];
$connection->insert('ahqa_app_cart_report', [
        'cart_id' => $quoteId,
        'quote_id' => $quoteId,
        'header_token'=>$accessToken,
        'customer_id' => (isset($data->customer_id))? $data->customer_id: 0,
        'request_content'=>json_encode($data),
        'created_at' => date('Y-m-d H:i:s')
    ]);
if(isset($data->customer_id)){
      
    try {
            // Load token by token string
        $token = $oauthToken->loadByToken($data->customer_id);

        if ($token->getCustomerId()) {
            $customerId=$token->getCustomerId();
            $activeQuoteCollection = $quoteCollectionFactory->create()
                ->addFieldToFilter('customer_id', $customerId)
                ->addFieldToFilter('is_active', 1)
                ->addFieldToFilter('entity_id', ['neq' => $quoteId]) // Exclude current quote ID
                ->setPageSize(1);

            $activeQuote = $activeQuoteCollection->getFirstItem();

            if ($activeQuote && $activeQuote->getId()) {
                $quoteId= $activeQuote->getId();
                //$message= "Customer has another active quote with ID: " . $activeQuote->getId().'=='.$customerId;
            }else{
               //$message= "No other active quotes found for the customer.";
               //$messageSuccess=false;
            }
        }else{
            $message= "Customer Session Expired.Please login again.";
            $messageSuccess=false;
        }
    } catch (\Exception $e) {
        // Handle errors (e.g., token not found)
         $message= $e->getMessage();
         $messageSuccess=false;
        //return null;
    }
}
if ($quoteId) {
  // Define an quote id if not exist to add in bulk
      
    try {
        // Load the quote using the QuoteRepository
        $quote = $objectManager->get(\Magento\Quote\Model\QuoteRepository::class)->get($quoteId);
        if (!$quote->getIsActive()) {
            $customerId = $quote->getCustomerId();
    
            if ($customerId) {
                // Check if the customer has any other active quotes
                $activeQuoteCollection = $quoteCollectionFactory->create()
                    ->addFieldToFilter('customer_id', $customerId)
                    ->addFieldToFilter('is_active', 1)
                    ->addFieldToFilter('entity_id', ['neq' => $quoteId]) // Exclude current quote ID
                    ->setPageSize(1);
    
                $activeQuote = $activeQuoteCollection->getFirstItem();
    
                if ($activeQuote && $activeQuote->getId()) {
                    $quoteId= $activeQuote->getId();
                    //$message= "Customer has another active quote with ID: " . $activeQuote->getId();
                }
            } else {
                $message= "The quote is a guest cart without an associated customer.";
                $messageSuccess=false;
            }
        } 
    } catch (\Exception $e) {
        $message= "Please Update App New Version"; // . $e->getMessage();
         // Prepare SQL select statement
        $sql = "SELECT quote_id FROM ahqa_app_cart_report WHERE cart_id = :cart_id";
        $bind = ['cart_id' => $quoteId];
       
        // Execute the query
        $result = $connection->fetchAll($sql, $bind);
    
        // Check if any records found
        if ($result) {
            $quoteId=$result[0]['quote_id'];
        } else {
            $oldquoteId=$quoteId;
            $quoteIdNew = $cartManagement->createEmptyCart();
            $connection->insert('ahqa_app_cart_report', [
                'cart_id' => $oldquoteId,
                'quote_id' => $quoteIdNew,
                'customer_id' => (isset($data->customer_id))? $data->customer_id: null,
                'created_at' => date('Y-m-d H:i:s')
            ]);
             $quoteId=$quoteIdNew;
        }
        //$quoteId=false;
    }
}
if ($quoteId) {
    // // Define an array of items to add in bulk
    try {
      // Load the quote
        $quote = $objectManager->get(\Magento\Quote\Model\QuoteRepository::class)->get($quoteId);
        // Get the existing items in the quote
        $existingItems = $quote->getAllItems();
        $itemToUpdate = [];
        //'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);
                $availableStock=$stockItem->getQty();
                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;
                  $itemToUpdate[$sku]=true;
                  continue;
                }
        
                // Example: Check if item quantity exceeds a limit
                $maxQuantity = $stockItem->getMaxSaleQty(); // Set your maximum quantity limit
                $minQuantity = $stockItem->getMinSaleQty(); // Set your maximum quantity limit
                if ($qty > $maxQuantity) {//requested sku
                     $itemToUpdate[$sku]=true;
                     $itemSku[$sku]="Maximum qty ($maxQuantity) allowed per customer.";
                      $message="The requested qty exceeds the maximum qty ($maxQuantity) allowed in shopping cart";
                     $messageSuccess =false;
                }else if ($qty < $minQuantity) { //requested sku
                     $itemToUpdate[$sku]=true;
                     $itemSku[$sku]="Minimum qty ($minQuantity) allowed in shopping cart";
                     $message="The requested qty ($qty) is below the minimum qty ($minQuantity) allowed in shopping cart";
                     $messageSuccess =false;
                }else if ($qty > $availableStock) { //requested sku
                     $itemToUpdate[$sku]=true;
                     $itemSku[$sku]="Out Of Stock";
                     $message="The requested qty ($qty) is not available.Available Stock is ($availableStock).";
                     $messageSuccess =false;
                }
                if (!empty($existingItems)) { //If cart-have an items then give items list
                    if (!isset($itemToUpdate[$sku])) { //check if cart not merge if requested - $sku
                        foreach ($existingItems as $existingItem) {
                            $cartSku=$existingItem->getProduct()->getSku();
                            $cartQty=$existingItem->getQty();
                            if (!isset($itemToUpdate[$cartSku])) {  //check existing quote item condition - $cartSku
                                $stockItem2 = $objectManager->create(\Magento\CatalogInventory\Api\StockRegistryInterface::class)->getStockItemBySku($cartSku);
                                $availableStock2=$stockItem2->getQty();
                                 if (!$stockItem2->getIsInStock()) {
                                 //return false; // Product is out of stock
                                  $message= "Some Products are Out of Stock.";
                                  $itemSku[$cartSku]='Out Of Stock';
                                  $messageSuccess =false;
                                  $itemToUpdate[$cartSku]=true;
                                }
                                
                                $maxQuantity2 = $stockItem2->getMaxSaleQty(); // Set your maximum quantity limit
                                $minQuantity2 = $stockItem2->getMinSaleQty(); // Set your maximum quantity limit
                                if ($cartQty > $maxQuantity2) {//requested sku
                                     $itemToUpdate[$cartSku]=true;
                                     $itemSku[$cartSku]="Maximum qty ($maxQuantity2) allowed per customer.";
                                      $message="The requested qty exceeds the maximum qty ($maxQuantity2) allowed in shopping cart";
                                     $messageSuccess =false;
                                }else if ($cartQty < $minQuantity2) { //requested sku
                                     $itemToUpdate[$cartSku]=true;
                                     $itemSku[$cartSku]="Minimum qty ($minQuantity2) allowed in shopping cart";
                                     $message="The requested qty ($cartQty) is below the minimum qty ($minQuantity2) allowed in shopping cart";
                                     $messageSuccess =false;
                                }else if ($cartQty > $availableStock) { //requested sku
                                     $itemToUpdate[$cartSku]=true;
                                     $itemSku[$cartSku]="Out Of Stock";
                                     $message="The requested qty ($cartQty) is not available.Available Stock is ($availableStock2).";
                                     $messageSuccess =false;
                                }
                            }
                            if($cartSku === $sku && $existingItem->getQty()==$qty){ //if same qty then don't do anything
                                $itemToUpdate[$sku]=true;
                            }
                            else if ($cartSku === $sku && $existingItem->getQty()!=$qty) { //requested sku
                                 $itemToUpdate[$sku]=true;
                                try {
                                    $itemToUpdate2 =$existingItem; 
                                    $itemToUpdate2->setQty($qty); // Collect totals and save the quote
                                    $quote->collectTotals();
                                    $totalAmount= $quote->getSubtotal();
                                    $quote->save();
                                } catch (\Exception $e) {
                                    $message= $e->getMessage();
                                    $itemSku[$sku]='-'.$e->getMessage(); //'Out Of Stock';
                                    $messageSuccess =false;
                                }
                            }
                        }
                    }
                    
                    //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
                            $totalAmount= $quote->getSubtotal();
                            $quote->save();
                             
                        } catch (\Exception $e) {
                            $message= $e->getMessage();
                            $itemSku[$sku]=$e->getMessage(); //'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();
                        $totalAmount= $quote->getSubtotal();
                        // Save the quote to reflect the changes
                        $quote->save();
                    } catch (\Exception $e) {
                        $message= $e->getMessage();
                        $itemSku[$sku]=$e->getMessage(); //'Out Of Stock';
                        $messageSuccess =false;
                    }
                }
               
            }
        }
        // $quote->collectTotals();
        // $totalAmount= $quote->getSubtotal();
        // // Save the quote to reflect the changes
        // $quote->save();
       
    } catch (\Exception $e) {
        $message= "Can't add: " . $e->getMessage();
        $messageSuccess =false;
    }

}
$result=[ "message"=> $message,"success"=> $messageSuccess,"outofstock"=>$itemSku,"quote_id"=>$quoteId,'subtotal'=>$totalAmount];
echo json_encode($result);