<?php
ini_set('display_errors', 1);
error_reporting(E_ERROR);

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

$zdb = $_SESSION["zdbyear_" . $dbname];
$admin = $_SESSION["admin_" . $dbname];
$zcompany = $_SESSION["zcompany"];
$formname = "Aaya Gaya";

$grid = "cashinoutrep.php";
$cust = "accmast";
$ztit = $_SESSION["tit_" . $dbname];
$zroot = $_SESSION["zdir"];
$maindb = $cust;
$accdb = "actran";

$fseries = $_SESSION["series"];
$keycond = "";
$abal = 'accmtn';
$accbal = $abal . $ztit;
$compcond = '';

//if (isset($_POST["view"])) {
$a = 1;

$mfrmdate = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
$mtodate = $mfrmdate;
$mname1 = trim($_REQUEST["accode"]);

if ($mfrmdate == "" && $mtodate == "") {
    $mfrmdate = date("Y-m-d");
    $mtodate = date("Y-m-d");
}

$mfdt = $mfrmdate;
$mtdt = $mtodate;

$paytypecond = '';
if (!empty($_POST["paytype"])) {
    $paytype = trim($_POST["paytype"]);
    $paytypecond = "AND `paytype`='$partytype'";
}

$zyear = right($zdb, 4);
//$mfrmdate = getzdates($zyear, 'S', $conn);
//$mtodate = getzdates($zyear, 'E', $conn);
mysqli_select_db($conn, $zdb);

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

    $count = $_POST["items"];

    for ($i = 0; $i <= $count; $i++) {

        $vouchno = $_POST["vouchno_$i"];

        $lrrecd = isset($_POST["lrrecd_$i"]) ? '1' : '0';

        mysqli_query(
            $conn,
            "UPDATE `salemain`
             SET lrrecd='$lrrecd'
             WHERE vouchno='$vouchno'"
        ) or die(mysqli_error($conn));
    }
}



//if ($a == 1) {
$recqry = mysqli_query($conn, "SELECT *,DATE_FORMAT(`vouchdt`, '%d-%m-%Y') as mydt,DATE_FORMAT(`lrdate`, '%d-%m-%Y') as lrdt FROM `salemain` WHERE `vouchdt` = '$mfrmdate'") or die(mysqli_error($conn));
$rcount = mysqli_num_rows($recqry);

include("includes/linkshead.php");
?>
<style>
    @media print {
        a {
            text-decoration: none;
            /* Remove the underline */
            color: black;
            /* Change the color to black */
        }

        a[href]:after {
            content: none;
            /* Hide the href */
        }

        table td {
            font-size: 10px;
        }
    }

    .noprint {
        margin-top: 5px;
        border: 2px solid;
        border-radius: 10px;
    }

    .noprint1 {
        margin-top: 5px;
        border: 2px solid;
        border-radius: 10px;
    }

    .intbtn {
        color: black;
        text-transform: uppercase;
        text-decoration: none;
        border: 2px solid green;
        border-radius: 5px;
        padding: 10px 20px;
        font-size: 17px;
        font-weight: bold;
        background: transparent;
        position: relative;
        transition: all 1s;
        overflow: hidden;
    }

    .intbtn:hover {
        color: white;
    }

    .intbtn::before {
        content: '';
        position: absolute;
        height: 100%;
        width: 0%;
        top: 0;
        left: -40px;
        transform: skewX(45deg);
        background-color: #963634;
        z-index: -1;
        transition: all 1s;
    }

    .intbtn:hover::before {
        width: 160%;
    }
</style>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $("body").on("click", ".intbtn", Deposit);
        $("body").on("click", ".savdep", savDeposit);


        function savDeposit() {
            var formData = {};
            // Iterate over all visible input, textarea, and select fields
            $('.depModal input, textarea, select').filter(':visible').each(function () {
                var fieldName = $(this).attr('name');
                var fieldValue;
                var fieldType = $(this).attr('type'); // Get the type of the field


                // Only add to the object if the field has a name attribute

                if (fieldType === 'checkbox' || fieldType === 'radio') {
                    // For checkboxes and radios, check if they are checked
                    fieldValue = $(this).is(':checked') ? $(this).val() : null;
                } else {
                    // For other fields (text, textarea, select), get the value directly
                    fieldValue = $(this).val();
                }
                if (fieldName && fieldValue !== null) {
                    formData[fieldName] = fieldValue;
                }
            });

            // Convert the object to JSON format
            var jsonData = JSON.stringify(formData);
            var newv = 0;
            $.ajax({
                //                url: 'addhtrtcrd.php', // Replace with your server URL
                url: 'saveAgentIn.php', // Replace with your server URL
                type: 'POST',
                contentType: 'application/json',
                data: jsonData,
                success: function (response) {
                    var m = response;
                    if (m.success == true) {

                        newv = m.vouchno;
                        $(".vouchno").val(m.vouchno);
                        if (newv > 0) {
                            location.reload();
                        }
                        event.preventDefault();
                    }
                },
                error: function (xhr, status, error) {
                    console.error('Error:', status, error);
                }
            });
            //            alert(jsonData);
        }

        function Deposit() {
            $(".depModal").modal("show");
            var depwit = $(this).val();
            $(".para").val(depwit);
            if (depwit == "I") {
                $(".inttrd").show();
                $(".deptrd").hide();
                $(".wittrd").hide();
                $(".trdint").show();
                $("#myLargeModalLabel1").hide();
                $("#myLargeModalLabel2").hide();
                $("#myLargeModalLabel3").show();

            }
        }

        $("#prevDate").click(function () {
            let d = new Date($("#selDate").val());
            d.setDate(d.getDate() - 1);

            let newDate = d.toISOString().split('T')[0];
            location.href = "?date=" + newDate;
        });

        $("#nextDate").click(function () {
            let d = new Date($("#selDate").val());
            d.setDate(d.getDate() + 1);

            let newDate = d.toISOString().split('T')[0];
            location.href = "?date=" + newDate;
        });

        $("#selDate").change(function () {
            location.href = "?date=" + $(this).val();
        });
    })
