<?php
include("db/cn.php");
include("common/tx.php");
ob_start();
if (isset($_SESSION['user_name']) && isset($_SESSION['user_role']) && isset($_SESSION['outlet_name']) && isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];
}
ob_end_flush();
?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title><?php echo $tx; ?></title>

    <!-- Custom fonts for this template-->
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
   <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">

    <!-- Custom styles for this template-->
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
        <link href="../css/sb-admin-2.css" rel="stylesheet">
    
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<style>
 #table-container-wrapper {
    max-height: 460px; /* Adjust the maximum height as needed */
    overflow-y: auto; /* Enable vertical scroll when content overflows */
}
body {
    font-family: 'Quicksand', sans-serif;
    
}
		    .chart-container {
      position: relative;
      background: rgba(255, 255, 255, 0.9);
      border-radius: 10px;
      padding: 15px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }

    canvas {
      max-width: 100%;
      height: auto;
    }
.bg-gradient-primary{
    
	background:#0A4657;
	color:#fff;	
	
	}

.btn-primary{
	background:#0A4657;
	color:#fff;
	 border:1px #0A4657 solid;
	
	}  
.btn-primary:hover{
  
  background:#fff;
  border:1px #0A4657 solid;
	color:#0A4657;
	
	}	 
    .chart-container {
      position: relative;
      background: rgba(255, 255, 255, 0.9);
      border-radius: 10px;
      padding: 15px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }

    canvas {
      max-width: 100%;
      height: auto;
    }
	
	.fa-download:hover{
		color:#953E39;
		}
		
.btn, .form-control, tr{
	  	font-weight:700;
		}
  </style>

<body id="page-top">

    <!-- Page Wrapper -->
    <div id="wrapper">

        <!-- Sidebar -->
        <?php
        include("common/sd.php");
		?>
        <!-- End of Sidebar -->

        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">

            <!-- Main Content -->
            <div id="content">

                <!-- Topbar -->
                <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">

                    <!-- Sidebar Toggle (Topbar) -->
                    <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
                        <i class="fa fa-bars"></i>
                    </button>

                    <!-- Topbar Search -->
                    
  <?php include('common/log.php');  ?>

                    <!-- Topbar Navbar -->
                    
                </nav>
<div class="container-fluid mt-5">
    <div class="row">
        <div class="col-sm-3">
               <h2 style="color:#060606; font-weight:700;">Invoice Report</h2>  
        </div>
        <div class="col-sm-6"></div>
        <div class="col-sm-3">

        </div>
    </div>
    <br>
   
    <form method="POST" action="">
    <div class="row">
        <div class="form-group col-3">
            <label>Payment Method:</label>
            <select id="paid" name="paid" class="form-control">
                <option value="">Select</option>
                <option value="cash">Cash</option>
                <option value="credit">Credit</option>
                <option value="bank1">Bank 1</option>
                <option value="bank2">Bank 2</option>
                <option value="bank3">Bank 3</option>
               
            </select>
        </div>
        <div class="col-sm-12">
            
                <div class="row">
                    <div class="form-group col-3">
                        <label for="start_date">Start Date:</label>
                        <input type="date" id="start_date" name="start_date" class="form-control" required>
                    </div>
                    <div class="form-group col-3">
                        <label for="end_date">End Date:</label>
                        <input type="date" id="end_date" name="end_date" class="form-control" required>
                    </div>
                    <div class="form-group col-4" style="margin-top:30px;">
                        <button type="submit" class="btn btn-primary"><i class="fas fa-filter "></i>&nbsp;Filter</button>
                         <a href="report_in.php"><button type="button" class="btn btn-dark btn-lg">
                             <i class="fas fa-sync-alt fa-1x"></i></button></a>
                         <button id="downloadExcel" type="submit" class="btn btn-success">Excel</button>
                          <button id="downloadPdf" type="button" class="btn btn-danger">
                             PDF</button>
                       
                        
                    </div>
                </div>
            
        </div>
       
    </div>
     </form>
