<?php

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

ini_set('display_errors', 1);
error_reporting(E_ERROR);

$maindb = "actran";
$formname = "Single JV Tally Report";
$file = "jvsingle.php";
$zroot = $_SESSION["zdir"];
$admin = $_SESSION["admin_" . $dbname];
$zdb = $_SESSION["zdbyear_" . $dbname];
$myyear = $_SESSION[$myyear];
mysqli_select_db($conn, $zdb);
// browse($zdb);
// die();
$scope = $_POST["scope"];
$mfrmdate = trim($_POST["fdate"]);
$mtodate = trim($_POST["tdate"]);

    $scopecond = "('JVS')";
    $sourcecond = "AND source = 'JVS'";
    $typename = "JV SINGLE";
    $mmaindb = "jventry";

if (empty($_POST["fdate"])) {
    browse("From Date Cannot Be Empty");
    header("refresh:1; discbook.php");
}
if (empty($_POST["tdate"])) {
    browse("To Date Cannot Be Empty");
    header("refresh:1; discbook.php");
}
$mfdt = date("d-m-Y", strtotime($mfrmdate));
$mtdt = date("d-m-Y", strtotime($mtodate));

$getpmain = mysqli_query($conn, "SELECT *, DATE_FORMAT(`date`, '%d-%m-%Y') as mydt FROM `$maindb` WHERE grpcode != '001' AND grpcode != '002' 
     $sourcecond AND `date` BETWEEN '$mfrmdate' AND '$mtodate' ORDER BY `vouchno` ASC") or die(mysqli_error($conn));

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

    include("includes/head_excel_rep.php");

    $contents .= "Sr.,Voucher Date,Voucher Type,Voucher No,Ledger,Amount,Dr/Cr,Narration,Bill No,Bill Amount\n";

    $ctr = 0;
    $totcramt = 0;
    $totdramt = 0;

    $lastVouchNo = '';

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

        $ctr++;

        $dramt = 0;
        $cramt = 0;
        $roundoffcrdr = '';

        // 👉 Party Name
        $getsale = mysqli_query($conn, "SELECT name FROM accmast WHERE accode='{$pmain['accode']}'");
        $sale = mysqli_fetch_array($getsale);

        // 👉 Narration
        $getnarr = mysqli_query($conn, "SELECT * FROM `$mmaindb` WHERE vouchno='{$pmain['vouchno']}'");
        $fetnarr = mysqli_fetch_array($getnarr);


        // 👉 Dr / Cr
        if ($pmain['amount'] > 0) {
            $cramt = abs($pmain['amount']);
            $roundoffcrdr = "CR";
            $type = "CR";
        } else {
            $dramt = abs($pmain['amount']);
            $roundoffcrdr = "DR";
            $type = "DR";
        }

        // 👉 Fetch Bill Details
        $getbildet = mysqli_query($conn, "SELECT billno, SUM(setoff) as setoff FROM billsett WHERE bnkvouch = '{$pmain['vouchno']}' AND source ='{$pmain['source']}' GROUP BY billno");

        // =========================
        // ✅ IF BILL EXISTS
        // =========================
        if (mysqli_num_rows($getbildet) > 0) {

            $firstRow = true;

            while ($fetbildet = mysqli_fetch_assoc($getbildet)) {
                $newvouch = $pmain['vouchno'];
                if ($prevvouch == $newvouch) {
                    $vouchtype = '';
                    $vouchno = '';
                    $remfld = "";
                    $billno = "";
                    $setoff = "";
                    $mydt = '';
                } else {
                    $vouchno = $newvouch;
                    $mydt = $pmain['mydt'];
                    $remfld = $fetnarr['narr1'] . " " . $fetnarr['narr2'];
                    $prevvouch = $newvouch;
                    $vouchtype = 'Journal';
                    $billno = $fetbildet['billno'];
                    $setoff = $fetbildet['setoff'];
                    $newline = $contents .= "\n";
                }

                if ($firstRow) {

                    // ✅ Print voucher details ONCE
                    $contents .= "{$ctr},";
                    $contents .= "{$mydt},";
                    $contents .= "{$typename},";
                    $contents .= "{$pmain['vouchno']},";
                    $contents .= "{$sale['name']},";
                    $contents .= "{$pmain['amount']},";
                    $contents .= "{$roundoffcrdr},";
                    $contents .= "{$remfld},";

                    $firstRow = false;
                } else {
                    // ✅ Empty columns for next bill rows
                    $contents .= ",,,,,,,,";
                }
                // ✅ Bill details
                $contents .= "{$billno},";
                $contents .= "{$setoff}\n";

                $lastVouchNo = $pmain['vouchno'];
            }
        } else {

            // =========================
            // ❌ NO BILL CASE
            // =========================

            $newvouch = $pmain['vouchno'];
                if ($prevvouch == $newvouch) {
                    $vouchtype = '';
                    $vouchno = '';
                    $remfld = "";
                    $billno = "";
                    $setoff = "";
                    $mydt = '';
                } else {
                    $vouchno = $newvouch;
                    $mydt = $pmain['mydt'];
                    $remfld = $fetnarr['narr1'] . " " . $fetnarr['narr2'];
                    $prevvouch = $newvouch;
                    $vouchtype = 'Journal';
                    $billno = $fetbildet['billno'];
                    $setoff = $fetbildet['setoff'];
                    $newline = $contents .= "\n";
                }

            if ($lastVouchNo != '' && $lastVouchNo != $pmain['vouchno']) {
                $contents .= "\n";
            }

            $contents .= "{$ctr},";
            $contents .= "{$mydt},";
            $contents .= "{$typename},";
            $contents .= "{$vouchno},";
            $contents .= "{$sale['name']},";
            $contents .= "{$pmain['amount']},";
            $contents .= "{$roundoffcrdr},";
            $contents .= "{$remfld},";
            $contents .= "-,0\n";

            $lastVouchNo = $pmain['vouchno'];
        }

        $totdramt += $dramt;
        $totcramt += $cramt;
    }

    // =========================
    // ✅ GRAND TOTAL
    // =========================
    $contents .= ",,,,Grand Total,{$totdramt},{$totcramt}\n";

    $contents = strip_tags($contents);

    $filename = "{$formname}_Tally_Format_" . date('d-m-Y') . ".csv";

    header("Content-Type: text/csv");
    header("Content-Disposition: attachment; filename=\"$filename\"");
    echo $contents;
    exit;
}
