<?php
include("db/cn.php");
include("common/tx.php");
ini_set('display_errors', 1);
error_reporting(E_ALL);

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

/* ================= SESSION ================= */
if (
    !isset($_SESSION['user_name']) ||
    !isset($_SESSION['user_role']) ||
    !isset($_SESSION['outlet_name']) ||
    !isset($_SESSION['outlet_address'])
) {
    die("Session expired");
}

$userName       = $_SESSION['user_name'];
$userRole       = $_SESSION['user_role'];
$outlet_name    = $_SESSION['outlet_name'];
$outlet_address = $_SESSION['outlet_address'];

/* ================= DEFAULTS ================= */
$creditor = '';
$startDate = '';
$endDate = '';
$transactions = [];
$openingBalance = 0;
$balance = 0;

/* ================= FILTER ================= */
if (isset($_POST['filter'])) {

    $creditor  = mysqli_real_escape_string($connection, $_POST['supplier']);
    $startDate = date('Y-m-d', strtotime($_POST['startDate']));
    $endDate   = date('Y-m-d', strtotime($_POST['endDate']));

    /* ===== BASE OPENING ===== */
    $baseOpening = 0;
    $res = mysqli_query($connection,
        "SELECT open_amount FROM creditor_opening_amount
         WHERE creditor_name='$creditor' LIMIT 1"
    );
    if ($res && mysqli_num_rows($res)) {
        $baseOpening = (float)mysqli_fetch_assoc($res)['open_amount'];
    }

    /* ===== TRANSACTIONS BEFORE START DATE ===== */
$creditSalesBefore = mysqli_fetch_assoc(mysqli_query($connection,
    "SELECT COALESCE(SUM(order_total),0) total FROM (
        SELECT order_id, MAX(discount_amount) AS order_total
        FROM log_user_sales
        WHERE customer_name='$creditor'
        AND paid_by='credit'
        AND status!='refund'
        AND date_time < '$startDate'
        GROUP BY order_id
    ) t"
))['total'];


