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

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

require '../vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;

$zdb = $_SESSION["zdbyear_" . $dbname];

mysqli_select_db($conn, $zdb);

mysqli_set_charset($conn, "utf8");

$reporttype = $_POST['reporttype'];
$isAllReport = ($reporttype == 1);

$fdate = $_POST['fdate'];
$tdate = $_POST['tdate'];

$frdt = date('d-m-Y', strtotime($fdate));
$todt = date('d-m-Y', strtotime($tdate));

$transporter = trim($_POST['transporter'] ?? '');
$party = trim($_POST['party'] ?? '');


/* =========================================================
   FILTER CONDITIONS
========================================================= */

$where = "";


/* =========================
   TRANSPORTER FILTER
========================= */

if ($transporter != '') {

    $transportArray = explode(',', $transporter);

    $finalTransport = [];

    foreach ($transportArray as $tr) {

        $tr = trim($tr);

        if ($tr != '') {
            $finalTransport[] = "'" . $tr . "'";
        }
    }

    if (count($finalTransport) > 0) {

        $transportIN = implode(",", $finalTransport);

        $where .= "
            AND a.transporter IN ($transportIN)
        ";
    }
} else {

    /* BLANK = ALL grpcode 010 */

    $where .= "
        AND a.grpcode='010'
    ";
}



/* =========================
   SINGLE KARIGAR FILTER
========================= */

if ($party != '') {

    $where .= "
        AND a.accode='$party'
    ";
}

