<?php

require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include ("includes/function.php");

$zdb = $_SESSION["zdbyear_$dbname"];
mysqli_select_db($conn, $zdb);
$zroot = $_SESSION["zdir"];

if ($_REQUEST["para"]) {
    $vouchno = $_REQUEST["vouchno"];
    $firstdate = $_REQUEST["firstdate"];
    $treatment = $_REQUEST["treatment"];
    $qty = $_REQUEST["qty"];
    $duration = $_REQUEST["duration"];
    mysqli_query($conn, "Delete from `schedtreattemp` WHERE vouchno = '$vouchno' and treatment = '$treatment' ") or die(mysqli_error($conn));
}

if ($_REQUEST["firstdate"]) {
    $vouchno = $_REQUEST["vouchno"];
    $firstdate = $_REQUEST["firstdate"];
    $treatment = $_REQUEST["treatment"];

    $gettt = mysqli_query($conn, "SELECT code,name FROM `treatment` WHERE `name`='$treatment'") or die(mysqli_error($conn));
    if (mysqli_num_rows($gettt) > 0) {
        $tcode = mysqli_fetch_array($gettt);
        $treatcode = $tcode['code'];
    }
    $qty = $_REQUEST["qty"];
    $duration = $_REQUEST["duration"];
    $sctr = 0;
    $getsched = mysqli_query($conn, "SELECT * FROM `schedtreat` WHERE vouchno = '$vouchno' and treatment = '$treatcode'  ")or die(mysqli_error($conn));
    $row = mysqli_num_rows($getsched);
    if ($row > 0) {
        echo "2";
    } else {
        $nduration = $firstdate;
        mysqli_query($conn, "Delete from schedtreattemp WHERE vouchno = '$vouchno' and treatment = '$treatcode' ");
        for ($i = 0; $i < $qty; $i++) {
            $sctr++;
            mysqli_query($conn, "INSERT INTO `schedtreattemp`(`vouchno`, `srno`, `treatment`, `scheddate`)
                                                  VALUES ('$vouchno', '$sctr', '$treatcode', '$nduration')")or die(mysqli_error($conn));

            $fduration = strtotime($nduration);
            $tduration = strtotime("+" . $duration . " days", $fduration);

            $nduration = date("Y-m-d", $tduration);
        }
    }
}
?>