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

$zdb = $_SESSION["zdbyear_" . $dbname];
$zyear = substr($_SESSION["zdbyear_" . $dbname], -4);

$zworkhrs = $_SESSION["zwork"];
$zroot = $_SESSION["zdir"];
$zcono = $_SESSION["zcono"];

if ($zcono == '') {
    $zcono = 1 ;
}

mysqli_select_db($conn, $zdb);

$gcomp = mysqli_query($conn, "SELECT pfbasic, pfmaxamt, esic, esicmaxamt from $zroot.company where code = '$zcono' ")or die(mysqli_error($conn));
$fcomp = mysqli_fetch_array($gcomp);

$zpfperc = $fcomp['pfbasic'];
$zpfmaxamt = $fcomp['pfmaxamt'];
$zesicperc = $fcomp['esic'];
$zesicmaxamt = $fcomp['esicmaxamt'];
$username = $_SESSION['username_' . $dbname];

$gyear = mysqli_query($conn, "SELECT * from $zroot.compyear where cono = '$zcono' and finyear = '$zyear'")or die(mysqli_error($conn));
$fyear = mysqli_fetch_array($gyear);

$zsdate1 = $fyear['startdate'];
$zedate1 = $fyear['lastdate'];

$syear  = date('Y', strtotime($zsdate1)) ;
$eyear  = date('Y', strtotime($zedate1)) ;

//$syear = $fyear['syear'];
//$eyear = $fyear['eyear'];

//browse($syear);
//browse($eyear);

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

    $cond = "";
    $cond1 = "";
    $dcond = "";
    $dcond1 = "";

    if (!empty($_POST["cmbemp"])) {

        $cmbemp = trim($_POST["cmbemp"]);

        $cond = "AND `accode` = '$cmbemp'";
        $cond1 = "AND a.`accode` = '$cmbemp'";
    }

    if (!empty($_POST["cmbdept"])) {
        $dname = trim($_POST["cmbdept"]);
        $dcond = "AND deptcode = '$dname'";
        $dcond1 = "AND a.deptcode = '$dname'";
    }

    $mmon = $_POST["month"];
    $yearno = $_POST["yearno"];
//    browse($mmon);
//    browse($yearno);

    if ($mmon == 13) {
        $dmon = 3 ;
        $mmon = 13 ;
        
        $nextmon = 4;
        $mondate1 = $eyear . '-' . $dmon . '-01';
        $nextdate1 = $eyear . '-' . $nextmon . '-01';
    } else {
        if ($mmon == 12) {
            $nextmon = 1;
            $nextyear = $eyear;

            $mondate1 = $syear . '-' . $mmon . '-01';
            $nextdate1 = $eyear . '-' . $nextmon . '-01';
        } else {
            if ($mmon < 10) {
                $mmon = '0' . $mmon;
            }
            if ($mmon < 4) {
                $nextmon = $mmon + 1;
                $nextyear = $eyear;

                $mondate1 = $eyear . '-' . $mmon . '-01';
                $nextdate1 = $eyear . '-' . $nextmon . '-01';
            } else {
                $nextmon = $mmon + 1;
                $nextyear = $yearno + 1;

                $mondate1 = $syear . '-' . $mmon . '-01';
                $nextdate1 = $syear . '-' . $nextmon . '-01';
                
//                browse($mondate1);
//                browse($nextdate1);
            }
        }
    }
//    browse('mmon-1');
//    browse($mmon);

    $mondate = $mondate1;
    $lastdate = date('Y-m-d', strtotime('-1 days', strtotime($nextdate1)));

    // $lastdate = date('Y-m-d', strtotime($nextdate1, '-1 days'));

    $procdt = $_POST["procdt"];
    $mvouchdt = $procdt;

    $msource = "SALR";

