<?php
  
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if($_POST["submit"])

{

	$tname= $_POST['descrip'];
	$tPrice=$_POST['tprice'];   
    $sdate=$_POST['sdate']; 
    $user=$_POST['user'];
    $iname  = $_POST['descrip'];                                                      //CHECKING ENDS HERE

  require_once"labClass.php";

  $con=new labClass();

  if(!$con->vtPrice($tPrice))
          
          {
            
          ?>
            <h6 class="text-danger">Error occured!..</h6>
          <?php
            require_once "excwithdrawrf.php";

 
        }
 
  else    {
           $recID=1;
           $r= $con->getExcBalance($recID)->fetch();
           if($r['cbalance']>=$tPrice){
           $bal=$r['cbalance']-$tPrice;
           $u= $con->updateExcBalance($recID,$bal);
               $rQ= $con->excessbalwithdraw($tname, $tPrice,$sdate,$user);

               //print_r($rQ);

 if($rQ->rowCount()>0)
    {

  $Q= $con->getThisItem($iname);
  if($Q->rowCount()>0)
    {
   $in=$Q->fetch();
   $tQty=$in['iqty']-1;
   if($rQ->rowCount()>0)
      {
       ///itemID:itemID,iqty:iqty,nQty:nQty,isprice:isprice,ipprice:ipprice,iname:iname,tQty:tQty
        $Qr= $con->updateItemExBmoney($iname,$tQty);
        if($Qr->rowCount()>0)
      {
                ?>
                <h6 class="text-success">Withdraw successfull !..</h6>
                <?php
              
              
              ////////////////////////////////////////
              
             
	$tname= $iname;
	$tPrice=$tPrice;   
    $sdate=$_POST['sdate']; 
    $user=$_POST['user'];
                                                             //CHECKING ENDS HERE
 

            if(!$con->vtPrice($tPrice))
                       {
                       ?>
                        <h6 class="text-danger">Error occured!..</h6>
                      <?php
                       }
 
                       else    {
                                if($tname=="SHOP(Cash in hand)" || $tname=="Other source")
                                  {
                                    $recID=$_POST['sourceID'];
                                     $r= $con->getBalance($recID)->fetch();
                                      if($r['cbalance']>=$tPrice){
                                         $bal=$r['cbalance']-$tPrice;
                                          $u= $con->updateBalance($recID,$bal);
                                          $rQ= $con->balwithdraw($recID,$tname, $tPrice,$sdate,$user);
                                 if($rQ->rowCount()>0)
                                    {
                                       require_once "excwithdrawrf.php";
                                     }
                                    }else{
                                    echo "Invalid amount!..";
                                        
                                    }
                                  }else{
                               /////////////////////
                               
                            // withdrawal amount requested
                            $withdrawAmount = $tPrice;
                            
                            // fetch balances 
                            
                            $stmt = $con->getPairBalance();
                            $balances = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
                            
                            $cashBalance   = $balances['SHOP(Cash in hand)'] ?? 0;
                            $sourceBalance = $balances['Other source'] ?? 0;
                            
                            $totalAvailable = $cashBalance + $sourceBalance;
                            
                            if ($withdrawAmount > $totalAvailable) {
                                die("Insufficient funds! Available: $totalAvailable");
                            }
                            
                            $cashUsed = 0;
                            $sourceUsed = 0;
                            
                            // Deduct from cash first
                            if ($withdrawAmount <= $cashBalance) {
                                $cashUsed = $withdrawAmount;
                                $cashBalance -= $cashUsed;
                                } 
                               else {
                                // Use all cash, then take the rest from other source
                                $cashUsed = $cashBalance;
                                $withdrawRemaining = $withdrawAmount - $cashBalance;
                            
                                $cashBalance = 0;
                            
                                if ($withdrawRemaining <= $sourceBalance) {
                                    $sourceUsed = $withdrawRemaining;
                                    $sourceBalance -= $sourceUsed;
                                   } else {
                                    // This case should not happen since we checked total available
                                    die("Unexpected error in withdrawal distribution!");
                                  }
                                }
                            
                             
                                $tname="SHOP(Cash in hand)"; $bal=$cashBalance;
                                $ca= $con->updateBalanceByAccN($tname,$bal);
                             
                                 $tname="Other source"; $bal=$sourceBalance;
                                 $cb= $con->updateBalanceByAccN($tname,$bal);
                             
                                $recID=12;$tname=$_POST['descrip']." :Shop: $cashUsed, Other Source: $sourceUsed";
                                $cc= $con->balwithdraw($recID,$tname, $tPrice,$sdate,$user);
                            
                             
                            
                            //echo "Withdrawal successful! Cash used: $cashUsed, Other Source used: $sourceUsed";
                            
                               //////////////
                                  }
                                } 
                                          
                                          
              
              ///////////////////////////////////////////
              
              
               

               }
           }else{
               echo "Invalid amount!..";
           }
       }else{
               echo "Update failed!..";
      }
      
      
      }else{
               echo "Item not found!..";
           }
   
 
         }
}
}

?>