<?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);

$formname = "Joint Report";
$action = "jointrep_fr.php";

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

$zyear = right($zdb, 4);
$mfrdate = getzdates($zyear, 'S');
$mtodate = getzdates($zyear, 'E');

mysqli_select_db($conn, $zdb);

$fromdate = isset($_GET['fromdate']) ? $_GET['fromdate'] : $mfrdate;
$todate = isset($_GET['todate']) ? $_GET['todate'] : $mtodate;

?>

<!DOCTYPE html>
<html>

<head>

    <title>Group Supplier Purchase Dashboard</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

    <style>
        body {
            background: #f4f6f9;
            font-family: Arial;
        }

        .reportbox {
            background: #fff;
            padding: 15px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
            margin-top: 20px;
        }

        .mainrow {
            background: #f8f9fa;
            cursor: pointer;
            font-weight: 600;
        }

        .mainrow:hover {
            background: #eef3ff;
        }

        .detailtable {
            margin-bottom: 0px;
            background: #fcfcfc;
        }

        .amt {
            text-align: right;
        }

        .bal {
            color: #d9534f;
            font-weight: bold;
        }

        .paid {
            color: #5cb85c;
            font-weight: bold;
        }

        .purchase {
            color: #0275d8;
            font-weight: bold;
        }

        .cardbox {
            background: #fff;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
        }

        .cardtitle {
            color: #777;
            font-size: 13px;
        }

        .cardamt {
            font-size: 26px;
            font-weight: bold;
            margin-top: 5px;
        }

        .mainrow.activegrp {
            background: #dfeeff !important;
            border-left: 4px solid #1d7cf2;
        }

        .mainrow.activegrp td {
            font-weight: 700;
        }

        .reset-btn {

            height: 38px;

            padding: 0 18px;

            background: #f1f3f6;

            color: #333;

            border-radius: 10px;

            text-decoration: none;

            font-size: 13px;
            font-weight: 700;

            display: flex;
            align-items: center;
            gap: 6px;

            border: 1px solid #ddd;

            transition: .2s ease;
        }

        .reset-btn:hover {

            background: #e5e7eb;

            color: #000;
        }
    </style>

</head>

