<?php
include("db/cn.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();

$transactions = [];
$totalBalance = 0;
$supplierName = '';
$startDate = '';
$endDate = '';

if (isset($_POST['filter'])) {
    $supplierName = $_POST['supplier'];
    $startDate = $_POST['startDate'];
    $endDate = $_POST['endDate'];

    // Helper function to validate and format dates
    function isValidDate($dateString) {
        // Check for '0000-00-00' or '00-00-0000' or similar invalid dates
        if (empty($dateString) || $dateString == '0000-00-00 00:00:00' || $dateString == '0000-00-00' || $dateString == '00-00-0000') {
            return false;
        }

        // Check if the date can be converted to a valid timestamp
        $timestamp = strtotime($dateString);
        if ($timestamp === false || $timestamp == strtotime('01-01-1970')) {
            return false;
        }

        return true;
    }

    // Helper function to format the date for display
    function formatDateForDisplay($dateString) {
        if (isValidDate($dateString)) {
            return date("d-m-Y", strtotime($dateString)); // Change display format here
        }
        return ''; // Return empty string if date is invalid
    }

    // Get supplier opening balance (within the date range)
    $query = "SELECT open_amount AS amount, date_time 
              FROM supplier_opening_amount 
              WHERE supplier_name = '$supplierName' 
              AND date_time BETWEEN '$startDate' AND '$endDate'";
    $result = mysqli_query($connection, $query);
    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $openingBalance = $row['amount'];
        $date_time = $row['date_time'];

        // Check for valid date before processing
        if (isValidDate($date_time)) {
            $totalBalance += $openingBalance;
            $transactions[] = [
                'date' => formatDateForDisplay($date_time),
                'description' => 'Opening Balance',
                'amount' => $openingBalance,
                'type' => 'balance'
            ];
        }
    }

    // Get cash-like purchases (do not affect total balance)
    $query = "SELECT discount_amount AS amount, date_time, paid_by 
              FROM purchase 
              WHERE customer_name = '$supplierName' AND paid_by IN ('Cash', 'Bank1', 'Bank2', 'Bank3', 'Others') 
              AND date_time BETWEEN '$startDate' AND '$endDate'
              GROUP BY inv_id";
    $result = mysqli_query($connection, $query);
    while ($row = mysqli_fetch_assoc($result)) {
        $date_time = $row['date_time'];

        // Check for valid date before processing
        if (isValidDate($date_time)) {
            $transactions[] = [
                'date' => formatDateForDisplay($date_time),
                'description' => $row['paid_by'] . ' Purchase',
                'amount' => $row['amount'],
                'type' => 'no_effect'
            ];
        }
    }

    // Get credit purchases (affect total balance as debit)
    $query = "SELECT discount_amount AS amount, date_time 
              FROM purchase 
              WHERE customer_name = '$supplierName' AND paid_by = 'Credit' 
              AND status = '' AND date_time BETWEEN '$startDate' AND '$endDate'
              GROUP BY inv_id";
    $result = mysqli_query($connection, $query);
    while ($row = mysqli_fetch_assoc($result)) {
        $date_time = $row['date_time'];

        // Check for valid date before processing
        if (isValidDate($date_time)) {
            $transactions[] = [
                'date' => formatDateForDisplay($date_time),
                'description' => 'Credit Purchase',
                'amount' => -$row['amount'],
                'type' => 'debit'
            ];
            $totalBalance += $row['amount'];
        }
    }

    // Get payments made to supplier (affect total balance as credit)
    $query = "SELECT supplier_amount AS amount, date_time 
              FROM supplier_paid 
              WHERE supplier_name = '$supplierName' 
              AND date_time BETWEEN '$startDate' AND '$endDate'";
    $result = mysqli_query($connection, $query);
    while ($row = mysqli_fetch_assoc($result)) {
        $date_time = $row['date_time'];

        // Check for valid date before processing
        if (isValidDate($date_time)) {
            $transactions[] = [
                'date' => formatDateForDisplay($date_time),
                'description' => 'Payment to Supplier',
                'amount' => $row['amount'],
                'type' => 'credit'
            ];
            $totalBalance -= $row['amount'];
        }
    }

    // Get purchase returns (affect total balance as credit only if 'paid_by' is 'Credit')
    $query = "SELECT discount_amount AS amount, date_time 
              FROM purchase 
              WHERE customer_name = '$supplierName' AND paid_by = 'Credit'  
              AND status = 'return' AND date_time BETWEEN '$startDate' AND '$endDate'
              GROUP BY r_inv_id";
    $result = mysqli_query($connection, $query);
    while ($row = mysqli_fetch_assoc($result)) {
        $date_time = $row['date_time'];

        // Check for valid date before processing
        if (isValidDate($date_time)) {
            $transactions[] = [
                'date' => formatDateForDisplay($date_time),
                'description' => 'Purchase Return',
                'amount' => -$row['amount'],
                'type' => 'credit'
            ];
            $totalBalance -= $row['amount'];
        }
    }

    // Sort transactions by date
    usort($transactions, function($a, $b) {
        return strtotime($a['date_time']) - strtotime($b['date_time']);
    });
}
?>


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Supplier Report</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link rel="stylesheet" href="css/custom_css.css" />
</head>
<style>
 #table-container-wrapper {
    max-height: 460px; /* Adjust the maximum height as needed */
    overflow-y: auto; /* Enable vertical scroll when content overflows */
}


