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

{

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

  require_once"labClass.php";

  $con=new labClass();

  if(!$con->vtPrice($tPrice))
          
          {
            
          ?>
            <h6 class="text-danger">Error occured!..</h6>
          <?php
            require_once "balancewithdraw.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);

               //print_r($rQ);

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

                 
                ?>
                <h6 class="text-success">Successfull added!..</h6>
                <?php
              
                require_once "balancewithdraw.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['tname']." :Shop: $cashUsed, Other Source: $sourceUsed";
    $cc= $con->balwithdraw($recID,$tname, $tPrice,$sdate,$user);

 

echo "Withdrawal successful! Cash used: $cashUsed, Other Source used: $sourceUsed";

   //////////////
      }
         }
}


?>