/* =========================================================
   QUERY
========================================================= */
$qry = mysqli_query($conn, "

SELECT 
    a.accode,
    a.name karigar,
    a.transporter,

    t.name transportername,

     /* ================= STOCK ================= */

    IFNULL((
        SELECT SUM(amount)
        FROM stockent s
        WHERE s.party = a.accode
        AND s.vouchdt BETWEEN '$fdate' AND '$tdate'
    ),0) stocktotal,


    /* ================= BANK ================= */

    IFNULL((
        SELECT SUM(amount)
        FROM bankent b
        WHERE b.party = a.accode
        AND b.vouchdt BETWEEN '$fdate' AND '$tdate'
    ),0) banktotal,


    /* ================= ACCESSORIES ================= */

    IFNULL((
        SELECT SUM(rt.amount)

        FROM rawtran rt

        LEFT JOIN rawmain rm
        ON rm.vouchno = rt.vouchno

        WHERE rm.party = a.accode

        AND rt.vouchdt BETWEEN '$fdate' AND '$tdate'

    ),0) acstotal,


    /* ================= BANK PAYMENT ================= */

    IFNULL((
        SELECT SUM(amount)
        FROM bankent s
        WHERE s.party = a.accode
        AND s.vouchdt BETWEEN '$fdate' AND '$tdate' AND s.group = '1'
    ),0) Banktotal,


    /* ================= SATURDAY CASH ================= */

    IFNULL((
        SELECT SUM(amount)
        FROM bankent b
        WHERE b.party = a.accode
        AND b.vouchdt BETWEEN '$fdate' AND '$tdate' AND b.group = '2'
    ),0) Saturdaytotal,


    /* ================= WEDNESDAY CASH ================= */

    IFNULL((
        SELECT SUM(amount)
        FROM bankent c
        WHERE c.party = a.accode
        AND c.vouchdt BETWEEN '$fdate' AND '$tdate' AND c.group = '3'
    ),0) Wednesdaytotal,

    /* ================= REPAIRING (RP) ================= */

    IFNULL((
        SELECT SUM(amount)
        FROM bankent r
        WHERE r.party = a.accode
        AND r.vouchdt BETWEEN '$fdate' AND '$tdate' AND r.group = '4'
    ),0) Repairingtotal,

    /* ================= OTHERS ================= */

    IFNULL((
        SELECT SUM(amount)
        FROM bankent r
        WHERE r.party = a.accode
        AND r.vouchdt BETWEEN '$fdate' AND '$tdate' AND r.group = '5'
    ),0) Otherstotal


FROM accmast a

LEFT JOIN transport t
ON t.code = a.transporter

WHERE 1

$where

ORDER BY a.name,a.transporter

") or die(mysqli_error($conn));

/* =========================================================
   TOTALS
========================================================= */

$grandStock = 0;
$grandBank = 0;
$grandAcc = 0;



/* =========================================================
   HTML VIEW
========================================================= */

if (isset($_POST['view'])) {
?>

    <!DOCTYPE html>
    <html>

    <head>

        <meta charset="utf-8">

        <title>Karigar Summary</title>

        <style>
            body {
                font-family: Arial;
                background: #fff;
                padding: 20px;
            }

            table {
                width: 100%;
                border-collapse: collapse;
                font-size: 14px;
            }

            th,
            td {
                border: 1px solid #555;
                padding: 6px;
            }

            thead th {
                background: #ececc4;
                text-align: center;
            }

            .title {
                background: #efc08f !important;
                color: #3f3f8c;
                font-size: 20px;
                font-weight: bold;
            }

            .daterow {
                background: #dbe5f1 !important;
                font-size: 18px;
                font-weight: bold;
            }

            .center {
                text-align: center;
            }

            .right {
                text-align: right;
            }

            .yellow {
                background: yellow;
                font-weight: bold;
            }

            .summary {
                width: 350px;
                margin: 30px auto 0;
            }

            .summary th {
                background: #dbeaf7;
                font-size: 18px;
            }

            .finalamt {
                background: #f6c9cf;
                color: #b00000;
                font-weight: bold;
            }

            .printbtn {
                text-align: center;
                margin-bottom: 20px;
            }

            @media print {

                .printbtn {
                    display: none;
                }

                body {
                    padding: 0;
                }

            }

            .finalamt-positive {
                background: #ff4d4d;
                color: #fff;
                font-weight: bold;
            }

            .finalamt-negative {
                background: #008000;
                color: #fff;
                font-weight: bold;
            }
        </style>

    </head>

    <body>
        <div class="printbtn">
            <button onclick="window.print()">
                PRINT
            </button>
        </div>

        <table>
            <thead>
                <tr>
                    <?php
                    if ($isAllReport) {
                        $colspan = 6;
                    } else {
                        $colspan = 4;
                    }
                    ?>


                    <th colspan="<?= $colspan ?>" class="title">

                        <?php

                        $showTransport = 'ALL SUMMARY REPORT';

                        if ($reporttype == 6) {
                            $showTransport = 'OTHERS REPORT';
                        } elseif ($reporttype == 5) {
                            $showTransport = 'REPAIRING (RP) REPORT';
                        } elseif ($reporttype == 4) {
                            $showTransport = 'WEDNESDAY CASH REPORT';
                        } elseif ($reporttype == 3) {
                            $showTransport = 'SATURDAY CASH REPORT';
                        } elseif ($reporttype == 2) {
                            $showTransport = 'BANK PAYMENT REPORT';
                        } elseif ($reporttype == 1) {
                            $showTransport = 'ALL SUMMARY REPORT';
                        }


                        ?>

                        <?= strtoupper($showTransport) . " ( " . $frdt . " - " . $todt . ")" ?>
                    </th>
                </tr>


                <tr>
                    <th width="5%">Sr. No.</th>
                    <th width="10%">SHOP NAME</th>
                    <th width="30%">KARIGAR NAME</th>

                    <?php if ($isAllReport) { ?>

                        <th width="18%">STOCK AMOUNT</th>
                        <th width="18%">BANK AMOUNT</th>
                        <th width="18%">ACCESSORIES</th>

                    <?php } else { ?>

                        <th width="20%">AMOUNT</th>

                    <?php } ?>

                </tr>

            </thead>



            <tbody>

                <?php

                $i = 1;
                $grandAMT = 0;
                $grandHB = 0;
                $grandIR = 0;
                $grandOTH = 0;
                $Amount = 0;

                while ($row = mysqli_fetch_assoc($qry)) {


                    if ($reporttype == 6) {
                        $Amount = $row["Otherstotal"];
                    } elseif ($reporttype == 5) {
                        $Amount = $row["Repairingtotal"];
                    } elseif ($reporttype == 4) {
                        $Amount = $row["Wednesdaytotal"];
                    } elseif ($reporttype == 3) {
                        $Amount = $row["Saturdaytotal"];
                    } elseif ($reporttype == 2) {
                        $Amount = $row["Banktotal"];
                    }

                    if ($row['transportername'] == "HB") {
                        $grandHB += $Amount;
                    } elseif ($row['transportername'] == "IR") {
                        $grandIR += $Amount;
                    } elseif ($row['transportername'] == "OTHERS") {
                        $grandOTH += $Amount;
                    }

                    $grandStock += $row['stocktotal'];
                    $grandBank += $row['banktotal'];
                    $grandAcc += $row['acstotal'];

                    $grandAMT += $Amount;

                ?>
                    <tr>
                        <td class="center">
                            <?= $i++ ?>
                        </td>

                        <td class="center">
                            <?= $row['transportername'] ?>
                        </td>

                        <td>
                            <?= strtoupper($row['karigar']) ?>
                        </td>

                        <?php if ($isAllReport) { ?>

                            <td class="right">
                                <?= $row['stocktotal'] > 0 ? number_format($row['stocktotal'], 2) : '-' ?>
                            </td>

                            <td class="right">
                                <?= $row['banktotal'] > 0 ? number_format($row['banktotal'], 2) : '-' ?>
                            </td>

                            <td class="right">
                                <?= $row['acstotal'] > 0 ? number_format($row['acstotal'], 2) : '-' ?>
                            </td>

                        <?php } else { ?>

                            <td class="right">
                                <?= $Amount > 0 ? number_format($Amount, 2) : '-' ?>
                            </td>

                        <?php } ?>

                    </tr>

                <?php } ?>



                <?php if ($isAllReport) { ?>

                    <tr class="yellow">

                        <td colspan="3" class="right">TOTAL :</td>

                        <td class="right"><?= number_format($grandStock, 2) ?></td>

                        <td class="right"><?= number_format($grandBank, 2) ?></td>

                        <td class="right"><?= $grandAcc > 0 ? number_format($grandAcc, 2) : '-' ?></td>

                    </tr>

                <?php } else { ?>

                    <tr class="yellow">

                        <td colspan="3" class="right">TOTAL :</td>

                        <td class="right"><?= number_format($grandAMT, 2) ?></td>

                    </tr>

                <?php } ?>

            </tbody>

        </table>



        <?php

        if ($isAllReport) {
            $finalAmount = ($grandAcc + $grandBank) - $grandStock;
        } else {
            $finalAmount = $grandHB + $grandIR + $grandOTH;
        }

        ?>



        <table class="summary">

            <tr>

                <th colspan="2">
                    SUMMERY
                </th>

            </tr>

            <?php if ($isAllReport) { ?>

                <tr>

                    <td>
                        STOCK TOTAL
                    </td>

                    <td class="right">
                        <?= number_format($grandStock, 2) ?>
                    </td>

                </tr>

                <tr>

                    <td>
                        BANK TOTAL
                    </td>

                    <td class="right">
                        <?= number_format($grandBank, 2) ?>
                    </td>

                </tr>

                <tr>

                    <td>
                        ACCESSORIES TOTAL
                    </td>

                    <td class="right">
                        <?= $grandAcc > 0 ? number_format($grandAcc, 2) : '-' ?>
                    </td>

                </tr>


            <?php } else { ?>

                <tr>

                    <td>
                        HB TOTAL
                    </td>

                    <td class="right">
                        <?= number_format($grandHB, 2) ?>
                    </td>

                </tr>

                <tr>

                    <td>
                        IR TOTAL
                    </td>

                    <td class="right">
                        <?= number_format($grandIR, 2) ?>
                    </td>

                </tr>

                <tr>

                    <td>
                        OTHERS TOTAL
                    </td>

                    <td class="right">
                        <?= $grandOTH > 0 ? number_format($grandOTH, 2) : '-' ?>
                    </td>

                </tr>

            <?php } ?>


            <tr class="<?= ($finalAmount >= 0) ? 'finalamt-positive' : 'finalamt-negative'; ?>">
                <td>
                    FINAL AMOUNT
                </td>

                <td class="right">
                    <?php echo number_format($finalAmount, 2); ?>
                </td>

            </tr>



        </table>

    </body>

    </html>

<?php
}

/* =========================================================
   EXCEL
========================================================= */

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

    $spreadsheet = new Spreadsheet();

    $sheet = $spreadsheet->getActiveSheet();

    $sheet->setTitle('Karigar Summary');

    /* =========================================================
       COLUMN WIDTH
    ========================================================= */

    $sheet->getColumnDimension('A')->setWidth(10);
    $sheet->getColumnDimension('B')->setWidth(18);
    $sheet->getColumnDimension('C')->setWidth(40);
    if ($isAllReport) {
        $sheet->getColumnDimension('D')->setWidth(18);
        $sheet->getColumnDimension('E')->setWidth(18);
        $sheet->getColumnDimension('F')->setWidth(18);
    } else {
        $sheet->getColumnDimension('D')->setWidth(18);
    }
    /* =========================================================
       TITLE
    ========================================================= */

    $showTransport = 'ALL SUMMARY REPORT';

    if ($reporttype == 6)
        $showTransport = 'OTHERS REPORT';
    elseif ($reporttype == 5)
        $showTransport = 'REPAIRING (RP) REPORT';
    elseif ($reporttype == 4)
        $showTransport = 'WEDNESDAY CASH REPORT';
    elseif ($reporttype == 3)
        $showTransport = 'SATURDAY CASH REPORT';
    elseif ($reporttype == 2)
        $showTransport = 'BANK PAYMENT REPORT';


    if ($isAllReport) {

        // A-F
        $sheet->mergeCells('A1:E1');
        $sheet->setCellValue('A1', strtoupper($showTransport));
        $sheet->setCellValue('F1', date("d-m-Y", strtotime($tdate)));
    } else {

        // A-D
        $sheet->mergeCells('A1:C1');
        $sheet->setCellValue('A1', strtoupper($showTransport));
        $sheet->setCellValue('D1', date("d-m-Y", strtotime($tdate)));
    }

    /* =========================================================
       HEADER ROW
    ========================================================= */

    if ($isAllReport) {

        $sheet->fromArray([
            [
                'Sr. No.',
                'SHOP NAME',
                'KARIGAR NAME',
                'STOCK AMOUNT',
                'BANK AMOUNT',
                'ACCESSORIES'
            ]
        ], NULL, 'A2');
    } else {

        $sheet->fromArray([
            [
                'Sr. No.',
                'SHOP NAME',
                'KARIGAR NAME',
                'AMOUNT'
            ]
        ], NULL, 'A2');
    }


    /* =========================================================
       TITLE STYLE
    ========================================================= */

    if ($isAllReport) {

        $sheet->getStyle('A1:F1')->applyFromArray([

            'font' => [
                'bold' => true,
                'size' => 14,
                'color' => ['rgb' => '3f3f8c']
            ],

            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER,
                'vertical' => Alignment::VERTICAL_CENTER
            ],

            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN
                ]
            ]

        ]);

        $sheet->getStyle('A1:E1')
            ->getFill()
            ->setFillType(Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('efc08f');

        $sheet->getStyle('F1')
            ->getFill()
            ->setFillType(Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('dbe5f1');
    } else {

        $sheet->getStyle('A1:D1')->applyFromArray([

            'font' => [
                'bold' => true,
                'size' => 14,
                'color' => ['rgb' => '3f3f8c']
            ],

            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER,
                'vertical' => Alignment::VERTICAL_CENTER
            ],

            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN
                ]
            ]

        ]);

        $sheet->getStyle('A1:C1')
            ->getFill()
            ->setFillType(Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('efc08f');

        $sheet->getStyle('D1')
            ->getFill()
            ->setFillType(Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('dbe5f1');
    }


    /* =========================================================
       HEADER STYLE
    ========================================================= */

    if ($isAllReport) {

        $sheet->getStyle('A2:F2')->applyFromArray([

            'font' => [
                'bold' => true,
                'size' => 11
            ],

            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER,
                'vertical' => Alignment::VERTICAL_CENTER,
                'wrapText' => true
            ],

            'fill' => [
                'fillType' => Fill::FILL_SOLID,
                'startColor' => [
                    'rgb' => 'ececc4'
                ]
            ],

            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN
                ]
            ]

        ]);
    } else {

        $sheet->getStyle('A2:D2')->applyFromArray([

            'font' => [
                'bold' => true,
                'size' => 11
            ],

            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER,
                'vertical' => Alignment::VERTICAL_CENTER,
                'wrapText' => true
            ],

            'fill' => [
                'fillType' => Fill::FILL_SOLID,
                'startColor' => [
                    'rgb' => 'ececc4'
                ]
            ],

            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN
                ]
            ]

        ]);
    }


    /* =========================================================
       DATA
    ========================================================= */

    mysqli_data_seek($qry, 0);

    $rowNo = 3;
    $i = 1;
    $grandAMT = 0;
    $grandHB = 0;
    $grandIR = 0;
    $grandOTH = 0;

    while ($row = mysqli_fetch_assoc($qry)) {

        if ($reporttype == 6) {
            $Amount = $row["Otherstotal"];
        } elseif ($reporttype == 5) {
            $Amount = $row["Repairingtotal"];
        } elseif ($reporttype == 4) {
            $Amount = $row["Wednesdaytotal"];
        } elseif ($reporttype == 3) {
            $Amount = $row["Saturdaytotal"];
        } elseif ($reporttype == 2) {
            $Amount = $row["Banktotal"];
        }

        if ($row['transportername'] == "HB") {
            $grandHB += $Amount;
        } elseif ($row['transportername'] == "IR") {
            $grandIR += $Amount;
        } elseif ($row['transportername'] == "OTHERS") {
            $grandOTH += $Amount;
        }

        $sheet->setCellValue('A' . $rowNo, $i++);
        $sheet->setCellValue('B' . $rowNo, $row['transportername']);
        $sheet->setCellValue('C' . $rowNo, strtoupper($row['karigar']));
        if ($isAllReport) {

            $grandStock += $row['stocktotal'];
            $grandBank += $row['banktotal'];
            $grandAcc += $row['acstotal'];

            $sheet->setCellValue('D' . $rowNo, $row['stocktotal']);
            $sheet->setCellValue('E' . $rowNo, $row['banktotal']);
            $sheet->setCellValue('F' . $rowNo, $row['acstotal']);
        } else {

            $grandAMT += $Amount;

            $sheet->setCellValue('D' . $rowNo, $Amount);
        }

        $sheet->getStyle('A' . $rowNo . ':F' . $rowNo)
            ->applyFromArray([

                'alignment' => [
                    'vertical' => Alignment::VERTICAL_CENTER
                ],

                'borders' => [
                    'allBorders' => [
                        'borderStyle' => Border::BORDER_THIN
                    ]
                ]

            ]);

        $sheet->getStyle('A' . $rowNo . ':B' . $rowNo)
            ->getAlignment()
            ->setHorizontal(Alignment::HORIZONTAL_CENTER);

        $sheet->getStyle('D' . $rowNo . ':F' . $rowNo)
            ->getAlignment()
            ->setHorizontal(Alignment::HORIZONTAL_RIGHT);

        $rowNo++;
    }

    /* =========================================================
       TOTAL ROW
    ========================================================= */

    $sheet->mergeCells('A' . $rowNo . ':C' . $rowNo);

    $sheet->setCellValue('A' . $rowNo, 'TOTAL :');

    if ($isAllReport) {
        $sheet->setCellValue('D' . $rowNo, $grandStock);
        $sheet->setCellValue('E' . $rowNo, $grandBank);
        $sheet->setCellValue('F' . $rowNo, $grandAcc);
    } else {
        $sheet->setCellValue('D' . $rowNo, $grandAMT);
    }

    $sheet->getStyle('A' . $rowNo . ':F' . $rowNo)
        ->applyFromArray([

            'font' => [
                'bold' => true
            ],

            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_RIGHT
            ],

            'fill' => [
                'fillType' => Fill::FILL_SOLID,
                'startColor' => [
                    'rgb' => 'ffff00'
                ]
            ],

            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN
                ]
            ]

        ]);

    /* =========================================================
       SUMMARY TABLE
    ========================================================= */

    // $finalAmount = $grandHB + $grandIR + $grandOTH;

    $sumRow = $rowNo + 3;

    $sheet->mergeCells('C' . $sumRow . ':D' . $sumRow);

    $sheet->setCellValue('C' . $sumRow, 'SUMMERY');

    $sheet->getStyle('C' . $sumRow . ':D' . $sumRow)
        ->applyFromArray([

            'font' => [
                'bold' => true,
                'size' => 12
            ],

            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER
            ],

            'fill' => [
                'fillType' => Fill::FILL_SOLID,
                'startColor' => [
                    'rgb' => 'dbeaf7'
                ]
            ],

            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN
                ]
            ]

        ]);

    $sumRow++;

    if ($isAllReport) {

        $summaryData = [
            ['STOCK TOTAL', $grandStock],
            ['BANK TOTAL', $grandBank],
            ['ACCESSORIES TOTAL', $grandAcc],
            ['FINAL AMOUNT', ($grandAcc + $grandBank) - $grandStock]
        ];
    } else {

        $summaryData = [
            ['HB TOTAL', $grandHB],
            ['IR TOTAL', $grandIR],
            ['OTHERS TOTAL', $grandOTH],
            ['FINAL AMOUNT', $grandHB + $grandIR + $grandOTH]
        ];
    }

    foreach ($summaryData as $sd) {

        $sheet->setCellValue('C' . $sumRow, $sd[0]);
        $sheet->setCellValue('D' . $sumRow, $sd[1]);

        $sheet->getStyle('C' . $sumRow . ':D' . $sumRow)
            ->applyFromArray([

                'borders' => [
                    'allBorders' => [
                        'borderStyle' => Border::BORDER_THIN
                    ]
                ]

            ]);

        $sheet->getStyle('D' . $sumRow)
            ->getAlignment()
            ->setHorizontal(Alignment::HORIZONTAL_RIGHT);

        $sumRow++;
    }

    /* FINAL AMOUNT STYLE */

    $sheet->getStyle('C' . ($sumRow - 1) . ':D' . ($sumRow - 1))
        ->applyFromArray([

            'font' => [
                'bold' => true,
                'color' => [
                    'rgb' => 'b00000'
                ]
            ],

            'fill' => [
                'fillType' => Fill::FILL_SOLID,
                'startColor' => [
                    'rgb' => 'f6c9cf'
                ]
            ]

        ]);

    /* =========================================================
       NUMBER FORMAT
    ========================================================= */

    $sheet->getStyle('D3:F' . $sumRow)
        ->getNumberFormat()
        ->setFormatCode('#,##0');

    /* =========================================================
       FONT
    ========================================================= */

    $sheet->getStyle('A1:F' . $sumRow)
        ->getFont()
        ->setName('Arial');

    /* =========================================================
       DOWNLOAD
    ========================================================= */


    $showTransport = 'ALL SUMMARY REPORT';

    if ($reporttype == 6)
        $showTransport = 'OTHERS REPORT';
    elseif ($reporttype == 5)
        $showTransport = 'REPAIRING (RP) REPORT';
    elseif ($reporttype == 4)
        $showTransport = 'WEDNESDAY CASH REPORT';
    elseif ($reporttype == 3)
        $showTransport = 'SATURDAY CASH REPORT';
    elseif ($reporttype == 2)
        $showTransport = 'BANK PAYMENT REPORT';


    $filename = "$showTransport.xlsx";

    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

    header('Content-Disposition: attachment;filename="' . $filename . '"');

    header('Cache-Control: max-age=0');

    $writer = new Xlsx($spreadsheet);

    $writer->save('php://output');

    exit;
}


