<?php 
include("conn.php");
session_start();

function getTotalPin()
{
  include "conn.php";
  $v_code=$_SESSION['v_code'];

  $total = 0;
  $query = "select pin as tot from tbl_vendor where v_code='$v_code'";
  $smt1 = mysqli_query($conn, $query);
  if ($result = mysqli_fetch_assoc($smt1)) {
    if ($result['tot'])
      $total = $result['tot'];
  }
  return ($total);
}


$did=$_SESSION['v_code'];
if($_POST['action'])
{
  $action=$_POST['action'];
  //Add Data Start
  if($action=="Add")
  {
    if($_POST['did'] && $_POST['nop'])
    {
        $sid=$_POST['did'];
        $nop=$_POST['nop'];
        
        if(getTotalPin()>=$nop)
        {
                $sql="insert into tbl_pin1 (did,sid,nop)values('$did','$sid','$nop')";
                if(mysqli_query($conn,$sql))
                {
                   $sql="update tbl_vendor set pin=pin-'$nop' where v_code='$did'";
                   mysqli_query($conn,$sql);
                   
                   $sql="update tbl_vendor set pin=pin+'$nop' where v_code='$sid'";
                   mysqli_query($conn,$sql);
                   
                   
                  echo "Record added successfully.".$did.$sid;
                }
                else
                {
                  echo "Record not added. Error:".mysqli_error($conn);
                }
        }
        else
        {
            echo "Sorry Insufficient PIN";
        }

    }
    else
    {
      echo "Please complete all required fields.";
    }
  }

}
else
{
  echo "Invalid action specified.";
}
mysqli_close($conn);
?>