<body>

    <div class="container-fluid">

        <div class="row">

            <div class="col-md-12">

                <div class="reportbox">

                    <h3 style="margin-top:0px;">
                        Material Group Supplier Pending Dashboard
                    </h3>

                    <form method="GET">

                        <div class="row">

                            <div class="col-md-2">
                                <label>From Date</label>

                                <input type="date" name="fromdate" class="form-control"
                                    value="<?php echo $fromdate; ?>">
                            </div>

                            <div class="col-md-2">
                                <label>To Date</label>

                                <input type="date" name="todate" class="form-control" value="<?php echo $todate; ?>">
                            </div>

                            <div class="col-md-2">

                                <label>&nbsp;</label>

                                <div style="display:flex; gap:10px; align-items:end;">
                                    <button type="submit" class="btn btn-primary form-control"
                                        style="background-color: #554480;">
                                        Filter Report
                                    </button>

                                    <a href="grpwiserep.php" class="reset-btn">
                                        <i class="ri-refresh-line"></i>
                                        Reset
                                    </a>

                                </div>


                            </div>

                        </div>

                    </form>

                </div>

            </div>

        </div>

        <?php

        /*
        |--------------------------------------------------------------------------
        | PRELOAD SUPPLIER PAYMENTS
        |--------------------------------------------------------------------------
        */

        $paymentArr = array();

        $payqry = mysqli_query($conn, "SELECT accode, SUM(amount) as paidamt FROM actran WHERE amount < 0 
                                              AND grpcode = '009'
                                              AND `date` BETWEEN '$fromdate' AND '$todate' GROUP BY accode");

        while ($pay = mysqli_fetch_array($payqry)) {

            $paymentArr[$pay['accode']] = abs($pay['paidamt']);

        }

        /*
        |--------------------------------------------------------------------------
        | GROUP SUMMARY QUERY
        |--------------------------------------------------------------------------
        */
        $qry = mysqli_query($conn, "SELECT pt.itemgrp, COALESCE(gr.name, pt.itemgrp) as itemgrpname,SUM(pt.amount) as purchaseamt 
                                   FROM purrawtran pt 
                                   INNER JOIN purrawmain pm ON pm.vouchno = pt.vouchno
                                   LEFT JOIN rawmatgrp gr ON pt.itemgrp = gr.code 
                                   WHERE pm.vouchdt BETWEEN '$fromdate' AND '$todate'
                                   GROUP BY pt.itemgrp, gr.name
                                   ORDER BY gr.name");
        /*
        |--------------------------------------------------------------------------
        | TOP TOTALS
        |--------------------------------------------------------------------------
        */

        $totalpurchase = 0;
        $totalpaid = 0;
        $totalbalance = 0;

        $tempRows = array();

        while ($r = mysqli_fetch_array($qry)) {

            $gid = $r['itemgrp'];

            $suppqry = mysqli_query($conn, "SELECT pm.party, SUM(pt.amount) as purchaseamt FROM purrawmain pm 
                                                   LEFT JOIN purrawtran pt ON pm.vouchno = pt.vouchno
                                                   WHERE pt.itemgrp='$gid' AND pm.vouchdt BETWEEN '$fromdate' AND '$todate'
                                                   GROUP BY pm.party");

            $grouppaid = 0;

            while ($s = mysqli_fetch_array($suppqry)) {

                $accode = $s['party'];

                $grouppaid += $paymentArr[$accode] ?? 0;
            }

            $balance = $r['purchaseamt'] - $grouppaid;

            $totalpurchase += $r['purchaseamt'];
            $totalpaid += $grouppaid;
            $totalbalance += $balance;

            $r['paidamt'] = $grouppaid;
            $r['balance'] = $balance;

            $tempRows[] = $r;
        }

        ?>

        <div class="row" style="margin-top:15px;">

            <div class="col-md-4">

                <div class="cardbox">

                    <div class="cardtitle">
                        TOTAL PURCHASE
                    </div>

                    <div class="cardamt purchase">
                        ₹ <?php echo number_format($totalpurchase, 2); ?>
                    </div>

                </div>

            </div>

            <div class="col-md-4">

                <div class="cardbox">

                    <div class="cardtitle">
                        TOTAL PAID
                    </div>

                    <div class="cardamt paid">
                        ₹ <?php echo number_format($totalpaid, 2); ?>
                    </div>

                </div>

            </div>

            <div class="col-md-4">

                <div class="cardbox">

                    <div class="cardtitle">
                        TOTAL BALANCE
                    </div>

                    <div class="cardamt bal">
                        ₹ <?php echo number_format($totalbalance, 2); ?>
                    </div>

                </div>

            </div>

        </div>

        <div class="row">

            <div class="col-md-12">

                <div class="reportbox">

                    <table class="table table-bordered table-hover">

                        <thead>

                            <tr style="background:#554480;color:#fff;">

                                <th width="5%" class="text-right">Sr.</th>
                                <th>Material Group</th>
                                <th width="15%" class="amt">Purchase</th>
                                <th width="15%" class="amt">Paid</th>
                                <th width="15%" class="amt">Balance</th>

                            </tr>

                        </thead>

                        <tbody>

                            <?php

                            $sr = 1;

                            foreach ($tempRows as $row) {

                                $gid = $row['itemgrp'];

                                ?>

                                <tr class="mainrow" data-target="group<?php echo $gid; ?>">

                                    <td class="text-right">

                                        <span class="toggleicon" style="float:left;">
                                            <i class="glyphicon glyphicon-chevron-down"></i>
                                        </span>

                                        <?php echo $sr++; ?>

                                    </td>

                                    <td>

                                        <?php echo $row['itemgrpname']; ?>

                                    </td>

                                    <td class="amt purchase">

                                        <?php echo number_format($row['purchaseamt'], 2); ?>

                                    </td>

                                    <td class="amt paid">

                                        <?php echo number_format($row['paidamt'], 2); ?>

                                    </td>

                                    <td class="amt bal">

                                        <?php echo number_format($row['balance'], 2); ?>

                                    </td>

                                </tr>

                                <tr id="group<?php echo $gid; ?>" style="display:none;">

                                    <td colspan="5">

                                        <table class="table table-bordered detailtable">

                                            <tr style="background:#f0f0f0;">

                                                <th>Supplier</th>
                                                <th width="15%" class="amt">Purchase</th>
                                                <th width="15%" class="amt">Paid</th>
                                                <th width="15%" class="amt">Balance</th>

                                            </tr>

                                            <?php

                                            $suppqry = mysqli_query($conn, "SELECT pm.party, ac.name as supplier, SUM(pt.amount) as purchaseamt FROM purrawmain pm
                                                                                   LEFT JOIN purrawtran pt ON pm.vouchno = pt.vouchno
                                                                                   LEFT JOIN accmast ac ON pm.party = ac.accode 
                                                                                   WHERE pt.itemgrp='$gid' AND pm.vouchdt BETWEEN '$fromdate' AND '$todate' 
                                                                                   GROUP BY pm.party ORDER BY supplier");

                                            while ($sup = mysqli_fetch_array($suppqry)) {

                                                $accode = $sup['party'];

                                                $purchaseamt = $sup['purchaseamt'];

                                                $paidamt = $paymentArr[$accode] ?? 0;

                                                $totalSupplierPurchaseQry = mysqli_query($conn, "SELECT SUM(pt.amount) as totalpurchase
                                                                                                        FROM purrawmain pm
                                                                                                        LEFT JOIN purrawtran pt ON pm.vouchno = pt.vouchno
                                                                                                        WHERE pm.party='$accode'
                                                                                                        AND pm.vouchdt BETWEEN '$fromdate' AND '$todate'");

                                                $totalSupplierPurchase = mysqli_fetch_assoc($totalSupplierPurchaseQry)['totalpurchase'];

                                                $paidamt = 0;

                                                if ($totalSupplierPurchase > 0) {

                                                    $paidamt = ($purchaseamt / $totalSupplierPurchase) * ($paymentArr[$accode] ?? 0);

                                                }

                                                $balance = $purchaseamt - $paidamt;

                                                ?>

                                                <tr>

                                                    <td>

                                                        <?php echo $sup['supplier']; ?>

                                                    </td>

                                                    <td class="amt">

                                                        <?php echo number_format($purchaseamt, 2); ?>

                                                    </td>

                                                    <td class="amt">

                                                        <?php echo number_format($paidamt, 2); ?>

                                                    </td>

                                                    <td class="amt">

                                                        <?php echo number_format($balance, 2); ?>

                                                    </td>

                                                </tr>

                                            <?php } ?>

                                        </table>

                                    </td>

                                </tr>

                            <?php } ?>

                        </tbody>

                    </table>

                </div>

            </div>

        </div>

    </div>


    <script>

        $('body').on('click', '.mainrow', function () {

            var target = $(this).data('target');

            $('#' + target).toggle();

            var icon = $(this).find('.toggleicon i');

            if ($('#' + target).is(':visible')) {

                icon.removeClass('glyphicon-chevron-down')
                    .addClass('glyphicon-chevron-up');

                $(this).addClass('activegrp');

            } else {

                icon.removeClass('glyphicon-chevron-up')
                    .addClass('glyphicon-chevron-down');

                $(this).removeClass('activegrp');

            }

        });

    </script>

</body>

</html>