$refundsBefore = mysqli_fetch_assoc(mysqli_query($connection,
    "SELECT COALESCE(SUM(order_total),0) total FROM (
        SELECT r_order_id, MAX(discount_amount) AS order_total
        FROM log_user_sales
        WHERE customer_name='$creditor'
        AND paid_by='credit'
        AND status='refund'
        AND date_time < '$startDate'
        GROUP BY r_order_id
    ) t"
))['total'];




    $creditPaidBefore = mysqli_fetch_assoc(mysqli_query($connection,
        "SELECT COALESCE(SUM(amount),0) total
         FROM credit_paid
         WHERE cr_name='$creditor'
         AND date_time < '$startDate'"
    ))['total'];

    /* ===== FINAL OPENING BALANCE ===== */
    $openingBalance =
        $baseOpening
        + $creditSalesBefore
        - $refundsBefore
        - $creditPaidBefore;

    $balance = $openingBalance;

    /* ================= TRANSACTIONS BETWEEN DATES ================= */

    // CREDIT SALES
    $rs = mysqli_query($connection,
        "SELECT date_time date, discount_amount amount, paid_by, order_id,
         SUM(product_quantity) total_qty,
         GROUP_CONCAT(DISTINCT desc_note SEPARATOR ', ') desc_note
         FROM log_user_sales
         WHERE customer_name='$creditor'
         AND paid_by='credit'
         AND status!='refund'
         AND date_time BETWEEN '$startDate' AND '$endDate'
         GROUP BY order_id"
    );
    while ($r = mysqli_fetch_assoc($rs)) {
        $transactions[] = [
            'date'=>$r['date'],
            'description'=>'Credit Sale',
            'amount'=>$r['amount'],
            'paid_by'=>$r['paid_by'],
            'total_qty'=>$r['total_qty'],
            'invoice'=>$r['order_id'],
            'desc_note'=>$r['desc_note']
        ];
    }

    // POS CASH
    $rs = mysqli_query($connection,
        "SELECT date_time date, cash_amount amount, paid_by, order_id,
         SUM(product_quantity) total_qty,
         GROUP_CONCAT(DISTINCT desc_note SEPARATOR ', ') desc_note
         FROM log_user_sales
         WHERE customer_name='$creditor'
         AND paid_by='pos'
         AND status!='refund'
         AND date_time BETWEEN '$startDate' AND '$endDate'
         GROUP BY order_id"
    );
    while ($r = mysqli_fetch_assoc($rs)) {
        $transactions[] = [
            'date'=>$r['date'],
            'description'=>'POS Cash Received',
            'amount'=>$r['amount'],
            'paid_by'=>$r['paid_by'],
            'total_qty'=>$r['total_qty'],
            'invoice'=>$r['order_id'],
            'desc_note'=>$r['desc_note']
        ];
    }

    // REFUNDS
    $rs = mysqli_query($connection,
        "SELECT date_time date, discount_amount amount, paid_by, r_order_id invoice
         FROM log_user_sales
         WHERE customer_name='$creditor'
         AND status='refund'
         AND paid_by='credit'
         AND date_time BETWEEN '$startDate' AND '$endDate'
         GROUP BY r_order_id
         "
    );
    while ($r = mysqli_fetch_assoc($rs)) {
        $transactions[] = [
            'date'=>$r['date'],
            'description'=>'Credit Sale Return',
            'amount'=>-abs($r['amount']),
            'paid_by'=>$r['paid_by'],
            'total_qty'=>0,
            'invoice'=>$r['invoice']
        ];
    }

    // CREDIT RECEIVED
    $rs = mysqli_query($connection,
        "SELECT date_time date, amount, paid_by
         FROM credit_paid
         WHERE cr_name='$creditor'
         AND date_time BETWEEN '$startDate' AND '$endDate'"
    );
    while ($r = mysqli_fetch_assoc($rs)) {
        $transactions[] = [
            'date'=>$r['date'],
            'description'=>'Credit Received',
            'amount'=>-abs($r['amount']),
            'paid_by'=>$r['paid_by'],
            'total_qty'=>0,
            'invoice'=>'-'
        ];
    }

    usort($transactions, fn($a,$b)=>strtotime($a['date'])<=>strtotime($b['date']));
}

/* ================= CUSTOMER INFO ================= */
$customerInfo = [];
if ($creditor) {
    $rs = mysqli_query($connection,
        "SELECT cr_name, cr_address, phone_number, cr_id
         FROM credit_note WHERE cr_name='$creditor' LIMIT 1"
    );
    if ($rs && mysqli_num_rows($rs)) {
        $customerInfo = mysqli_fetch_assoc($rs);
    }
}
?>


<!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>
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, option, tr{
    font-weight:700;
}
p{
    color:#000;
}

  </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>
                <!-- End of Topbar -->

                <!-- Begin Page Content -->
                
                   <div class="container-fluid mt-5">
         <div class="row">
        <div class="col-sm-5">
     <h3 style="color:#060606; font-weight:700;">Customer Ledger Report</h3>
        </div>
        <div class="col-sm-4"></div>
        <div class="col-sm-3">
             
        </div>
    </div>
   <br>
   <?php
// 🔹 Fetch all customers (creditors) for the dropdown
$creditorQuery = "SELECT DISTINCT cr_name FROM credit_note ORDER BY cr_name ASC";
$creditorResult = mysqli_query($connection, $creditorQuery);
?>

        <form method="post">
            <div class="row">
              <div class="col-md-3">
    <div class="form-group">
        <label for="supplier">Customer Name:</label>
        <select class="form-control" name="supplier" required>
            <option value="">Select Customer</option>
            <?php
            if ($creditorResult && mysqli_num_rows($creditorResult) > 0) {
                while ($row = mysqli_fetch_assoc($creditorResult)) {
                    // Agar filter hua hai to selected value maintain karo
                    $selected = ($row['cr_name'] == $creditor) ? 'selected' : '';
                    echo "<option value='" . htmlspecialchars($row['cr_name']) . "' $selected>" . htmlspecialchars($row['cr_name']) . "</option>";
                }
            }
            ?>
        </select>
    </div>