//    browse($lastdate) ;

    $cmain = mysqli_query($conn, "SELECT a.*, b.name as employee, b.custcode, a.basic, b.da, b.hra, b.ta, b.oa, b.pfund, b.esic, b.gender,
                          b.p_tax FROM `attdtran` a, `accmast` b WHERE a.accode = b.accode AND a.mon='$mmon' 
                          and  b.active = 1 $dcond1 $cond1 ORDER BY a.accode, a.deptcode ") or die(mysqli_error($conn));
//    print table($cmain) ;
    
    if (mysqli_num_rows($cmain) <= 0) {
        browse("Record Not Found");
        header("refresh: 1; salproc.php");
        exit;
    }

    $xxmon = $mmon;
    $xxyear = date('Y');
    
    if ($xxmon == 13) {
       $daysmon = 30 ;
    } else {
       $daysmon = cal_days_in_month(CAL_GREGORIAN, $xxmon, $xxyear);
    }   

    mysqli_query($conn, "LOCK TABLES `payproc` WRITE, loan WRITE, loanpay WRITE, profslab WRITE, advance WRITE, actran WRITE");
    mysqli_query($conn, "DELETE  FROM `payproc` WHERE yearno='$yearno' AND monthno='$mmon' AND paid='N' $cond $dcond") or die(mysqli_error($conn));
    mysqli_query($conn, "UNLOCK TABLES");

    if (empty($zworkhrs)) {
        $zworkhrs = 8;
    }

    $monthsal = $basic_sal = $advmon = $absent = $pres = $overday = $salday = $halfsal = $totalamt = $loanmon = $total_ded = $esicamt = $halfday = $round_off = $net_sal = $otsal = $pfamt = $proftax = $proctype = $loanstat = $otday = $othrs = $pd = $paid = $due = $loanno = $dasal = $hrasal = $tasal = $oasal = 0;

    while ($row1 = mysqli_fetch_array($cmain)) {
        $accode = $row1["accode"];
        $employee = $row1["employee"];
        $gender = $row1["gender"];

        $cemp = mysqli_query($conn, "SELECT accode, `paid` FROM `payproc` WHERE yearno = '$yearno' AND monthno = '$mmon'
                                            AND accode = '$accode' ORDER BY accode") or die(mysqli_error($conn));

        $chkemp = mysqli_fetch_array($cemp);
        $paidst = $chkemp["paid"];

        if ($paidst != "Y") {
            $dept = $row1["dept"];
            $absent = $row1["ab"];
            $half = $row1["hf"];
            $otday = $row1["ot"];
            $othrs = $row1["othrs"];
            $pd = $row1["pd"];
            $leave = $row1["leave"];
            $basic = $row1['basic'];
            $da = $row1['da'];
            $hra = $row1['hra'];
            $ta = $row1['ta'];
            $oa = $row1['oa'];
            $salary = $row1["salary"];
            $totdays = $row1["totdays"];

            $deptcode = $row1["deptcode"];
            $employee = $row1["employee"];
            $empcode = $row1["custcode"];

            if ($row1['pr'] > 0) {
                $pres = $row1['pr'];
            } else {
                $pres = $daysmon - $absent - $half;
            }

            $daydetail = "PR-$pres" . " " . "HF-$half";
            if (!empty($ot)) {
                $daydetail = $daydetail . " " . "OT$otday";
            }
            if (!empty($othrs)) {
                $daydetail = $daydetail . " " . "OTHR$othrs";
            }

            $overday = $otday;
            $salday = $pres;

//for full day
//            $presbasic = ($basic / $daysmon) * $pres;
//            $presda = ($da / $daysmon) * $pres;
//            $preshra = ($hra / $daysmon) * $pres;
//            $presta = ($ta / $daysmon) * $pres;
//            $presoa = ($oa / $daysmon) * $pres;
//            $pressal = $presbasic + $presda + $preshra + $presta + $presoa;

            $totsalary = ($salary / $daysmon) * $totdays;

//for half day
//            $halfbasic = (($basic / $daysmon) * $half) / 2;
//            $halfda = (($da / $daysmon) * $half) / 2;
//
//            $halfhra = (($hra / $daysmon) * $half) / 2;
//            $halfta = (($ta / $daysmon) * $half) / 2;
//            $halfoa = (($oa / $daysmon) * $half) / 2;
//
//            $half_sal = $halfbasic + $halfda + $halfhra + $halfta + $halfoa;

//for ot
//            $otdbasic = ($basic / $daysmon) * $otday;
//            $otdda = ($da / $daysmon) * $otday;
//
//            $otdhra = ($hra / $daysmon) * $otday;
//            $otdta = ($ta / $daysmon) * $otday;
//            $otdoa = ($oa / $daysmon) * $otday;
//
//            $otdsal = $otdbasic + $otdda + $otdhra + $otdta + $otdoa;

//for others
//            $othbasic = ($basic / $daysmon / 8) * $othrs;
//            $othda = ($da / $daysmon / 8) * $othrs;
//
//            $othhra = ($hra / $daysmon / 8) * $othrs;
//            $othta = ($ta / $daysmon / 8) * $othrs;
//            $othoa = ($oa / $daysmon / 8) * $othrs;
//
//            $othsal = $othbasic + $othda + $othhra + $othta + $othoa;
//            $otamt = $otdsal + $othsal;

//            $basic_sal = $presbasic + $halfbasic + $otdbasic + $othbasic;
//            $dasal = $presda + $halfda + $otdda + $othda;
//            $hrasal = $preshra + $halfhra + $otdhra + $othhra;
//            $tasal = $presta + $halfta + $otdta + $othta;
//            $oasal = $presoa + $halfoa + $otdoa + $othoa;

            
//            $monthsal = $basic_sal + $dasal + $hrasal + $tasal + $oasal;
//            $totalamt = round($monthsal);
            
            $totalamt = round($totsalary);
            $monthsal = $totalamt ;
            
//            $calcsal = $basic_sal + $dasal;

            $pfamt = 0;
//            if ($row1['pfund'] == "Y") {
//                if ($calcsal < $zpfmaxamt) {
//                    $pfamt = ($calcsal * $zpfperc) / 100;
//                } else {
//                    $pfamt = $zpfmaxamt * $zpfperc / 100;
//                }
//            }

            $esicamt = 0;
//            if ($row1['esic'] == "Y") {
//                if ($calcsal > $zesicmaxamt) {
//                    $esicamt = 0;
//                } else {
//                    $esicamt = $totalamount * $zesicperc / 100;
//                }
//            }

//            if ($row1['p_tax'] == "Y") {
//                $gproftax = mysqli_query($conn, "SELECT * FROM profslab where gender = '$gender' and 
//                                                        '$totalamount' BETWEEN `slabfrom` and `slabto` and oddmonth > 0 ")or die(mysqli_error($conn));
//                $fproftax = mysqli_fetch_object($gproftax);
//                $oddmonth = $fproftax->oddmonth;
//
//                if ($oddmonth == $mmon) {
//                    $proftax = $fproftax->oddamt;
//                } else {
//                    $gproftax1 = mysqli_query($conn, "SELECT * FROM profslab where gender = '$gender' and 
//                                                        '$totalamount' BETWEEN `slabfrom` and `slabto` and oddmonth != '$oddmonth' ")or die(mysqli_error($conn));
//                    $fproftax1 = mysqli_fetch_object($gproftax1);
//                    $proftax = $fproftax1->amount;
//                }
//            }

            //////////////////   loan part
            
//            browse('work in progress...') ;

            $loanmon = 0;
            $balloan = 0;

//            browse('mondate');
//            browse($mondate);
//            
//            browse('accode');
//            browse($accode);

            $chkloan = mysqli_query($conn, "SELECT * FROM `loan` WHERE accode = '$accode' and `vouchdt` < '$mondate' order by vouchdt desc limit 0,1") or die(mysqli_error($conn));
//            print table($chkloan);
//            die();
//            browse(mysqli_num_rows($chkloan));

            if (mysqli_num_rows($chkloan) > 0) {
                $xloan = mysqli_fetch_array($chkloan);

                $loanno = $xloan["vouchno"];
                $loanamt = $xloan["amount"];

                $loandt = $xloan["vouchdt"];
                $instamt = $xloan["insamt"];

//                browse($accode);
//                browse($loanno);

//                browse('mmon');
//                browse($mmon);
//                
//                browse('loan');
//                browse($loanamt);
//
//                browse('loan date');
//                browse($loandt);

                $chkloanpay = mysqli_query($conn, "SELECT SUM(paidamt) AS loanpaid FROM `loanpay` WHERE `vouchno` = '$loanno' AND `accode` = '$accode' 
                                                          AND loandt <= '$loandt' and month != '$mmon'") or die(mysqli_error($conn));

                $tloan = mysqli_fetch_array($chkloanpay);
                $tloanpaid = $tloan["loanpaid"];
                $balloan = $loanamt - $tloanpaid;

//                browse('amt');
//                browse($loanamt);
//                browse($tloanpaid);
//                browse('balloan');
//                browse($balloan);

                if ($balloan > 0) {
                    if ($balloan <= $instamt) {
                        $loanmon = $balloan;
//                        browse('bal');
                    } else {
                        $loanmon = $instamt;
//                        browse('inst');
//                        browse($instamt);
                    }
                } else {
                    $loanmon = 0;
                }
            } else {
                $loanmon = 0;
                $balloan = 0;
                $loanstat = 0;
            }
//            browse('loanmon');
//            browse($loanmon);

            $halfday = $half;

            $chkadv = mysqli_query($conn, "SELECT SUM(amount) as advamt FROM `cashgive` WHERE accode = '$accode' AND MONTH(vouchdt) = '$mmon' ") or die(mysqli_error($conn));
            $adv = mysqli_fetch_array($chkadv);
            $advmon = $adv["advamt"];
            
//            browse('adv');
//            browse($advmon);
            
            $paidamt = 0; // Need to rectified
            $provfund = 0;
            $staffund = 0;
            $miscdedn = 0;
            $miscamt = 0;
            $proctype = "";
            $loanstat = $balloan - $loanmon;

            $total_ded = $loanmon + $advmon + $proftax + $pfamt + $esicamt;

            $net_sal = $totalamt - $total_ded;
            
            $round_off = round($net_sal) - $net_sal;
            
//            browse($accode) ;

            $paid = "N";
            mysqli_query($conn, "INSERT INTO `payproc`(`vouchdt`, `dateproc`, `yearno`, `monthno`, `dept`, `deptcode`, `empcode`, 
                                               `empname`, `accode`, `salary`, `basic`, `advance`, `absent`, `present`,
                                               `overday`, `salday`, `halfsal`, `monsalary`, `totalamt`, `loan`, `servchgs`,
                                               `total_ded`,`esic`, `halfday`, `round_off`, `net_sal`, `otamt`, `provfund`,
                                               `proftax`, `proctype`, `loanstat`, `ot`, `othrs`, `pd`, `paid`, `xkey`,
                                               `username`, `dueday`, `loanno`, `daydetail`, `da`, `hra`, `ta`, `oa`, `pfflag`,
                                               `ptflag`, `esicflag`)
                                        VALUES('$mvouchdt', '$procdt', '$yearno', '$mmon', '$dept', '$deptcode', '$empcode', 
                                               '$employee', '$accode', '$monthsal', '$basic_sal', '$advmon', '$absent', '$pres',
                                               '$overday', '$salday', '$halfsal', '$monthsal', '$totalamt', '$loanmon', '0',
                                               '$total_ded','$esicamt', '$halfday', '$round_off', '$net_sal', '$otsal', '$pfamt',
                                               '$proftax', '$proctype', '$loanstat', '$otday', '$othrs', '$pd', '$paid', '',
                                               '$username', '$due', '$loanno', '$daydetail', '$dasal', '$hrasal', '$tasal', '$oasal', '$row1[pfund]',
                                               '$ptflag', '$row1[esic]')") or die(mysqli_error($conn)); // provide '' for xkey

            /*             * Loan Pay Part* */

            mysqli_query($conn, "DELETE FROM `loanpay` WHERE `accode` = '$accode' AND `vouchno` = '$loanno' AND `yearno` = '$yearno' AND month = '$mmon' ") or die(mysqli_error($conn));

            if ($loanmon > 0) {
                mysqli_query($conn, " INSERT INTO `loanpay`(vouchno, loanno, loandt, loanamt, paidamt, accode, yearno, month, procdate, lastdate)
                                      VALUES ('$loanno', '$loanno', '$loandt', '$loanamt', '$loanmon', '$accode', '$yearno', '$mmon', '$procdt', '$lastdate') ") OR die(mysqli_error($conn));
            }

            /*             * Accounts Part* */

            mysqli_query($conn, "DELETE FROM `actran` WHERE `vouchno` = '$accode' AND `source` = '$msource' AND monthno = '$mmon'") OR die(mysqli_error($conn));

            if ($net_sal > 0) {
                $minus_amt = ($net_sal * -1);
                // first cash part
                mysqli_query($conn, " INSERT INTO `actran`(date, vouchno, trnno, type, `source`, `bankinit`, `grpcode`, init, accode, amount,
                                                   chqno, chqdate, `drawbank`, `petycode`, `markflag`, `trnflag`, chqret, retdate, 
                                                   recpno, clrdate, monthno)
                                           VALUES ('$mvouchdt', '$accode', '001', '', '$msource', '', '012', '', '035', '$minus_amt',
                                                    '', '0000-00-00', '', '', '', '', 'N', '0000-00-00', '', '0000-00-00', '$mmon')");
                // party part
                mysqli_query($conn, " INSERT INTO `actran`(date, vouchno, trnno, type, `source`, `bankinit`, `grpcode`, init, accode, amount,
                                                   chqno, chqdate, `drawbank`, `petycode`, `markflag`, `trnflag`, chqret, retdate,
                                                   recpno, clrdate, monthno)
                                           VALUES('$mvouchdt', '$accode', '002', '', '$msource', '', '044', '', '$accode', '$net_sal',
                                                   '', '0000-00-00', '', '', '', '', 'N', '0000-00-00', '', '0000-00-00', '$mmon')");
            }
        }
    }
    browse("Processing Complete");
}
?>

<!DOCTYPE HTML>
<html lang="en-US">
    <head>
        <meta charset="UTF-8">
        <title>Salary Procedure</title>

        <link href='http://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
        <link rel="stylesheet" href="alight/reset.css" />
        <link rel="stylesheet" href="light/general-light.css" />
        <link rel="stylesheet" href="css/chosen.css" />

        <!--[if lt IE 9]>
                <script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE9.js"></script>
    <script src = "http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
        <!--for alert box-->
        <script type="text/javascript" src="javascript/jquery.min.js"></script>
        <link rel="stylesheet" type="text/css" href="javascript/msgbox/jquery.msgbox.css" />
        <script type="text/javascript" src="javascript/msgbox/jquery.msgbox.min.js"></script>
        <!---->
    </head>
    <body>
        <!--        <div style="width: 40%; float: right; border: 0px solid red;">
        <?php
        echo "<b>Already Processed Months</b><hr/>";
        echo "<table cellspacing='0' cellpadding='0'>";
        while ($row2 = mysqli_fetch_assoc($getprocmon)) {
            $totsal = $row2["totnet"];
            $totsal1 = $totsal1 + $totsal;

            echo "<tr style='border-bottom: 1px solid black;'>";
            echo "<td width='100' style='border-bottom: 1px solid black;'>";
            echo "<font color='0099FF'><b>" . monthname($row2["monthno"]) . "</b></font>";
            echo "</td>";
            echo "<td style='border-bottom: 1px solid black;text-align: right;'>";
            echo "<b>" . round($row2["totnet"]) . "</b>";
            echo "</td>";
            echo "</tr>";
        }
        echo "<tr>";
        echo "<td style='border-bottom: 1px solid black;'>";
        echo "<font color='red'><b>Total</b></font>";
        echo "</td>";
        echo "<td style='border-bottom: 1px solid black;text-align: right;'>";
        echo "<font color='red'><b>" . round($totsal1) . "</b></font>";
        echo "</td>";
        echo "</tr>";
        echo "</table>";
        ?>
                </div>-->

    </div>
</form>

<script src="js/chosen.jquery.js" type="text/javascript"></script>
<script type="text/javascript"> $(".chzn-select").chosen();
    $(".chzn-select-deselect").chosen({allow_single_deselect: true});</script>

</body>
</html>