<?php

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

$maindb = "widowhelp";
$trandb = "widowmonth";

$formname = "WIDOW HELP - MONTHLY";
$file = "widowgen.php";

$compcd = $_SESSION["comp_" . $dbname];
$zroot = $_SESSION["zdir"];

$admin = $_SESSION["admin_" . $dbname];
$zdb = $_SESSION["zdbyear_" . $dbname];
$myyear = $_SESSION[$myyear];
mysqli_select_db($conn, $zdb);


if (isset($_POST["excel"])) {

//    $mfrmdate = trim($_POST["fdate"]);
//    $mtodate = trim($_POST["tdate"]);

    $mmon = $_POST["month"];

    $a = 0;

    $getchk = mysqli_query($conn, "SELECT * FROM `$trandb` WHERE month = '$mmon' ")or die(mysqli_error($conn));
    $getnos = mysqli_num_rows($getchk);
    if ($getnos > 0) {
        browse("Widow Help Generated For This Month - " . $mmon);
        $a = 1;
    }

//    if (empty($_POST["fdate"])) {
//        browse("From Date Cannot Be Empty");
//    }
//    if (empty($_POST["tdate"])) {
//        browse("To Date Cannot Be Empty");
//    }


    if ($a == 0) {
        $getcomp = mysqli_query($conn, "SELECT * FROM $zroot.company WHERE code = 1 ")or die(mysqli_error($conn));
        $getc = mysqli_fetch_array($getcomp);
        $mastamt = $getc["widow"];
//        browse($mastamt);

        $getpmain = mysqli_query($conn, "SELECT * FROM `$maindb` WHERE `active` > 0 group by memcode order by memcode ")or die(mysqli_error($conn));
        $getn = mysqli_num_rows($getpmain);

        $ctr = 0;
        $totamt = 0;
        $totdisc = 0;
        $totbill = 0;

        while ($pmain = mysqli_fetch_array($getpmain)) {
            $memcode = $pmain[memcode];

            $ctr++;
            mysqli_query($conn, "DELETE from `widowmonth` where month = '$mmon' and `memcode`= '$memcode' ")or die(mysqli_error($conn));

            mysqli_query($conn, "INSERT into `widowmonth` (series, memcode, month, amount) values ('$series', '$memcode' , '$mmon', '$mastamt' )") or die(mysqli_error($conn));
        }
    
        browse('Generated Successfully. Widow Help For Month - ' . $mmon) ;
    }       
}
?>