</div>
<div id = 'report'>
    <div class="container-fluid" id="table-container-wrapper">
    <?php
    // Check connection
    if ($connection->connect_error) {
        die("Connection failed: " . $connection->connect_error);
    }

    if (isset($_POST['start_date']) && isset($_POST['end_date'])) {
        $start_date = $_POST['start_date'];
        $end_date = $_POST['end_date'];
        $paid_by = isset($_POST['paid']) ? $_POST['paid'] : '';

        // Construct the SQL query using LIKE for the paid_by filter
        $query = "SELECT date_time, order_id, customer_name, customer_phone, discount_amount, paid_by, SUM(discount_amount) AS total_amount 
                  FROM log_user_sales 
                  WHERE date_time BETWEEN ? AND ? 
                  AND paid_by LIKE ? 
                  GROUP BY order_id";

        // Prepare the SQL query
        $stmt = $connection->prepare($query);

        // Use '%' for "All" payment methods, otherwise use the exact payment method
        $paid_by_param = !empty($paid_by) ? $paid_by : '%';
        $stmt->bind_param("sss", $start_date, $end_date, $paid_by_param);

        // Execute the query
        $stmt->execute();
        $result = $stmt->get_result();

        // Display results in a table
        echo "<table id='patientTable' class='table table-striped table-sm text-center bg-white'>";
      echo "
<thead class='font-weight-bold text-center'>
    <tr>
        <th colspan='8'>Report Date Range</th>
    </tr>
    <tr>
        <th colspan='8'>{$start_date}&nbsp;To&nbsp;{$end_date}</th>
    </tr>
</thead>";

        echo "<thead style='background:#0A4657; color:white;'>
                                    <tr>
                                        <th colspan='8' class='text-center p-3'>Invoice Report Information</th>
                                    </tr>
                                </thead>";
                                
        echo "<tr class='bg-dark text-white'>
                <th>Date/Time</th>
                <th>Order ID</th>
                <th>Customer Name</th>
                <th>Discount Amount(Rs)</th>
                <th>Paid By</th>
              </tr>
               ";
          
        $grandTotal = 0; // To calculate the grand total of all discounts
        while ($row = $result->fetch_assoc()) {
            echo "<tr style='color:#060606;'>
                    <td>{$row['date_time']}</td>
                    <td>{$row['order_id']}</td>
                    <td>{$row['customer_name']}</td>
                    <td>{$row['discount_amount']}</td>
                    <td style='text-transform:capitalize;'>{$row['paid_by']}</td>
                  </tr>";
            $grandTotal += $row['discount_amount'];
        }
        echo "
       
        </table>";

        // Display the grand total
        

        // Close the statement and connection
        $stmt->close();
    }

    $connection->close();
    ?>
    <?php echo "<h3 style='margin-left:;color:#060606;font-weight:700;'>Total Amount(Rs): $grandTotal</h3>";?>
</div>
</div>



    
            
                <!-- /.container-fluid -->

            </div>
            <br><br>
            <!-- End of Main Content -->

            <!-- Footer -->
            <?php include("common/main_ft.php");  ?>
            <!-- End of Footer -->

        </div>
        <!-- End of Content Wrapper -->

    </div>
    <!-- End of Page Wrapper -->

    <!-- Scroll to Top Button-->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <!-- Logout Modal-->
    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                    <a class="btn btn-primary" href="">Logout</a>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>  
   <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></script>
   
   <script>
  document.getElementById("downloadPdf").addEventListener("click", function (e) {
    e.preventDefault(); // ⛔ stop form submit

    const { jsPDF } = window.jspdf;
    const report = document.getElementById("report");

    if (!report) {
        alert("Report not found");
        return;
    }

    const now = new Date();
    const formattedDateTime =
        now.toLocaleDateString() + " " + now.toLocaleTimeString();

    html2canvas(report, { scale: 1 }).then(canvas => {

        const imgData = canvas.toDataURL("image/jpeg", 0.65);

        const pdf = new jsPDF("p", "mm", "a4");

        // ✅ FIXED: pageWidth defined
        const pageWidth = pdf.internal.pageSize.getWidth();
        const imgHeight = (canvas.height * pageWidth) / canvas.width;

        // CONTENT
        pdf.addImage(imgData, "JPEG", 0, 30, pageWidth, imgHeight);

        /* HEADER */
        pdf.setFont("helvetica", "bold");
        pdf.setFontSize(16);
        pdf.text("Whole Sale Retail", 2, 12);
        pdf.text("Invoice Report", pageWidth - 2, 12, { align: "right" });

        pdf.setFont("helvetica", "normal");
        pdf.setFontSize(10);
        pdf.text("Address: Al-Hafeez Shopping Mall, Gulberg III Lahore.", 2, 18);
        pdf.text("Phone: 0334-8739892, Whatsapp: 0334-8739892", 2, 22);
        pdf.text("Email: info@atrsms.pk", 2, 26);

        pdf.setFont("helvetica", "bold");
        pdf.text(`Printed: ${formattedDateTime}`, pageWidth - 2, 22, { align: "right" });

        pdf.save("Invoice-Report.pdf");
    })
    .catch(err => {
        console.error(err);
        alert("PDF generation failed");
    });
});
   </script>
   
    <!-- Bootstrap core JavaScript-->
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Core plugin JavaScript-->
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>

    <!-- Custom scripts for all pages-->
    <script src="../js/sb-admin-2.min.js"></script>

</body>

</html>