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

function getShortMonthName($monthNo)
{
    $dateObj = DateTime::createFromFormat('!m', $monthNo);
    return $dateObj ? $dateObj->format('F') : false;
}


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

$file = 'monthcomprep_fr.php';

$expense = $_POST["expense"];

$expcond = '';

if (!empty($expense)) {
    $expcond = "AND `expense`= '$expense'";
}


$monthcode = $_POST["month"];  // Just the month number (e.g., 12)
$year = $_POST["year"];        // Year (e.g., 2025)
$mmon = $monthcode;

// Create DateTime object from year and month
$date = DateTime::createFromFormat('Y-n', "$year-$monthcode");

if ($mmon == 1) {
    $pmon = 12 ;
} else {
    $pmon = $mmon - 1 ;
}

if ($mmon == 12) {
    $nmon = 1 ;
} else {
    $nmon = $mmon + 1 ;
}

// Format: YYYY-M
//$pmon = (clone $date)->modify('-1 month')->format('n');
//$mmon = $date->format('n');
//$nmon = (clone $date)->modify('+1 month')->format('n');

// Format: Full Month Name with Year (e.g., "December 2025")
//$prevmonthname = (clone $date)->modify('-1 month')->format('F Y');
//$monthname = $date->format('F Y');
//$nextmonthname = (clone $date)->modify('+1 month')->format('F Y');


$formname = 'Monthly Comparison For ' . $monthname;

// Example Output
// echo "Previous: $prevmonth ($prevmonthname)<br>";
// echo "Current: $month ($monthname)<br>";
// echo "Next: $nextmonth ($nextmonthname)<br>";


$getquery = mysqli_query($conn, "SELECT accode,name FROM `accmast` WHERE `grpcode` = '012'
                                        AND accode IN (SELECT expense FROM expentry ) $expcond ORDER BY name ") or die(mysqli_error($conn));
$numrecs = mysqli_num_rows($getquery);

if (isset($_POST["view"]) || ($_GET["view"])) {

    include("includes/linkshead.php");
    ?>
    <style type="text/css">
        #tabital {
            font-style: italic;
        }

        #font1 {
            font-style: italic;
        }

        #boldfont {
            font-weight: bold;
        }
    </style>
    </head>

    <body>
        <div class="container-fluid">
            <div class="col-lg-8 pad">
                <?php
                include("includes/head_rep2.php");
                ?>
                <div class="row">
                    <table class="table table-condesed table-bordered">
                        <tr>
                            <td style="font-size: 15px;padding:5px" class="HDFont" colspan="2">
                                Total No. of Record :&nbsp;&nbsp;<b><?php echo $numrecs; ?></b>
                            </td>
                        </tr>
                    </table>

                    <table style="background: white;width: 100%"
                        class="table table-condensed table-striped table-hover table-bordered">
                        <thead class="mySearchTr">
                            <tr>
                                <th width="3%;">Sr</th>
                                <th width="22%;">Expense</th>
                                <th width="8%;" class="text-right"><?= getShortMonthName($pmon); ?></th>
                                <th width="7%;" class="text-right">Qty</th>
                                <th width="8%;" class="text-right" style="background-color: #f7f6c2;color:black">
                                    <?= getShortMonthName($mmon); ?>
                                </th>
                                <th width="7%;" class="text-right" style="background-color: #f7f6c2;color:black">Qty</th>
                                <th width="8%;" class="text-right"><?= getShortMonthName($nmon); ?></th>
                                <th width="7%;" class="text-right">Qty</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $tamt = [$pmon => 0, $mmon => 0, $nmon => 0];
                            $tqty = [$pmon => 0, $mmon => 0, $nmon => 0];
                            $pctr = 0;

                            while ($pmain = mysqli_fetch_array($getquery)) {

                                $expcode = $pmain['accode'];
                                $expname = $pmain['name'];

                                $moncode = [$pmon, $mmon, $nmon];
                                $showmonamt = [];
                                $showmonqty = [];

                                foreach ($moncode as $val) {

                                    $getexpdet = mysqli_query($conn, "SELECT sum(amount) as tamt, sum(qty) as tqty 
                                                                      FROM `expentry` WHERE `expense`='$expcode' AND MONTH(vouchdt) = '$val'  ") or die(mysqli_error($conn));
                                    $fetexpdet = mysqli_fetch_object($getexpdet);
                                    $showmonamt[$val] = $fetexpdet->tamt;
                                    $showmonqty[$val] = $fetexpdet->tqty;

                                    $tamt[$val] += $showmonamt[$val];
                                    $tqty[$val] += $showmonqty[$val];
                                }

                                $pctr++;
                                echo "<tr>";
                                echo "<td>$pctr</td>";
                                echo "<td>$expname</td>";
                                echo "<td class='text-right'>" . ($showmonamt[$pmon] ?? 0) . "</td>";
                                echo "<td class='text-right'>" . ($showmonqty[$pmon] ?? 0) . "</td>";
                                echo "<td class='text-right' style='background-color: #f7f6c2;'>" . ($showmonamt[$mmon] ?? 0) . "</td>";
                                echo "<td class='text-right' style='background-color: #f7f6c2;'>" . ($showmonqty[$mmon] ?? 0) . "</td>";
                                echo "<td class='text-right'>" . ($showmonamt[$nmon] ?? 0) . "</td>";
                                echo "<td class='text-right'>" . ($showmonqty[$nmon] ?? 0) . "</td>";
                                echo "</tr>";

                            }

                            echo "<tr style='background-color: #98F9F0'>";
                            echo "<td></td>";
                            echo "<td class='text-right' style='font-size:15px'><b>Total</b></td>";

                            echo "<td class='numeric text-right' style='font-size:15px'><b>" . number_format($tamt[$pmon] ?? 0, 2) . "</b></td>";
                            echo "<td class='numeric text-right' style='font-size:15px'><b>" . number_format($tqty[$pmon] ?? 0, 3) . "</b></td>";

                            echo "<td class='numeric text-right' style='background-color: #f7f6c2; font-size:15px'><b>" . number_format($tamt[$mmon] ?? 0, 2) . "</b></td>";
                            echo "<td class='numeric text-right' style='background-color: #f7f6c2; font-size:15px'><b>" . number_format($tqty[$mmon] ?? 0, 3) . "</b></td>";

                            echo "<td class='numeric text-right' style='font-size:15px'><b>" . number_format($tamt[$nmon] ?? 0, 2) . "</b></td>";
                            echo "<td class='numeric text-right' style='font-size:15px'><b>" . number_format($tqty[$nmon] ?? 0, 3) . "</b></td>";
                            echo "</tr>";

                            ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php
}

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

    $contents = strip_tags($contents);

    if ($_POST["dtype"] == 1 || $_POST["dtype"] == 3) {
        header("Content-Disposition: attachment;filename = $formname" . "_Summary" . date('d-m-Y') . ".csv");
        print $contents;
    } else {
        header("Content-Disposition: attachment;filename = $formname" . "_Detail" . date('d-m-Y') . ".csv");
        print $contents;
    }
}

?>