</div>

            </div>

            <div class="row">
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="startDate">Start Date:</label>
                        <input type="date" class="form-control" name="startDate" required>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="endDate">End Date:</label>
                        <input type="date" class="form-control" name="endDate" required>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        
                        <button type="submit" class="btn btn-primary" name="filter" style="margin-top:30px;">
                            <i class="fas fa-filter fa-1x"></i>&nbsp;Filter</button>
                         <a href="report_recieve.php">
                             <button type="button" class="btn btn-dark btn-lg" 
                             style="margin-top:30px;"><i class="fas fa-sync-alt fa-1x"></i></button></a>
<button id="downloadExcel" class="btn btn-success " style="margin-top:30px;">Excel </button>
<button id="downloadPdf" type="button" class="btn btn-danger" style="margin-top:30px;">PDF</button>


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

        <br>
         
         <div id="table-container-wrapper">
<?php if (isset($transactions)): ?>


<?php if (!empty($customerInfo)): ?>
<table class="table table-bordered shadow-sm bg-white" >
    <thead style="background:#0A4657; color:white;">
        <tr>
            <th colspan="4" class="text-center">Customer Information</th>
        </tr>
        
        
    </thead>
    <tbody>
        <tr>
            <th colspan="4" class="text-center">Report Date: <?php echo $startDate.' To '.$endDate ?></th>
        </tr>
        <tr>
            <th style="width:30%;">ID</th>
            <td><?= htmlspecialchars($customerInfo['cr_id'] ?? '') ?></td>
            <th>Name:</th>
            <td><?= htmlspecialchars($customerInfo['cr_name'] ?? '') ?></td>
        </tr>
        <tr>
             <th>Phone:</th>
            <td><?= htmlspecialchars($customerInfo['phone_number'] ?? 'N/A') ?></td>
            <th>Address:</th>
            <td><?= htmlspecialchars($customerInfo['cr_address'] ?? '') ?></td>
        </tr>
        <tr>
            
        </tr>
   
    </tbody>
</table>
<?php endif; ?>



<table id="patientTable" class="table table-striped table-hover text-center table-sm bg-white">
<thead>
<tr class="bg-dark text-white">
    <th>Date</th>
    <th>Head</th>
    <th>Quantity</th>
    <th>Description</th>
    <th>Invoice No.</th>
    <th>Paid By</th>
    <th>Debit Amount (Rs)</th>
    <th>Credit Amount (Rs)</th>
    <th>Balance (Rs)</th>
</tr>
</thead>

<tbody>
<tr>
    <td style="color:#0A4657; font-weight:700;"><?= htmlspecialchars($startDate) ?></td>
    <td style="color:#0A4657; font-weight:700;">Opening Balance</td>
    <td>-</td>
    <td>-</td>
    <td></td>
    <td></td>

    <!-- Debit -->
    <td style="color:#0A4657; font-weight:700;">
        <?= $openingBalance > 0 ? number_format($openingBalance, 2) : '' ?>
    </td>

    <!-- Credit -->
    <td style="color:#0A4657; font-weight:700;">
        <?= $openingBalance < 0 ? number_format(abs($openingBalance), 2) : '' ?>
    </td>

    <!-- Balance -->
    <td style="color:#0A4657; font-weight:700;">
        <?= number_format($openingBalance, 2) ?>
    </td>
</tr>


<?php $totalQuantity = 0;?>
<?php foreach ($transactions as $transaction): ?>
<?php 
$positiveAmount = '';
$negativeAmount = '';

if ($transaction['amount'] > 0) {
    $balance += $transaction['amount'];
    $positiveAmount = number_format($transaction['amount'], 2);
} else {
    $balance += $transaction['amount'];
    $negativeAmount = number_format(abs($transaction['amount']), 2);
}

// 🔹 ADD THIS
if (!empty($transaction['total_qty']) && $transaction['total_qty'] > 0) {
    $totalQuantity += $transaction['total_qty'];
}

$description = $transaction['desc_name'] ?? '-';
?>