@media (max-width: 880px) {
    .col-4 {
        width: 33.33% !important;
    }
    .fa-wifi {
        display: none !important;
    }
    .col-6 {
        width: 50% !important;
    }
}

@media (min-width: 880px) {
    .sidebar {
        width: 100%;
        /* Change sidebar width to 100% on mobile */
        max-width: 120px; /* Set maximum width for the sidebar */
    }
}

@media (min-width: 880px) {
    .main-content {
        margin-left: ; /* Width of the sidebar */
    }
}

/* Added new class to control overlay */
.overlay {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.6);
    z-index: 999;
    display: none; /* Initially hidden */
} /* Custom styles for sidebar */
    .sidebar {
        width: 100px;
        background: linear-gradient(180deg, #3C2F23, #060606);
        position: fixed;
        bottom: 0;
        top: 60px;
        transition: transform 0.3s ease-in-out;
        transform: translateX(0);
        z-index: 1;
        height: 100%;
        border-radius: 0px;
		   transition: transform 0.3s ease-in-out, width 0.3s ease-in-out;
    }

    .sidebar.hide {
        transform: translateX(-100px);
        /* Move sidebar out of the viewport when it is hidden */
    }

    .sidebar .nav-item {
        padding: 10px 0;
        text-align: center;
        position: relative;
        font-size: 12px;
    }

    .sidebar .nav-link {
        color: #fff;
        position: relative;
        /* Ensure icon and text are positioned relative to the nav link */
        z-index: 2;
        /* Ensure the text and icon are above the hover background */
    }

    .sidebar .nav-link i {
        margin-bottom: 5px;
        /* Adjust the margin of the icon */
    }

    /* Custom styles for hover effect */
    .sidebar .nav-item:hover:after {
        background-color: #fff;
        content: '';
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 100%;
        z-index: 1;
        /* Ensure the hover background is below the text and icon */
    }

    .sidebar .nav-item:hover .nav-link {
        color: #503F2E;
    }

    /* Custom styles for divider */
    .sidebar .nav-item:after {
        content: "";
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 1px;
        background-color: #fff;
        transition: height 0.3s ease-in-out;
        /* Transition effect for smooth animation */
    }

    /* Custom styles for header */
 .header {
		
       background: linear-gradient(100deg, #3C2F23, #060606);
        color: #fff;
        padding: 10px;
        position: fixed;
        top: 0;
        width: 100%;
        z-index: 2;
        height: 69px;
        box-shadow: #FFF 2px 0px 0px 0px;
        /* Ensure header appears above sidebar */
    }

    .header .navbar-toggler {
        color: #fff;
    }

    .header .navbar-toggler-icon {
        color: #fff;
        /* Set the color of the toggle button to white */
    }

    .header .navbar-toggler.white {
        color: #fff !important;
        /* Ensure the toggle button is white */
    }

    .header .navbar-brand {
        color: #fff;
        /* Set navbar brand text color to white */
    }

    .header .nav-item .nav-link {
        color: #fff;
        /* Set nav link text color to white */
    }

.main-content {
    margin-top: 50px; /* Height of fixed header */
    margin-left: 70px; /* Initially, set margin-left to 0 */
    padding-top: 30px; /* Height of fixed header */
    transition: margin-left 0.3s ease-in-out; /* Add transition for smoother animation */
}


    /* Custom styles for search bar */
    .search-container {
        display: flex;
        align-items: center;
       width:100%;
        margin: 2px auto;


        float:left;
	}

/* Updated hide class to apply to the overlay */
.sidebar.hide, .overlay.hide {
    transform: translateX(-100%);
}

    .search-input {
        width: 100%;
        padding: 10px 30px 10px 10px;
        /* Adjust padding to accommodate the icon */
        border: 1px solid #ccc;
        border-radius: 20px;
        font-size: 16px;
    }

    .search-icon {
        position: relative;
        left: -25px;
        /* Adjust the position of the icon */
        color: #aaa;
    }

    .search-icon i {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
    }    .btn-dark {
        background: #503F2E;
        color: #fff;
        border: 1px solid #503F2E;
    }

    .btn-dark:hover {
        background: #fff;
        color: #503F2E;
        border: 1px solid #503F2E;
    }

    .bg-dark2 {
        background: #503F2E;
        color: #fff;
    }


    .modal-content {
        animation: modal-animation 0.5s;
    }

    @keyframes modal-animation {
        from {
            opacity: 0;
            transform: scale(0.8);
        }

        to {
            opacity: 1;
            transform: scale(1);
        }
    }	
    		.card {
    transition: all 0.3s ease-in-out;
    padding:10px;
}

.card:hover {
    background: #503F2E;
    color: #fff;
    box-shadow: 0 0 15px rgba(60, 47, 35, 0.7); /* Soft glow effect with color #1A5319 and opacity */
    border-radius: 10px;
	border:1px solid #fff;
	
}
	
</style>
<body>

    <?php include("common/hd.php");?>
    <?php include("common/sd.php");
	
	$supplierQuery = "SELECT DISTINCT supplier_name FROM supplier";
                                $supplierResult = mysqli_query($connection, $supplierQuery);
	 ?>
  <div class="main-content">
        <div class="container mt-5">
            <div class="row">
        <div class="col-sm-3">
     <h3 style="width:405px; height:66px; text-align:center; background:#503F2E; color:#fff; padding:12px; border-radius:10px;">Supplier Report</h3>
        </div>
        <div class="col-sm-6"></div>
        <div class="col-sm-3">
             <a href="report_p.php" class="btn btn-dark" style="margin-top:10px;float:right;">Back</a>
        </div>
    </div>
       <br>
            <form method="post">
                <div class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="supplier">Supplier Name:</label>
                            <select class="form-control" name="supplier" required style="text-transform:capitalize;">
                                <option value="">Select Supplier</option>
                                <!-- Populate suppliers from the database -->
                                <?php
                                
                                while ($supplierRow = mysqli_fetch_assoc($supplierResult)) {
         echo '<option value="' . $supplierRow['supplier_name'] . '">' . $supplierRow['supplier_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" value="<?php echo $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" value="<?php echo $endDate; ?>" required>
                        </div>
                    </div>
                    <div class="col-md-4">
                    <div class="form-group">
                        
                        <button type="submit" class="btn btn-dark" name="filter" style="margin-top:30px;">Filter</button>
                         <a href="report_supplier.php"><button type="button" class="btn btn-dark"  style="margin-top:30px;"><i class="fas fa-sync-alt fa-1x"></i></button></a>
<button id="downloadExcel" class="btn btn-dark " style="margin-top:30px;">Download </button>


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

                <?php if (!empty($transactions)) : ?>
                    <h3 style="background:#503F2E; color:#fff;padding:20px; border-radius:10px;text-align:center;text-transform:capitalize;">Supplier Ledger Report for: <?php echo $supplierName; ?>, from<br> <?php echo date('d-m-Y', strtotime($startDate)); ?> to <?php echo date('d-m-Y', strtotime($endDate)); ?></h3>

                    <div class="row">
                        <div class="col-sm-12" id="table-container-wrapper">
                            <table id="patientTable" class="table table-striped table-hover text-center table-sm">
                                <thead>
                                    <tr class="bg-dark text-white">
                                        <th>Date</th>
                                        <th>Description</th>
                                        <th>Amount(Rs)</th>
                                        <th>Balance(Rs)</th>
                                    </tr>
                                </thead>
                                <tbody>
    <?php 
    // Set initial balance from the opening balance
    $runningBalance = $openingBalance; 
    ?>
    <tr>
        <td><?php echo date('Y-m-d', $openingBalanceDate); ?></td>
        <td>Opening Balance</td>
        <td><?php echo number_format($openingBalance, 2); ?></td>
        <td><?php echo number_format($runningBalance, 2); ?></td>
    </tr>
    <?php 
    // Iterate over each transaction to update the running balance
    foreach ($transactions as $transaction) : 
        // Adjust balance based on the transaction type
        if ($transaction['type'] == 'debit') {
            $runningBalance += abs($transaction['amount']);
        } elseif ($transaction['type'] == 'credit') {
            $runningBalance -= abs($transaction['amount']);
        }
    ?>
        <tr>
            <td><?php echo date('d-m-Y', strtotime($transaction['date'])); ?></td>
            <td style="text-transform:capitalize;"><?php echo $transaction['description']; ?></td>
            <td><?php echo number_format(abs($transaction['amount']), 2); ?></td>
            <td>
                <?php 
                // Display balance for transactions that affect it.
                if (in_array($transaction['type'], ['debit', 'credit'])) {
                    echo number_format($runningBalance, 2);
                } else {
                    echo number_format($runningBalance, 2); // Display '-' for transactions that don't affect the balance
                }
                ?>
            </td>
        </tr>
    <?php endforeach; ?>
</tbody>

                            </table>
                        </div>

                        <div class="col-sm-12">
                            <table class="table">
                                <tfoot>
                                    <tr>
                                        <th>Final Balance:</th>
                                        <td><?php echo number_format($totalBalance, 2); ?></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                <?php else : ?>
                    <?php if (isset($_POST['filter'])) : ?>
                        <div class="alert alert-warning">
                            No records found for the selected supplier and date range.
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </form>
        </div>
    </div>

</body>
<!-- Include the SheetJS (xlsx) library -->
<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, 'Supplier_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>
</html>