/* =========================================================
   PDF USING FPDF
========================================================= */

if (isset($_POST['subpdf'])) {

    mysqli_data_seek($qry, 0);

    require('library/fpdf/fpdf.php');


    class PDF extends FPDF
    {
        function Header()
        {
            global $lparty;

            $this->SetFont('Arial', 'B', 16);
            $this->Cell(0, 8, strtoupper($lparty['name']), 0, 1, 'C');
            $this->Ln(2);
        }
    }


    $pdf = new PDF('P', 'mm', 'A4');


    $pdf->AddPage();

    $pdf->SetAutoPageBreak(true, 15);

    /* =========================================================
       TITLE
    ========================================================= */

    $showTransport = 'ALL SUMMARY REPORT';

    if ($reporttype == 6)
        $showTransport = 'OTHERS REPORT';
    elseif ($reporttype == 5)
        $showTransport = 'REPAIRING (RP) REPORT';
    elseif ($reporttype == 4)
        $showTransport = 'WEDNESDAY CASH REPORT';
    elseif ($reporttype == 3)
        $showTransport = 'SATURDAY CASH REPORT';
    elseif ($reporttype == 2)
        $showTransport = 'BANK PAYMENT REPORT';


    $pdf->SetFont('Arial', 'B', 16);

    $pdf->SetFillColor(239, 192, 143);

    $pdf->SetTextColor(63, 63, 140);

    $pdf->Cell(125, 12, strtoupper($showTransport), 1, 0, 'C', true);

    $pdf->SetFillColor(219, 229, 241);

    $pdf->Cell(70, 12, date("d-m-Y", strtotime($fdate)) . " - " . date("d-m-Y", strtotime($tdate)), 1, 1, 'C', true);

    $pdf->Ln(1);

    /* =========================================================
       HEADER
    ========================================================= */

    $pdf->SetFont('Arial', 'B', 8);

    $pdf->SetTextColor(0, 0, 0);

    $pdf->SetFillColor(236, 236, 196);

    if ($isAllReport) {
        $pdf->Cell(10, 10, 'SR.', 1, 0, 'C', true);
        $pdf->Cell(25, 10, 'SHOP', 1, 0, 'C', true);
        $pdf->Cell(70, 10, 'KARIGAR', 1, 0, 'C', true);
        $pdf->Cell(30, 10, 'STOCK', 1, 0, 'C', true);
        $pdf->Cell(30, 10, 'BANK', 1, 0, 'C', true);
        $pdf->Cell(30, 10, 'ACCESSORY', 1, 1, 'C', true);
    } else {

        $pdf->Cell(10, 10, 'SR.', 1, 0, 'C', true);
        $pdf->Cell(30, 10, 'SHOP', 1, 0, 'C', true);
        $pdf->Cell(110, 10, 'KARIGAR', 1, 0, 'C', true);
        $pdf->Cell(45, 10, 'AMOUNT', 1, 1, 'C', true);
    }

    /* =========================================================
       DATA
    ========================================================= */

    $pdf->SetFont('Arial', '', 8);

    $i = 1;
    $grandAMT = 0;

    while ($row = mysqli_fetch_assoc($qry)) {

        if ($reporttype == 6) {
            $Amount = $row["Otherstotal"];
        } elseif ($reporttype == 5) {
            $Amount = $row["Repairingtotal"];
        } elseif ($reporttype == 4) {
            $Amount = $row["Wednesdaytotal"];
        } elseif ($reporttype == 3) {
            $Amount = $row["Saturdaytotal"];
        } elseif ($reporttype == 2) {
            $Amount = $row["Banktotal"];
        }

        if ($row['transportername'] == "HB") {
            $grandHB += $Amount;
        } elseif ($row['transportername'] == "IR") {
            $grandIR += $Amount;
        } elseif ($row['transportername'] == "OTHERS") {
            $grandOTH += $Amount;
        }

        if ($isAllReport) {

            $pdf->Cell(10, 8, $i++, 1, 0, 'C');
            $pdf->Cell(25, 8, $row['transportername'], 1, 0, 'C');
            $pdf->Cell(70, 8, strtoupper($row['karigar']), 1, 0, 'L');
            $pdf->Cell(30, 8, $row['stocktotal'] > 0 ? number_format($row['stocktotal'], 2) : '-', 1, 0, 'R');
            $pdf->Cell(30, 8, $row['banktotal'] > 0 ? number_format($row['banktotal'], 2) : '-', 1, 0, 'R');
            $pdf->Cell(30, 8, $row['acstotal'] > 0 ? number_format($row['acstotal'], 2) : '-', 1, 1, 'R');
        } else {
            $pdf->Cell(10, 8, $i++, 1, 0, 'C');
            $pdf->Cell(30, 8, $row['transportername'], 1, 0, 'C');
            $pdf->Cell(110, 8, strtoupper($row['karigar']), 1, 0, 'L');
            $pdf->Cell(45, 8, $Amount > 0 ? number_format($Amount, 2) : '-', 1, 1, 'R');
        }

        $grandStock += $row['stocktotal'];
        $grandBank += $row['banktotal'];
        $grandAcc += $row['acstotal'];
        $grandAMT += $Amount;
    }

    /* =========================================================
       TOTAL ROW
    ========================================================= */

    $pdf->SetFont('Arial', 'B', 10);

    $pdf->SetFillColor(255, 255, 0);

    if ($isAllReport) {

        $pdf->Cell(105, 9, 'TOTAL :', 1, 0, 'R', true);
        $pdf->Cell(30, 9, number_format($grandStock, 2), 1, 0, 'R', true);
        $pdf->Cell(30, 9, number_format($grandBank, 2), 1, 0, 'R', true);
        $pdf->Cell(30, 9, number_format($grandAcc, 2), 1, 1, 'R', true);
    } else {

        $pdf->Cell(150, 9, 'TOTAL :', 1, 0, 'R', true);
        $pdf->Cell(45, 9, number_format($grandAMT, 2), 1, 1, 'R', true);
    }
    /* =========================================================
       SUMMARY
    ========================================================= */

    // $finalAmount = $grandHB + $grandIR - $grandOTH;

    $pdf->Ln(12);

    $startX = 70;

    $pdf->SetX($startX);

    $pdf->SetFillColor(219, 234, 247);

    $pdf->SetFont('Arial', 'B', 11);

    $pdf->Cell(80, 10, 'SUMMERY', 1, 1, 'C', true);


    if ($isAllReport) {

        $summary = [
            ['STOCK TOTAL', $grandStock],
            ['BANK TOTAL', $grandBank],
            ['ACCESSORIES TOTAL', $grandAcc],
            ['FINAL AMOUNT', ($grandAcc + $grandBank) - $grandStock]
        ];
    } else {

        $summary = [
            ['HB TOTAL', $grandHB],
            ['IR TOTAL', $grandIR],
            ['OTHERS TOTAL', $grandOTH],
            ['FINAL AMOUNT', $grandHB + $grandIR + $grandOTH]
        ];
    }


    foreach ($summary as $k => $s) {

        $pdf->SetX($startX);

        if ($k == 3) {

            $pdf->SetFillColor(246, 201, 207);

            $pdf->SetTextColor(176, 0, 0);

            $pdf->SetFont('Arial', 'B', 10);
        } else {

            $pdf->SetFillColor(255, 255, 255);

            $pdf->SetTextColor(0, 0, 0);

            $pdf->SetFont('Arial', '', 10);
        }

        $pdf->Cell(50, 9, $s[0], 1, 0, 'L', true);

        $pdf->Cell(30, 9, $s[1], 1, 1, 'R', true);
    }

    ob_clean();
    /* =========================================================
       OUTPUT
       ========================================================= */
    $pdf->Output(
        'I',
        "$showTransport.pdf"
    );

    exit;
}

?>