<tr style="color:#060606;">
    <td><?= htmlspecialchars($transaction['date']) ?></td>
    <td><?= htmlspecialchars($transaction['description']) ?></td>
    <td>
        <?php 
        // Show quantity only if it's greater than 0
        if ($transaction['total_qty'] > 0) {
            echo number_format($transaction['total_qty'], 0);
        } else {
            echo '-';
        }
        ?>
    </td>
    <td><?= htmlspecialchars($description) ?></td>
    <td><?= htmlspecialchars($transaction['invoice']) ?></td>
    <td><?= ucfirst(htmlspecialchars($transaction['paid_by'])) ?></td>
    <td><?= $positiveAmount ?></td>
    <td><?= $negativeAmount ?></td>
    <td><?= number_format($balance, 2) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

<table class="table bg-white">
<tfoot>
<tr>
    <th>Total Quantity:</th>
    <td><?= number_format($totalQuantity, 0) ?></td>
</tr>
<tr>
    <th>Final Balance:</th>
    <td><?= number_format($balance, 2) ?></td>
</tr>
</tfoot>
</table>



<?php endif; ?>




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

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

            <!-- Footer -->
            
            <!-- End of Footer -->

        </div>
        <!-- End of Content Wrapper -->
           
    </div>
     <?php include("common/main_ft.php");  ?>
    <!-- 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>
document.getElementById("downloadPdf").addEventListener("click", async function () {
    const { jsPDF } = window.jspdf;

    // ✅ FIX: DEFINE DATE TIME
    const now = new Date();
    const formattedDateTime = now.toLocaleDateString() + " " + now.toLocaleTimeString();

    const report = document.getElementById("table-container-wrapper");
    if (!report) {
        alert("Table not found!");
        return;
    }

    try {
        const canvas = await html2canvas(report, {
            scale: 2,
            useCORS: true
        });

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

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

        const pageWidth = pdf.internal.pageSize.getWidth();
        const pageHeight = pdf.internal.pageSize.getHeight();

        const imgWidth = pageWidth - 10;
        const imgHeight = (canvas.height * imgWidth) / canvas.width;

        let position = 30;

        /* HEADER */
        pdf.setFont("helvetica", "bold");
        pdf.setFontSize(16);
          pdf.text("BM Wholesale & Parchon Shop", 2, 12);
        pdf.setFont("helvetica", "normal");
        pdf.setFontSize(10);
        pdf.text("Address: Main Patang Chok", 2, 17);
        pdf.setFontSize(10);
        pdf.text("Phone: M.Munsif : 03397788996 | Basit : 03190097393", 2, 21);
        pdf.setFontSize(10);
        pdf.text("Email: No Email", 2, 26);

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

        pdf.addImage(imgData, "JPEG", 5, position, imgWidth, imgHeight);

        let heightLeft = imgHeight;

        while (heightLeft > pageHeight - 20) {
            heightLeft -= pageHeight;
            pdf.addPage();
            pdf.addImage(imgData, "JPEG", 5, 10 - heightLeft, imgWidth, imgHeight);
        }

        pdf.save("Customer-Ledger-Report.pdf");

    } catch (error) {
        console.error(error);
        alert("PDF generation failed");
    }
});
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.9/xlsx.full.min.js"></script>

<!-- JavaScript for exporting the table data to Excel -->
<script>
    document.getElementById('downloadExcel').addEventListener('click', function() {
        // Get the table element
        var table = document.getElementById('patientTable');

        // Clean the table to avoid potential issues with hidden rows or formatting
        var clone = table.cloneNode(true); // Clone the table
        var rows = clone.querySelectorAll('tr');

        // Remove hidden or empty rows if necessary
        rows.forEach(function(row) {
            if (row.style.display === 'none' || row.innerText.trim() === '') {
                row.remove();
            }
        });

        // Convert the table into a worksheet using SheetJS
        var workbook = XLSX.utils.table_to_book(clone, { sheet: "Patients" });

        // Export the Excel file with a proper name
        try {
            XLSX.writeFile(workbook, 'Recieveable_data.xlsx');
        } catch (error) {
            console.error("Error while writing the file: ", error);
            alert("Error generating Excel file. Please check if the SheetJS library is properly loaded.");
        }
    });
</script>
      
   <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></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>