<?php
session_start();
include("../../php_crud/my_class.php");
$obj=new my_class();
// ============
extract($_POST);

$branchid = $_SESSION['LOGIN_BRANCH'];
//$branchid = "3";
//echo "<pre>";
//print_r($_SESSION);
//echo "<hr>";
//print_r($_REQUEST);
//echo "</pre>";
// =================== Basic Find Out ========================
function Basic($gross,$fixed,$percent_sum){
    $net_gross = $gross-$fixed;
    $basic = ($net_gross*100)/(100+$percent_sum);
    return $basic;
}
// ================ Percent Value Find Out ====================
function Percent($basic,$percent){
    $amount = ($basic*$percent)/100;
    return $amount;
}
if(isset($_REQUEST["function"]) && $_REQUEST["function"]=="changeSalaryData")
{
$salary_type=$_REQUEST["salary_type"];
$salary=$_REQUEST["salary"];
$totalpercentage=100;
$totalpercentage_individual=0;
$totalinvAmount=0;
$totalinvAmount_individual=0;
    foreach ($_SESSION["payroll_head"] as $key=>$value)
    {

        if($value["cal_type"]=="P" && $value["pay_type"]=="G")
        {
            $totalpercentage=$totalpercentage+$value["value"];
        }
        else if($value["cal_type"]=="F" && $value["pay_type"]=="G")
        {
            $totalinvAmount=$totalinvAmount+$value["value"];
        }
        else if($value["cal_type"]=="F" && $value["pay_type"]=="I")
        {
            IF(ISSET($_SESSION["headIndividual"]) && $_SESSION["headIndividual"][$key][1]=="true")
            {
                $totalinvAmount_individual=$totalinvAmount_individual+$_SESSION["headIndividual"][$key][0];

            }

        }
        else if($value["cal_type"]=="P" && $value["pay_type"]=="I")
        {
            IF(ISSET($_SESSION["headIndividual"]) && $_SESSION["headIndividual"][$key][1]=="true")
            {
                $totalpercentage_individual=$totalpercentage_individual+$_SESSION["headIndividual"][$key][0];

            }

        }
    }
    if($salary_type=="B")
    {
        $basicSlary=$salary;
    }
    else{


        $basicSlary=$salary-$totalinvAmount;
        $basicSlary=($basicSlary/$totalpercentage)*100;
	}

?>
<div class="profile-user-info profile-user-info-striped span6" style="width: 80%; margin-left:12px;">
	<div class="profile-info-row" style="width: 100%">
		<div class="profile-info-name" style="width: 50%"> Basic </div>

		<div class="profile-info-value" style="padding-left:20%">
			<span class="editable" id="username"><?php echo round($basicSlary);?></span>
		</div>
	</div>
</div>
<?php
	$grandsalary=$basicSlary;
foreach ($_SESSION["payroll_head"] as $key=>$values)
{
	//pay_type
    if($values["pay_type"]=="G")//general
	{

        ?>
		<div class="profile-user-info profile-user-info-striped span6" style="width: 80%">
			<div class="profile-info-row" style="width: 100%">
				<div class="profile-info-name" style="width: 50%"> <?php echo $values["name"]; echo " (".$values["value"];if($values["cal_type"]=="P"){ ECHO "%"; } echo ")";?> </div>

				<div class="profile-info-value" style="padding-left:20%">
					<span class="editable" id="username">
						<?php
                        if($values["cal_type"]=="P")
						{
							echo round(($basicSlary*$values["value"])/100);
                            $grandsalary=$grandsalary+ round(($basicSlary*$values["value"])/100);
						}
                        else if($values["cal_type"]=="F")
                        {
                        	echo round($values["value"]);
                            $grandsalary=$grandsalary+ round($values["value"]);
                        }
						?>
					</span>
				</div>
			</div>
		</div>
        <?php
	}

}

    ?>
    <div class="profile-user-info profile-user-info-striped span6" style="width: 80%">
        <div class="profile-info-row" style="width: 100%">
            <div class="profile-info-name" style="width: 50%; background-color:lightgreen;"> Gross </div>

            <div class="profile-info-value" style="padding-left:20%;background-color:lightgray;">
			<span class="editable" id="username" style="font-weight: bold "> <?PHP
                if($salary_type=="B")
                {
                    echo round($grandsalary);
                }else
                {
                    echo round($salary);
                }

                ?></span>
            </div>
        </div>
    </div>

    </div>
    <?php
    foreach ($_SESSION["payroll_head"] as $key=>$values)
    {
        if($values["pay_type"]=="I")//individual
        {
            ?>
            <div class="profile-user-info profile-user-info-striped span6" style="width: 80%">
                <div class="profile-info-row" style="width: 100%">
                    <div class="profile-info-name" style="width: 50%"> <?php echo $values["name"]; echo " (".$values["value"];if($values["cal_type"]=="P"){ ECHO "%"; } echo ")";?> </div>

                    <div class="profile-info-value" style="padding-left:20%">
					<span class="editable" id="username">
						<?php

                        if(isset($_SESSION["headIndividual"]) && $_SESSION["headIndividual"][$key][1]=="true")
                        {

                            if($values["cal_type"]=="P")
                            {
                                echo round(($basicSlary*$_SESSION["headIndividual"][$key][0])/100);
                                $grandsalary=$grandsalary+ round(($basicSlary*$_SESSION["headIndividual"][$key][0])/100);
                            }
                            else if($values["cal_type"]=="F")
                            {
                                echo round($_SESSION["headIndividual"][$key][0]);
                                $grandsalary=$grandsalary+ round($_SESSION["headIndividual"][$key][0]);
                            }

                        }
                        else{
                            echo "0";
                        }

                        ?>
					</span>
                    </div>
                </div>
            </div>
            <?php
        }
    }

    ?>
    <div class="profile-user-info profile-user-info-striped span6" style="width: 80%">
        <div class="profile-info-row" style="width: 100%">
            <div class="profile-info-name" style="width: 50%; background-color:lightgreen;"> Total </div>

            <div class="profile-info-value" style="padding-left:20%;background-color:lightgray;">
			<span class="editable" id="username" style="font-weight: bold "> <?PHP

                $totalpercentage_individual_cal=($basicSlary*$totalpercentage_individual)/100;
                $salary=$salary+$totalpercentage_individual_cal+$totalinvAmount_individual;

                if($salary_type=="B")
                {
                    echo round($grandsalary);
                }else
                {
                    echo round($salary);
                }

                ?></span>
            </div>
        </div>
    </div>

    </div>
    <?php

}
if(isset($_REQUEST["function"]) && $_REQUEST["function"]=="changeSalaryIndivutaldata")
{
    $head_name=$_REQUEST["head_name"];
    $head_value=$_REQUEST["head_value"];
    $hidd=$_REQUEST["hidd"];
    $_SESSION["headIndividual"][$head_name]=array($head_value,$hidd);
}
if(isset($_REQUEST["function"]) && $_REQUEST["function"]=="updateSalaryReductionSetup")
{
    $salary_reduce_days=$_REQUEST["salary_reduce_days"];
    $late_days=$_REQUEST["late_days"];
    //$sql="Update `_pay_roll_late_absenc_setup` set salary_reduce_days='".$salary_reduce_days."' and late_days='".$late_days."'";
    $sql_array=array('_salary_reduce_days'=>$salary_reduce_days,'_late_days'=>$late_days);
    $entry2=$obj->Update_Data("_pay_roll_late_absenc_setup",$sql_array,"_br_id='$branchid' ");
    echo "Update Successful";
}
if(isset($_REQUEST["function"]) && $_REQUEST["function"]=="AddSalaryReductionSetup")
{
    $salary_reduce_days=$_REQUEST["salary_reduce_days"];
    $late_days=$_REQUEST["late_days"];
    //$sql="Update `_pay_roll_late_absenc_setup` set salary_reduce_days='".$salary_reduce_days."' and late_days='".$late_days."'";
    $sql_array=array(
            '_salary_reduce_days'=>$salary_reduce_days,
        '_late_days'=>$late_days,
        '_br_id'=>$branchid
    );
    $entry2=$obj->Insert_Data("_pay_roll_late_absenc_setup",$sql_array);
    echo "Add Successful";
}
if(isset($_REQUEST["function"]) && $_REQUEST["function"]=="createDefaultHolidayPack")
{
    $days=array(
            'Saturday'=>'0',
            'Sunday'=>'1',
            'Monday'=>'1',
            'Tuesday'=>'1',
            'Wednesday'=>'1',
            'Thursday'=>'1',
            'Friday'=>'0'
    );

    foreach ($days as $key=>$value)
    {
        $sql_array=array(
            '_br_id'=>$branchid,
            '_days'=>$key,
            '_status'=>$value
        );
        $entry2=$obj->Insert_Data("_payroll_weekly_holiday",$sql_array);
    }
    echo "Weekly Holiday Pack create Successful";
}
if(isset($_REQUEST["function"]) && $_REQUEST["function"]=="WeeklyStatusChange")
{
    $id=$_REQUEST["id"];
    $status=$_REQUEST["status"];

    if($status=="0")
    {
        ?><div id='WeeklyStatusBtn<?php echo $id;?>'><button class='btn btn-minier btn-danger no-padding'  onclick="WeeklyStatusChange('<?php echo $id;?>','1')">Off</button></div>
        <?php
    }
    if($status=="1")
    {
        ?><div  id='WeeklyStatusBtn<?php echo $id;?>'><button class='btn btn-minier btn-success no-padding' onclick="WeeklyStatusChange('<?php echo $id;?>','0')">On</button></div>
        <?php
    }
    $sql_array=array('_status'=>$status);
    $obj->Update_Data("_payroll_weekly_holiday",$sql_array,"_br_id='$branchid' and _id='$id'");

}
if(isset($_REQUEST["function"]) && $_REQUEST["function"]=="AddTax")
{
    $TaxAmount=$_REQUEST["TaxAmount"];
    $sql_array=array(
        '_value'=>$TaxAmount,
        '_status'=>'1',
        '_br_id'=>$branchid,
        '_type'=>$type
    );
    $entry2=$obj->Insert_Data("_payroll_tax_setup",$sql_array);
    echo "Add Successful";
}
if(isset($_REQUEST["function"]) && $_REQUEST["function"]=="ModifyTax")
{
    $TaxAmount=$_REQUEST["TaxAmount"];
    $sql_array=array(
        '_value'=>$TaxAmount,
    );
    $entry2=$obj->Update_Data("_payroll_tax_setup",$sql_array,"_br_id='$branchid' and _type='$type'");
    echo "Update Successful";
}
if(isset($_REQUEST["function"]) && $_REQUEST["function"]=="ActiveInacriveTaxStatus")
{

    $status=$_REQUEST["status"];
    $Taxstatus="";
    $TaxClass="";
    $TaxnStatus="";
    if($type=="1")
    {
        $resdiv="taxStatusResult";
        $jsfunc="ActiveInacriveTaxStatus";
    }
    else if($type=="2")
    {
        $resdiv="StampStatusResult";
        $jsfunc="ActiveInacriveStampStatus";
    }
    if($status=="0")
    {
        $Taxstatus="Inactive";
        $TaxClass="danger";
        $TaxnStatus="1";
        echo "<span id='<?php echo $resdiv; ?>'><button class='btn btn-small btn-$TaxClass btn_only' onclick='$jsfunc($TaxnStatus)'>$Taxstatus</button></span>";
    }
    if($status=="1")
    {
        $Taxstatus="Active";
        $TaxClass="success";
        $TaxnStatus="0";
        echo "<span id='<?php echo $resdiv; ?>'><button class='btn btn-small btn-$TaxClass btn_only' onclick='$jsfunc($TaxnStatus)'>$Taxstatus</button></span>";
    }
    $sql_array=array('_status'=>$status);
    $obj->Update_Data("_payroll_tax_setup",$sql_array,"_br_id='$branchid' and _type='$type'");

}
if(isset($_REQUEST["function"]) && $_REQUEST["function"]=="SearchEmpSalaryListMonthly")
{
    $month=$_REQUEST["month"];
    $year=$_REQUEST["year"];
    $fastival=$_REQUEST["fastival"];
    $trowHead_f = $obj->Total_Count_By_Cond("_pay_roll_details","_br_id='$branchid' AND _month='$month' AND _year='$year' AND _status='A'");
    IF($trowHead_f>0)
    {
        $pstatus="A";
    }
    ELSE{
        $pstatus="P";
    }

    $Days=Array();
    foreach ($obj->View_All_By_Cond("_payroll_weekly_holiday"," _status='0'") AS $v21) {
        $Days[]=$v21["_days"];
    }
    $month_day = cal_days_in_month(CAL_GREGORIAN,$month,$year);
    $date_1  = strtotime("$year-$month-01");
    $date_2 = strtotime("$year-$month-$month_day");
    //$days = array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday');
    $count = 0;
    $dcount = 0;
    $daycount = 0;
    foreach ($Days as $nday)
    {
        while ($date_1 < $date_2) {
            if(date('l', $date_1) == $Days[$dcount]);
            {
                $count++;
            }
            $date_1 += 7 * 24 * 3600;
        }
        $daycount=$daycount+$count;

        $dcount++;
    }
    if($govtHoliday=="")
    {
        $govtHoliday=0;
    }
    $workingDays=$month_day-$daycount-$govtHoliday;
    $TotalHoliday=$govtHoliday;

    ?>
    <style>

        #sample-table-1 tr th{

            font-size:9px;

        }
        .grandSlaray{
            font-size:13px;
            font-weight: bolder;
            color: dimgray;
            border-color: dimgray;
        }

    </style>
    <div class="page-content" style="padding: 0px;">

        <div id="modal-table" class="modal hide fade  " style="width:60%; left: 40%; overflow-x:show" tabindex="-1">
            <form class="form-vertical" >
                <div class="modal-header no-padding">
                    <div class="table-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        Edit employee monthly salary
                    </div>
                </div>
                <div class="modal-body " id="model_table_value">
                </div>

                <div class="modal-footer">
                    <button  class="btn btn-small btn-success btn_only" data-dismiss="modal" id="pay_update" type="button" style=" display: block; float: left;margin-left:13px;">
                        <i class="icon-ok bigger-100"></i>
                        Save
                    </button>

                    <!-- <button onclick="e_call_save('e_all')" class="btn btn-small btn-success btn_all" data-dismiss="modal" type="button" style=" display: none; float: left;">
                        <i class="icon-ok bigger-100"></i>
                        Save
                    </button> -->

                    <button class="btn btn-small btn-danger pull-left" data-dismiss="modal" style="float: left;">
                        <i class="icon-remove"></i>
                        Close
                    </button>
                </div>
            </form>
        </div>
        <div style="overflow-x: scroll;">
            <div class="row-fluid">
                <div class="span12">
                    <?php

                    $trowHead_f=0;
                    $trowHead_g=0;
                    $trowHead_i=0;
                    $trowHead_i_d=0;

                    $trow = $obj->Total_Count_By_Cond("_pay_roll_emp_setup","_br_id='$branchid'  AND _status='A'");
                    $trowHead_g = $obj->Total_Count_By_Cond("_pay_roll_head","_branch_id='$branchid' AND _pay_type='G' AND _status='A'");
                    $trowHead_i = $obj->Total_Count_By_Cond("_pay_roll_head","_branch_id='$branchid' AND _pay_type='I' AND _head_type='C' AND _status='A'");
                    $trowHead_i_d = $obj->Total_Count_By_Cond("_pay_roll_head","_branch_id='$branchid' AND _pay_type='I' AND _head_type='D' AND _status='A'");
                     $trow_tax = $obj->Total_Count_By_Cond("_payroll_tax_setup","_br_id='$branchid' AND _status='1' and _type=1");
                     $Stamp_tax = $obj->Total_Count_By_Cond("_payroll_tax_setup","_br_id='$branchid' AND _status='1' and _type=2");
                     $row= $obj->View_All_By_Cond("_pay_roll_late_absenc_setup","_br_id='$branchid'");
                     $sumofsalary= $obj->View_colmn_By_Cond("_pay_roll_master","SUM(_gross) sgross,SUM(_total_salary) stsalary,SUM(`_total_deduction`) stdeduct,SUM(`_net_payable`) snetpay,SUM(`_payable`) spay","_br_id='$branchid' AND _month='$month' AND _year='$year' GROUP BY _month");

                     $late_days=$row[0]["_late_days"];
                      $salary_reduce_days=$row[0]["_salary_reduce_days"];
                    if($fastival!="")
                    {

                        $trowHead_f = $obj->Total_Count_By_Cond("_pay_roll_head","_branch_id='$branchid' AND _pay_type='F' AND _head_type='C' AND _status='A' AND _id in ($fastival)");
                    }

                    if($trow>'0') {
                        ?>


                        <table id="sample-table-1" class="table table-striped table-bordered table-hover table-responsive">
                        <thead>

                        <tr>
                            <th class="center" rowspan="2">SL</th>
                            <th class="center" colspan="3">Employee info</th>
                            <?php
                            foreach($obj->Head_amount("pd._br_id='$branchid' AND pd._year='$year' AND pd._month='$month'  and pd._type IN ( 'B', 'G')  AND pd._txrn_type='C' GROUP BY pd._head_id ORDER BY FIELD(pd._type, 'B', 'G'),pd._head_id") AS $v21){
                                ?>
                                <th class="center" rowspan="2"><?php if($v21['_head_id']=='0'){echo 'Basic';}else{echo $v21['_head_name']; } ?></th>
                            <?php } ?>
                            <th class="center" rowspan="2">Gross</th>
                        <?php
                        foreach($obj->Head_amount("pd._br_id='$branchid' AND pd._year='$year' AND pd._month='$month' and pd._type IN ('I', 'F')   AND pd._txrn_type='C' GROUP BY pd._head_id ORDER BY FIELD(pd._type, 'I', 'F'),pd._head_id") AS $v21){
                        ?>
                        <th class="center" rowspan="2"><?php if($v21['_head_id']=='0'){echo 'Basic';}else{echo $v21['_head_name']; } ?></th>
                    <?php } ?>
<!--                            <th class="center" rowspan="2">Total Salary</th>-->
                            <th  colspan="5" class="center">Attendance</th>

                                <th class="center" colspan="<?php echo $trowHead_i_d+2; ?>">Deductions</th>

                            <th class="center" rowspan="2">Net Salary</th>
                            <?php
                            if ($trow_tax != 0) {
                                ?>
                                <th class="center" rowspan="2">Tax</th>
                                <?php
                            }?>
                            <?php
                            if ($Stamp_tax != 0) {
                                ?>
                                <th class="center" rowspan="2">Stamp</th>
                                <?php
                            }?>
                            <th class="center" rowspan="2">Payable Salary</th>
                            <th class="center" rowspan="2">Action</th>

                        </tr>
                        <tr>
                        <th class="center">Emp ID</th>
                        <th class="center">Emp Name</th>
                        <th class="center">Designation</th>



                        <th class="center">Present</th>
                        <th class="center">Absent</th>
                        <th class="center">Late</th>
                        <th class="center">Leave</th>
                        <th class="center">Holiday</th>
                        <th class="center">Absent Deduction</th>


                            <?php
                            if ($trowHead_i_d != 0) {
                                foreach ($obj->View_All_By_Cond("_pay_roll_head", "_branch_id='$branchid' AND _pay_type='I' AND _head_type='D' AND _status='A'") AS $v21) {
                                    ?>
                                    <th class="center"><?php echo $v21['_name']; ?></th>
                                <?php }
                            }?>

                            <th class="center">Total</th>
                        </tr>
                            </thead>

                            <tfoot style="background-color: #dae0f2;">
                            <tr>
                                <th colspan="<?php echo $trowHead_g_n= $trowHead_g+5; ?>" ><span class="grandSlaray">Grand Total</span></th><th ><span class="grandSlaray"><?php echo $sumofsalary[0]["sgross"]; ?></span></th>
                                <?php if($trowHead_i!=0)
                                {
                                    ?>
                                    <th colspan="<?php echo $trowHead_i;?>">&nbsp;</th>
                                <?php
                                }?>

                                
                                <th colspan="<?php echo $trowHead_i_d_n= $trowHead_i_d+6;?>">&nbsp;</th><th><span class="grandSlaray"><?php echo $sumofsalary[0]["stdeduct"]; ?></span></th>
                                <th><span class="grandSlaray"><?php echo $sumofsalary[0]["snetpay"]; ?></span></th>
                                <?php if($trow_tax+$Stamp_tax!=0)
                                {
                                    ?>
                                    <th colspan="<?php echo $trow_tax+$Stamp_tax;?>">&nbsp;</th>
                                    <?php
                                }?>
                                <th><span class="grandSlaray"><?php echo $sumofsalary[0]["spay"]; ?></span></th>
                                <th>&nbsp;</th>
                            </tr>
                            </tfoot>

                            <tbody>

                            <?php
                            $month_day = cal_days_in_month(CAL_GREGORIAN,$month,$year);

                            $i=0;
                            foreach($obj->Emp_Payroll("pr._br_id='$branchid' AND pr._status='A'") AS $v1){
                                $i++;
                                // ===================================
                            foreach ($obj->View_All_By_Cond("_pay_roll_master", "_month='$month' AND _year='$year' AND _br_id='$branchid' AND _emp_id='".$v1['_emp_id']."'") AS $v21) {
                                $emp_gross=$v21["_gross"];
                                $emp_total_salary=$v21["_total_salary"];
                                $emp_absent_deduction=$v21["_absent_deduction"];
                                $emp_total_deduction=$v21["_total_deduction"];
                                $emp_net_payable=$v21["_net_payable"];
                                $emp_payable=$v21["_payable"];

                            }

                                ?>
                                <tr>
                                    <td class="center"><?php echo $i; ?></td>
                                    <td><?php echo $v1['_uniq_id']; ?></td>
                                    <td><?php echo $v1['_full_name']; ?></td>
                                    <td><?php echo $v1['_designation']; ?></td>

                                    <?php
                                    foreach($obj->Head_amount("pd._br_id='$branchid' AND pd._emp_id='".$v1['_emp_id']."' AND pd._year='$year' AND pd._month='$month'  AND pd._txrn_type='C' and  pd._type in ('B', 'G') ORDER BY FIELD(pd._type, 'B', 'G', 'I', 'F'),pd._head_id") AS $v2){
                                        ?>
                                        <td><?php echo ROUND($v2['_amount']); ?></td>
                                    <?php } ?>
                                    <td><?php echo $emp_gross; ?></td>
                                    <?php
                                    foreach($obj->Head_amount("pd._br_id='$branchid' AND pd._emp_id='".$v1['_emp_id']."' AND pd._year='$year' AND pd._month='$month'  AND pd._txrn_type='C' and  pd._type in ('I', 'F') ORDER BY FIELD(pd._type, 'B', 'G', 'I', 'F'),pd._head_id") AS $v2){
                                        ?>
                                        <td><?php echo ROUND($v2['_amount']); ?></td>
                                    <?php } ?>
<!--                                    <td>--><?php //echo $emp_total_salary; ?><!--</td>-->



                                    <?php $atd = $obj->Atd_Calculate("ma.br_id='$branchid' AND  ma.emp_id='".$v1['_emp_id']."' AND ma.month='$month' AND ma.year='$year'"); ?>
                                    <td><?php echo $atd['_present']; ?></td>
                                    <td><?php echo $atd['_absent']; ?></td>
                                    <td><?php echo $atd['_late']; ?></td>
                                    <td><?php echo $atd['_paid_leave'] ?></td>
                                    <td><?php echo $TotalHoliday; ?></td>


                                    <td>
                                        <?php
                                        echo $emp_absent_deduction;
                                        ?>
                                    </td>

                                    <?php
                                    foreach($obj->Head_amount("pd._br_id='$branchid' AND pd._emp_id='".$v1['_emp_id']."' AND pd._year='$year' AND pd._month='$month'   AND pd._txrn_type='D' AND pd._head_id!='0' ORDER BY FIELD(pd._type, 'B', 'G', 'I', 'F'),pd._head_id") AS $v3){
                                        ?>
                                        <td><?php echo $v3['_amount']; ?></td>
                                    <?php } ?>



                                    <td><?php echo $emp_total_deduction; ?></td>
                                    <td><?php  echo $emp_net_payable;
                                    ?></td>



                                        <?php
                                        if($trow_tax>0)
                                        {
                                            $tx = $obj->Head_amount("pd._br_id='$branchid' AND pd._emp_id='".$v1['_emp_id']."' AND pd._year='$year' AND pd._month='$month'   AND pd._txrn_type='D' AND pd._type='T'","Tax");
                                            $tax = ROUND($tx['_amount']);
                                            echo "<td>$tax</td>";
                                        }

                                        ?>



                                        <?php
                                        if($Stamp_tax>0)
                                        {
                                            $st = $obj->Head_amount("pd._br_id='$branchid' AND pd._emp_id='".$v1['_emp_id']."' AND pd._year='$year' AND pd._month='$month'   AND pd._txrn_type='D' AND pd._type='S'","Stamp");
                                            $stamp = ROUND($st['_amount']);
                                            echo "<td>$stamp</td>";
                                        }

                                        ?>

                                    <td><?php echo $emp_payable; ?></td>
                                    <td><i class="icon-edit bigger-170" style="cursor:pointer; <?php if($pstatus=="A"){ echo "pointer-events:none; color:lightgray";}?>" href="#modal-table" data-toggle="modal"  onclick="Payroll_show_edit_view('<?php echo $v1['_emp_id'];?>','<?php echo $year;?>','<?php echo $month;?>','<?php echo $v1['_full_name']; ?>')"></i></td>

                                </tr>
                            <?php }

                            ?>

                            </tbody>
                        </table>





                        <script>




                            function printFN(sheet_type){
                               // alert('Hello');
                                var br_id = '<?php echo $branchid; ?>';
                                var month =  '<?php echo $month; ?>';
                                var year = '<?php echo $year; ?>';
                                var td = '<?php echo $TotalHoliday; ?>';

                                var datastr="br_id="+br_id+"&month="+month+"&year="+year+"&sheet_type="+sheet_type+"&td="+td;
//                                $.ajax({
//                                    type:"post",
//                                    url:"module/pay_roll/report/payroll_sheet_report.php",
//                                    data:datastr ,
//                                    success:function(result){
//                                       // alert(result);
//                                        window.open('module/pay_roll/report/payroll_sheet_report.php?'+datastr);
//                                    }
//                                });
                               // alert('module/pay_roll/report/payroll_sheet_report.php?'+datastr);
                                window.open('module/pay_roll/report/payroll_sheet_report.php?'+datastr);
                            }
                        </script>
                        <?php

                    }
                    else{echo '<span style="color: red;">No Data Available in This Month</span>';}
                    ?>
                </div><!--/span-->
            </div><!--/row-->
        </div>
    </div>
    <script>
        function Payroll_show_edit_view(id,year,month,fullname) {
            var datastr = "function=edit_employee_salary&id="+id+"&month="+month+"&year="+year+"&fullname="+fullname;
            $("#model_table_value").load("module/pay_roll/show_payroll_result.php",datastr);
           // alert("value "+id+year+month);
        }
        </script>