</script>
<script>
    function saveAsPDF() {
        const element = document.getElementById('content-to-save');
        // Get the invoice number from an element
        const vouchno = document.getElementById('vouchno')?.textContent || 'NoINV';

        html2pdf()
            .set({
                margin: 0,
                filename: `LR.pdf`, // Dynamically set filename
                image: {
                    type: 'jpeg',
                    quality: 0.98
                },
                html2canvas: {
                    scale: 3
                }, // Increase scale for better quality and fit
                jsPDF: {
                    unit: 'in',
                    format: 'a4',
                    orientation: 'landscape'
                }
            })
            .from(element)
            .save();
    }
</script>
</head>

<body>
    <form method="POST">

        <div class="container">
            <br>
            <div class="row">
                <div class="col-lg-4 col-md-1 col-sm-3 col-xs-3 pad text-right">
                </div>
                <div class="col-lg-2 col-md-1 col-sm-3 col-xs-3 pad text-right">
                    <input type="submit" name="submit" value="Update" class="btn btn-danger noprint1"
                        style="background-color:blue; color: white; float:right; margin-right: 5%;width: 100%">

                    <!--<button type="button" class="intbtn noprint" value="I">Entry</button>-->
                </div>
                <div class="col-lg-2 col-md-1 col-sm-3 col-xs-3 pad text-right">

                    <!-- <button class="btn btn-primary goBack noprint" onclick="window.close()" style="float: right;width: 150px;height:35px;background-color: white;color:#A0B1BA;">Go Back</button> -->
                    <button type="button" class="btn btn-primary noprint1" onclick="saveAsPDF()"
                        style="float: right;width: 150px;height:35px;background-color: #40916c;color:#ffffff;">PDF</button>
                </div>
            </div>
            <div id="content-to-save">
                <div class="row">
                    <div class="col-lg-6" style="width:100%;">
                        <div class="box">
                            <?php
                            //                    include("includes/head_rep.php");
                            ?>

                            <table width="100%">
                                <tr>
                                    <th colspan="2" style="text-align:left;padding:10px;">
                                        <div style="display:flex;align-items:center;gap:10px;">

                                            <span style="font-size:18px;font-weight:700;color:#212529;">
                                                <?= $mname ?>
                                            </span>

                                            <button type="button" id="prevDate" class="btn btn-primary btn-sm">
                                                ◀
                                            </button>

                                            <div style="
                                                 border:2px solid #0d6efd;
                                                 border-radius:8px;
                                                 padding:4px 10px;
                                                 background:#f8f9fa;
                                                 display:flex;
                                                 align-items:center;
                                                 gap:8px;
                                                 ">
                                                <span style="
                                                      font-size:16px;
                                                      font-weight:bold;
                                                      color:#0d6efd;
                                                      ">
                                                    📅
                                                </span>

                                                <input type="date" id="selDate" value="<?= $mfrmdate ?>" style="
                                                       border:none;
                                                       background:transparent;
                                                       font-size:16px;
                                                       font-weight:bold;
                                                       color:#212529;
                                                       outline:none;
                                                       ">
                                            </div>

                                            <button type="button" id="nextDate" class="btn btn-primary btn-sm">
                                                ▶
                                            </button>

                                        </div>
                                    </th>
                                </tr>
                            </table>



                            <table style="background: white;width: 100%" class=" table-condensed table-bordered">
                                <thead class="mySearchTr">
                                    <tr>
                                        <th style="width:5%">Sr</th>
                                        <th style="width:5%">Voucher</th>
                                        <th style="width:10%">Date</th>
                                        <th style="width:25%">Party</th>
                                        <!--<th style="width:5%">Type</th>-->
                                        <th style="width:6%" class="text-right">Net.Amt</th>
                                        <th style="width:9%">No. Cartons</th>
                                        <th style="width:15%">Transporter</th>
                                        <th style="width:9%">LR No.</th>
                                        <th style="width:7%">LR Date</th>
                                        <th style="width:5%">LR Recd.</th>
                                        <th style="width:5%">Entry</th>
                                        <th style="width:5%">Bill Print</th>
                                        <th style="width:5%">LR View</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $ctr = 0;
                                    $nctr = 1;
                                    $totamt = 0;
                                    $totpack = 0;
                                    $totbill = 0;
                                    $totitmpr = 0;
                                    $totiqtty = 0;
                                    $linstyle = '';
                                    $status = '';

                                    while ($pmain = mysqli_fetch_array($recqry)) {
                                        $lrchk = "";
                                        if ($pmain['lrrecd'] == '1') {
                                            $lrchk = "checked";
                                        }
                                        if ($pmain['cashcred'] == 'C') {
                                            $paytype = "Cash";
                                        } else {
                                            $paytype = "Credit";
                                        }
                                        $getparty = mysqli_query($conn, "SELECT `accode`,`name` FROM `accmast` WHERE `accode`='$pmain[party]'") or die(mysqli_error($conn));
                                        $party = mysqli_fetch_array($getparty);

                                        $trge = "<a target='_blank' href='sale.php?vouchno=$pmain[vouchno]&mode=edit&edpara=1'><i class='fa fa-pencil'></i></a>";
                                        $trge2 = "<a target='_blank' href='sale_pdf.php?vouchno=$pmain[vouchno]&mode=edit'><i class='fa fa-print'></i></a>";
                                        $trge3 = "";
                                        if ($pmain['imgpath'] != "") {
                                            $separator = (strpos($pmain['imgpath'], '?') !== false) ? '&' : '?';

                                            $trge3 = "<a id=\"print\" class=\"btn btn-pad btn-square\" style=\"background-color:#5BC0DE;\" href=\"{$pmain['imgpath']}{$separator}a=" . mt_rand() . "\" target=\"_blank\">View Image</a>";
                                            // $trge3 = "<a id=\"print\" class=\"btn btn-pad btn-square\" style=\"background-color:#5BC0DE;\" href=\"{$pmain['imgpath']}\" target=\"_blank\">View Image</a>";
                                        }

                                        $gettransp = mysqli_query($conn, "SELECT `code`,`name` FROM `transport` WHERE `code`= '$pmain[transporter]'") or die(mysqli_error($conn));
                                        $ltrans = mysqli_fetch_array($gettransp);

                                        echo "<tr id='boldfont' style='$linstyle'>";
                                        echo "<td>$nctr</td>";
                                        echo "<td>$pmain[vouchno]<input type='hidden' name='vouchno_$ctr' value='$pmain[vouchno]'></td>";
                                        echo "<td>$pmain[mydt]</td>";
                                        echo "<td>$party[name]</td>";
                                        //                                    Echo "<td>$paytype</td>";
                                        echo "<td class='text-right'>$pmain[billamt]</td>";
                                        echo "<td class='text-right'>$pmain[nocart]</td>";
                                        echo "<td>$ltrans[name]</td>";
                                        echo "<td>$pmain[lrno]</td>";
                                        echo "<td>$pmain[lrdt]</td>";
                                        echo "<td style='padding:0;'>
        <div style='display:flex;justify-content:center;align-items:center;height:100%;'>
            <input type='checkbox'
                   name='lrrecd_$ctr'
                   class='lrrecd'
                   $lrchk
                   style='width:25px;height:25px;'>
        </div>
      </td>";
                                        echo "<td class='text-center noPrint'>$trge</td>";
                                        echo "<td class='text-center noPrint'>$trge2</td>";
                                        echo "<td class='text-center noPrint'>$trge3</td>";
                                        echo "</tr>";
                                        $ctr++;
                                        $nctr++;

                                        $totnetamt = $totnetamt + $pmain['nocart'];
                                    }
                                    echo "<input type='hidden' name='items' value='$ctr'>";
                                    $colr = "grey";
                                    echo "<tr> ";
                                    echo "<td align='right' colspan='5' style='color:$colr;' id='font'><h4><b>Grand Total</h4></b></td>";
                                    //                                echo "<td align='right' style='color:red;' id='font'><h4><b>$totiqty</b></h4></td>";
//                            echo "<td align='right' style='color:red;' id='font'><h4><b>$totsubtot</b></h4></td>";
//                            echo "<td align='right' style='color:red;' id='font'><h4><b>$totdiscamt</b></h4></td>";
//                            echo "<td align='right' style='color:red;' id='font'><h4><b>$totfretight</b></h4></td>";
                                    echo "<td align='right' style='color:red;' id='font'><h4><b>$totnetamt</b></h4></td>";
                                    echo "</tr>";
                                    ?>
                                </tbody>
                            </table>

                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php include("includes/linksfoot.php") ?>
    </form>
</body>

</html>