<?php
}

if(isset($_REQUEST["function"]) && $_REQUEST["function"]=="viewDaysResult")
{
    $trowHead_f = $obj->Total_Count_By_Cond("_pay_roll_details","_br_id='$branchid' AND _month='$month' AND _year='$year' AND _status='A'");

if($trowHead_f>0)
{

    $pstatus="<span style='color: blue; font-weight: bold'>APPROVED</span>&nbsp;<span id='printView'>&nbsp;</span>";
}
else{
    $trowHead_f = $obj->Total_Count_By_Cond("_pay_roll_details","_br_id='$branchid' AND _month='$month' AND _year='$year' AND _status='P'");
    if($trowHead_f>0)
    {
        $pstatus="<span style='color: darkblue;font-weight: bold'>Waiting for approval</span>&nbsp;<span id='printView'>&nbsp;</span>";
    }
    else{
        $pstatus="<span style='color: green;font-weight: bold'>NEW</span>&nbsp;<span id='printView'>&nbsp;</span>";
    }


}
    if($month!="" && $year!="")
    {
        $Days=Array();
        foreach ($obj->View_All_By_Cond("_payroll_weekly_holiday"," _status='0' and _br_id='$branchid'") AS $v21) {
            $Days[]=$v21["_days"];
        }

        $month_day = cal_days_in_month(CAL_GREGORIAN,$month,$year);
        $date_1  = strtotime("$year-$month-01");
        $date_2 = strtotime("$year-$month-$month_day");
        //$days = array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday');
        $count = 0;
        $dcount = 0;
        $daycount = 0;
        foreach ($Days as $nday)
        {
            while ($date_1 < $date_2) {
                if(date('l', $date_1) == $Days[$dcount]);
                {
                    $count++;
                }
                $date_1 += 7 * 24 * 3600;
            }
            $daycount=$daycount+$count;

            $dcount++;
        }
$workingDays=$month_day-$daycount-$govtHoliday;
        $_SESSION["workingDays"]=$workingDays;
        //echo "<pre>"; print_r($_SESSION);
        if($govtHoliday!="")
        {
            $govtVal="Total Govt. holiday: <span class='label label-info arrowed-in arrowed-in-right'>$govtHoliday</span>";
        }
        else{
            $govtVal="Total Govt. holiday: <span class='label label-info arrowed-in arrowed-in-right'>0</span>";
        }
        echo"
<table width='100%' class='table alert alert-success'>
<tr>
<td>
Total day: <span class='label label-success arrowed-in arrowed-in-right' style='font-weight: bold;font-size: 14px'>$month_day</span> || &nbsp; 
$govtVal || &nbsp; 
Weekly holiday: <span class='label label-warning arrowed-in arrowed-in-right'>$daycount</span> || &nbsp; 
Total working day: <span class='label label-inverse arrowed' style='font-weight: bold;font-size: 14px'>$workingDays</span>
</td>
<td  style='padding-right: 5px;text-align: right'>
$pstatus
</td>
</tr>
</table>
";
    }
    else{
        echo "<div class='alert alert-block alert-success'><button class='close' type='button' data-dismiss='alert'>
<i class='icon-remove'></i>
</button>Please select month or year..</div>";
    }





}
if(isset($_REQUEST["function"]) && $_REQUEST["function"]=="edit_employee_salary")
{
    //echo $_REQUEST["id"]." ".$_REQUEST["month"]." ".$_REQUEST["year"];

    echo "<div class='profile-user-info profile-user-info-striped'>
            <div class='profile-info-row'>
            <div class='profile-info-name'> Employee Name </div>
            <div class='profile-info-value' >
                <span id='username' class='editable editable-click'>".$_REQUEST["fullname"]."</span>
            </div>
        </div>
        </div>";
    echo "<table width='100%'>
<tr>
<td style='width: 60%' valign='top'>";
    echo "<div class='profile-user-info profile-user-info-striped'>";
    $total_plus=0;
    $total_minus=0;

    $row_master=$obj->View_colmn_By_Cond("`_pay_roll_master`","*","_br_id='$branchid' AND _year='".$_REQUEST["year"]."' AND _month='".$_REQUEST["month"]."' AND _emp_id='".$_REQUEST["id"]."'");

    foreach ($obj->View_colmn_By_Cond("`_pay_roll_head` a JOIN `_pay_roll_details` b ON a.`_id`=b.`_head_id` AND a.`_branch_id`=b.`_br_id`","a._name HeadName,b.`_id` dtlsID,b.`_amount`,b.`_txrn_type`","a._pay_type IN('I','F') AND a._status='A'  AND b.`_emp_id`='".$_REQUEST["id"]."' AND b.`_month`='".$_REQUEST["month"]."' AND b.`_year`='".$_REQUEST["year"]."' and b.`_br_id`='$branchid'") as $val)
    {
        //print_r($val);
        $SHOWTYPE="<span style='color:darkred; font-weight: bold;'>(+)</span>";
        if($val["_txrn_type"]=="C")
        {
            $SHOWTYPE="<span style='color:darkred; font-weight: bold;'>(+)</span>";
            $total_plus=$total_plus+$val["_amount"];
        }
        if($val["_txrn_type"]=="D")
        {
            $SHOWTYPE="<span style='color:darkgreen; font-weight: bold;'>(-)</span>";
            $total_minus=$total_minus+$val["_amount"];
        }
        echo "<div class='profile-info-row'>
            <div class='profile-info-name'> ".$val["HeadName"]." </div>
            <div class='profile-info-value' >
                <span id='username' class='editable editable-click'><input type='text' id='amt_".$val["dtlsID"]."' value='".trim($val["_amount"])."' style='margin:0px;' onblur='changeSalaryEditInfo()'  /><input type='hidden' id='payType_".$val["dtlsID"]."' value='".$val["_txrn_type"]."' style='margin:0px;'  /> $SHOWTYPE</span>
            </div>
        </div>";
       $id[] =$val["dtlsID"];
    }

echo "<input type='hidden' value='".implode($id,",")."' id='idlist'>";
echo "<input type='hidden' value='".$row_master[0]["_gross"]."' id='grossSalary'>";
echo "<input type='hidden' value='".($row_master[0]["_total_deduction"]-$total_minus)."' id='NetDeduction'>";
echo "<input type='hidden' value='".($row_master[0]["_net_payable"]-$row_master[0]["_payable"])."' id='NetpayableExtra'>";
echo "<input type='hidden' value='".$row_master[0]["_id"]."' id='payrollMasteid'>";


    echo "</td>

<td style='width: 40%' valign='top'>";
    echo "<div class='profile-user-info profile-user-info-striped'>";
    echo "<div id='changeResult'>";
    echo "<div class='profile-info-row'>
            <div class='profile-info-name'> Total Salary </div>
            <div class='profile-info-value' >
                <span id='username' class='editable editable-click'>".$row_master[0]["_total_salary"]."</span>
            </div>
        </div>";
    echo "<div class='profile-info-row'>
            <div class='profile-info-name'> Total Deduction </div>
            <div class='profile-info-value' >
                <span id='username' class='editable editable-click'>".$row_master[0]["_total_deduction"]."</span>
            </div>
        </div>";
    echo "<div class='profile-info-row'>
            <div class='profile-info-name'> Net Payable Salary</div>
            <div class='profile-info-value' >
                <span id='username' class='editable editable-click'>".$row_master[0]["_net_payable"]."</span>
            </div>
        </div>";
    echo "<div class='profile-info-row'>
            <div class='profile-info-name'> Payable Salary </div>
            <div class='profile-info-value' >
                <span id='username' class='editable editable-click'>".$row_master[0]["_payable"]."</span>
            </div>
        </div>";
    echo "</div>";
    echo "</div>";
    echo "</td>
</tr>
</table>";
?>
    <script>
        function changeSalaryEditInfo()
        {
            var idarray=$('#idlist').val().split(",");
            var grossSalary=$('#grossSalary').val();
            var NetDeduction=$('#NetDeduction').val();
            var NetpayableExtra=$('#NetpayableExtra').val();
            var totalPlus=0;
            var totalMinus=0;
            var amount=0;
            var tranType="";
            for (var i = 0, len = idarray.length; i < len; i++) {

                amount=parseInt($('#amt_'+idarray[i]).val().trim());
                tranType=($('#payType_'+idarray[i]).val().trim());
                if(tranType=="C"){
                    totalPlus=totalPlus+amount;
                }
                else if(tranType=="D"){
                    totalMinus=totalMinus+amount;
                }
            }
            var str ="function=changeSalaryEditView&totalPlus="+totalPlus+"&totalMinus="+totalMinus+"&grossSalary="+grossSalary+"&NetDeduction="+NetDeduction+"&NetpayableExtra="+NetpayableExtra;

            $.ajax({
                type:"post",
                url:"module/pay_roll/show_payroll_result.php",data:str ,success:function(st){
                    $("#changeResult").html(st);
                }
            });
        }
        $( "#pay_update" ).click(function() {
            var idarray=$('#idlist').val().split(",");
            var sidarray=$('#idlist').val();
            var grossSalary=$('#grossSalary').val();
            var NetDeduction=$('#NetDeduction').val();
            var NetpayableExtra=$('#NetpayableExtra').val();
            var payrollMasteid=$('#payrollMasteid').val();
            var totalPlus=0;
            var totalMinus=0;
            var amountArray="";
            var transArray="";
            for (var i = 0, len = idarray.length; i < len; i++) {

                amount=parseInt($('#amt_'+idarray[i]).val().trim());
                amountArray=amountArray+amount+",";

                tranType=($('#payType_'+idarray[i]).val().trim());
                transArray=transArray+tranType+",";

                if(tranType=="C"){
                    totalPlus=totalPlus+amount;
                }
                else if(tranType=="D"){
                    totalMinus=totalMinus+amount;
                }
            }
            amountArray=amountArray.slice(0,-1)
            transArray=transArray.slice(0,-1)
            var str ="function=UpdateEmployeePayrollSalary&sidarray="+sidarray+"&amountArray="+amountArray+"&transArray="+transArray+"&totalPlus="+totalPlus+"&totalMinus="+totalMinus+"&grossSalary="+grossSalary+"&NetDeduction="+NetDeduction+"&NetpayableExtra="+NetpayableExtra+"&payrollMasteid="+payrollMasteid;

            $.ajax({
                type:"post",
                url:"module/pay_roll/show_payroll_result.php",data:str ,success:function(st){
                    alert(st);
                }
            });
        });
        </script>
<?php

}
if(isset($_REQUEST["function"]) && $_REQUEST["function"]=="get_salary_count")
{
    extract($_REQUEST);
   echo $trowHead_f = $obj->Total_Count_By_Cond("_pay_roll_details","_br_id='$branchid' AND _month='$month' AND _year='$year' AND _status='$status'");

}
if(isset($_REQUEST["function"]) && $_REQUEST["function"]=="get_holiday_Conut")
{
    extract($_REQUEST);
    //SELECT _holiday FROM `hr_emp_monthly_attandce` WHERE br_id='4' AND `month`='03' AND `year`='2017' LIMIT 1
    $emp_holiday_q=$obj->View_colmn_By_Cond("hr_emp_monthly_attandce","_holiday","br_id='$branchid' AND `month`='$month' AND `year`='$year' LIMIT 1") ;
    echo $emp_holiday=$emp_holiday_q[0]["_holiday"];

}
if(isset($_REQUEST["function"]) && $_REQUEST["function"]=="changeSalaryEditView")
{
    extract($_REQUEST);

$cal_sal_total=$grossSalary+$totalPlus;

$totalDeduction=$NetDeduction+$totalMinus;
$netPayable=$cal_sal_total-$totalDeduction;
$Payable=$netPayable-$NetpayableExtra;
    echo "<div class='profile-info-row'>
            <div class='profile-info-name'> Total Salary </div>
            <div class='profile-info-value' >
                <span id='username' class='editable editable-click'>".$cal_sal_total."</span>
            </div>
        </div>";
    echo "<div class='profile-info-row'>
            <div class='profile-info-name'> Total Deduction </div>
            <div class='profile-info-value' >
                <span id='username' class='editable editable-click'>".$totalDeduction."</span>
            </div>
        </div>";
    echo "<div class='profile-info-row'>
            <div class='profile-info-name'> Net Payable Salary</div>
            <div class='profile-info-value' >
                <span id='username' class='editable editable-click'>".$netPayable."</span>
            </div>
        </div>";
    echo "<div class='profile-info-row'>
            <div class='profile-info-name'> Payable Salary </div>
            <div class='profile-info-value' >
                <span id='username' class='editable editable-click'>".$Payable."</span>
            </div>
        </div>";


}
if(isset($_REQUEST["function"]) && $_REQUEST["function"]=="UpdateEmployeePayrollSalary")
{
    extract($_REQUEST);
//    [function] => UpdateEmployeePayrollSalary
//[sidarray] => 5390,5391,5392,5393
//    [amountArray] => 500,2000,1000,10000
//    [transArray] => C,C,D,C
//[totalPlus] => 12500
//    [totalMinus] => 1000
//    [grossSalary] => 41400
//    [NetDeduction] => 13173
//    [NetpayableExtra] => 12
    $sidarray_n=explode(",",$sidarray);
    $amountArray_n=explode(",",$amountArray);
    $transArray_n=explode(",",$transArray);
    for($i=0;$i<count($sidarray_n);$i++)
    {

        $sql_array=array('_amount'=>$amountArray_n[$i]);
        $obj->Update_Data("_pay_roll_details",$sql_array,"_id='".$sidarray_n[$i]."' ");
    }
    $cal_sal_total=$grossSalary+$totalPlus;
    $totalDeduction=$NetDeduction+$totalMinus;
    $netPayable=$cal_sal_total-$totalDeduction;
    $Payable=$netPayable-$NetpayableExtra;
    //``_total_salary``_total_deduction``_net_payable``_payable``
    $sql_array=array('_total_salary'=>$cal_sal_total,'_total_deduction'=>$totalDeduction,'_net_payable'=>$netPayable,'_payable'=>$Payable);
    $obj->Update_Data("_pay_roll_master",$sql_array,"_id='".$payrollMasteid."' ");
    echo "Update Successful";


}
if(isset($_REQUEST["function"]) && $_REQUEST["function"]=="updateDalilyAttandanceByDate")
{
    extract($_REQUEST);
    $explodeDate=explode(",",$dateList);
    $LOGIN_USERID=$_SESSION["LOGIN_USERID"];

    $month = trim(date("m",strtotime($explodeDate[0])));
    $Year = trim(date("Y",strtotime($explodeDate[0])));
    $CurrenTime = date('H:i:s');
    $obj->Delete_Data("hr_emp_daily_attendance","br_id='$branchid' and month(entry_date)='$month' and YEAR(entry_date)='$Year' and atd_status='5'");
    foreach ($explodeDate as $updateDate) {
        $quaryDate2 = date("Y-m-d", strtotime($updateDate));
        $obj->Delete_Data("hr_emp_daily_attendance","br_id='$branchid' and DATE(entry_date)='$quaryDate2'");
    }

   //select * from `hr_emp_daily_attendance` where br_id='4' and month(entry_date)='01' and YEAR(entry_date)='2017' and atd_status='5'
   //select count(emp_id) cid from `hr_emp_daily_attendance` where br_id='4' and date(entry_date)='2017-01-01' and emp_id='13'
    //SELECT _id FROM _pf_emp_personal_info WHERE _status='A' AND _branch_id='4';
    foreach ($obj->View_colmn_By_Cond("_pf_emp_personal_info","_id","_status='A' AND _branch_id='$branchid'") as $val)
    {
        $_id= $val["_id"]." ";
        foreach ($explodeDate as $updateDate)
        {
             $quaryDate = date("Y-m-d", strtotime($updateDate));


             $quaryDateTIME="$quaryDate $CurrenTime";
            $sql_array=array(
                'emp_id'=>$_id,
                'br_id'=>$branchid,
                'late_time'=>'0',
                'atd_status'=>'5',
                '_in_time'=>'00:00:00',
                '_out_time'=>'00:00:00',
                '_atd_type'=>"Auto",
                'comment'=>"Holiday",
                'entry_by'=>$LOGIN_USERID,
                'entry_date'=>$quaryDateTIME,
                'last_update_by'=>$LOGIN_USERID,

            );
            $entry2=$obj->Insert_Data("hr_emp_daily_attendance",$sql_array);

        }


    }
        echo "<span style='color: green;font-weight: bold;background-color: #DFF0D8; padding: 5px;'>Update dalily attandance by date($dateList) is successful</span>";
}
if(isset($_REQUEST["function"]) && $_REQUEST["function"]=="RetakebyDate")
{
    extract($_REQUEST);
    $RetakeDates;
    $quaryDate = date("Y-m-d", strtotime($RetakeDates));
    $obj->Delete_Data("hr_emp_daily_attendance","br_id='$branchid' and date(entry_date)='$quaryDate'");

    $sql_array=array('STATUS'=>0);
    $obj->Update_Data("`_atd_device_log` a inner join _pf_emp_personal_info b on a.`CARD_NO`=b.`_id_card`",$sql_array,"date(CHECK_TIME)='$quaryDate'");

    ///////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////
    $today_date=$quaryDate;
    foreach ($obj->View_All_By_Cond("_atd_device_log","STATUS='0' AND DATE(CHECK_TIME)='$today_date' ORDER BY ID,FLAG") AS $v1) {

        $id = $v1['ID'];
        $cardno = $v1['CARD_NO'];
        $time = $v1['CHECK_TIME'];
        $input_time = $v1['CHECK_TIME'];

        $flag = $v1['FLAG'];
        $mechine_id = '1';
        $login_time = date("H:i:s", strtotime($time));
        $ck_date = date( 'Y-m-d', strtotime($time));
        //echo "2";

        if($ck_date==$today_date){

            // echo "3";
            // ============= Start Employee Attendance ===============
            $emp = $obj->Details_By_Cond("_pf_emp_personal_info","_id_card='$cardno'");
            //echo "</br>";
            //echo "_pf_emp_personal_info","_id_card='$cardno'";
            $emp_id = $emp['_id'];
            $br_id = $emp['_branch_id'];
            $emp_id = $emp['_id'];
            if($emp_id){

                $day = date("l");
                $daySts = $obj->Details_By_Cond("hr_emp_timing","br_id='$br_id' AND day='$day'");
                $chkdayst= $daySts['day_status'];
                $office_time = $daySts['in_time'];

                if($chkdayst==1) {
                    // echo "4";

                    foreach($obj->View_All_By_Cond("_pf_emp_personal_info","_branch_id='$br_id' AND _status='A'") as $value){

                        $emid = $value['_id'];
                        $form_data = array(
                            'emp_id'=>$emid,
                            'br_id'=>$br_id,
                            //'entry_date'=>date("Y:m:d h:i:s"),
                            'entry_date'=>date($input_time),
                            //'entry_date'=>"2017-02-15 07:30:00",

                            '_atd_type' => 'Automatic',
                            'atd_status'=>'0'

                        );

                        $obj->Insert_Data_By_Cond("hr_emp_daily_attendance", $form_data,"emp_id='$emid' AND br_id='$br_id' And date(entry_date)='$today_date'");
                    }




                    // =========== Attandance Status Change ===========
                    $atd_status = $obj->Details_By_Cond("hr_emp_daily_attendance","emp_id='$emp_id' And date(entry_date)='$today_date'");
                    // echo "6";
                    if($atd_status['atd_status']=='0')
                    {
                        // echo "5";

                        $roster_chk=$obj->Details_By_Cond("hr_roaster_setup a, _pf_emp_personal_info b"," a.id=b._roaster_id and  b._id='$emp_id' ");

                        $office_time=$roster_chk['start_time'];

                        // =============  a.id=b._roaster_id AND b._id=3
                        $checkTime = date("H:i:s", strtotime($office_time));
                        $loginTime = date("H:i:s", strtotime($time));

                        $checkTime_1 = date("His", strtotime($office_time));
                        $loginTime_1 = date("His", strtotime($time));

                        $checkTime = strtotime($checkTime);
                        $loginTime = strtotime($loginTime);
                        $diff = $checkTime-$loginTime;

                        if($checkTime_1<$loginTime_1){
                            $l_time = (int)(abs($diff)/60);
                            $atn_status=2;
                        }
                        else{
                            $l_time = '0';
                            $atn_status=1;
                        }
                        // =============

                        $in_data=array(
                            'late_time'=>$l_time,
                            'atd_status'=>$atn_status,
                            '_in_time'=>$login_time
                        );
                        $in = $obj->Update_Data("hr_emp_daily_attendance", $in_data, "id='".$atd_status['id']."'");
                        if($in){
                            $att_data=array(
                                'STATUS'=>'1'
                            );
                            $a = $obj->Update_Data("_atd_device_log",$att_data,"ID='$id'");
                        }
                    }
                    else if($atd_status['atd_status']=='1'){
                        // echo "6";
                        $out_data=array(
                            '_out_time'=>$login_time
                        );
                        $out = $obj->Update_Data("hr_emp_daily_attendance", $out_data, "id='".$atd_status['id']."'");
                        if($out){
                            $att_data=array(
                                'STATUS'=>'1'
                            );
                            $a = $obj->Update_Data("_atd_device_log",$att_data,"ID='$id'");
                        }
                    }
                    else{
                        //echo "7";
                        $att_data=array(
                            'STATUS'=>'4' //Inactive Employee
                        );
                        $a = $obj->Update_Data("_atd_device_log",$att_data,"ID='$id'");
                        echo 'Sorry! This Employee is Inactive';
                    }
                }
                else{
                    $att_data=array(
                        'STATUS'=>'5' //Invalid Date
                    );
                    $a = $obj->Update_Data("_atd_device_log",$att_data,"ID='$id'");
                }
            }




        }

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

    echo "<span style='color: green;font-weight: bold;background-color: #DFF0D8; padding: 5px;'>Retake employee attandance by date($RetakeDates) is successful</span>";
}