<?php
include("../db/cn.php");
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Check if session data exists
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'];
}

$startDate = isset($_POST['startDate']) ? $_POST['startDate'] : null;
$endDate = isset($_POST['endDate']) ? $_POST['endDate'] : null;

// Function to apply date filter and sort by date_time
function add_date_filter($query, $startDate, $endDate) {
    if (stripos($query, 'GROUP BY') !== false) {
        $parts = preg_split('/GROUP BY/i', $query);
        $baseQuery = trim($parts[0]);
        $groupByClause = 'GROUP BY ' . trim($parts[1]);

        if ($startDate && $endDate) {
            if (stripos($baseQuery, 'WHERE') !== false) {
                $baseQuery .= " AND date_time BETWEEN '$startDate' AND '$endDate'";
            } else {
                $baseQuery .= " WHERE date_time BETWEEN '$startDate' AND '$endDate'";
            }
        }
        return $baseQuery . ' ' . $groupByClause . " ORDER BY date_time ASC";
    } else {
        if ($startDate && $endDate) {
            if (stripos($query, 'WHERE') !== false) {
                $query .= " AND date_time BETWEEN '$startDate' AND '$endDate'";
            } else {
                $query .= " WHERE date_time BETWEEN '$startDate' AND '$endDate'";
            }
        }
        return $query . " ORDER BY date_time ASC";
    }
}

// Define the missing function to get the previous closing balance
function get_previous_closing_balance($connection, $startDate) {
    $balance = 0;
    $queries = [
        "SELECT SUM(loan_amount) AS amount FROM loan WHERE paid = 'bank1' && date_time < '$startDate'",
        "SELECT SUM(amount_i) AS amount FROM transfer WHERE from_i = 'bank1' && date_time < '$startDate'",
        "SELECT SUM(amount_i) AS amount FROM transfer WHERE to_i = 'bank1' && date_time < '$startDate'",
        "SELECT SUM(amount) AS amount FROM withdraw WHERE paid_by = 'bank1' && date_time < '$startDate'",
        "SELECT SUM(open_cash) AS amount FROM bank1_opening WHERE date_time < '$startDate'",
        "SELECT SUM(discount_amount) AS amount FROM log_user_sales WHERE paid_by = 'bank1' AND date_time < '$startDate'",
        "SELECT SUM(total_amount) AS amount FROM order_detail WHERE  paid_by = 'bank1' && order_status = 'refund' AND date_time < '$startDate'",
        "SELECT SUM(discount_amount) AS amount FROM purchase WHERE paid_by = 'bank1' AND status = 'Purchase_Return'  AND date_time < '$startDate' ",
        "SELECT SUM(amount) AS amount FROM incash WHERE paid_by = 'bank1' &&  date_time < '$startDate'",
        "SELECT SUM(amount) AS amount FROM credit_paid WHERE paid_by = 'bank1' AND date_time < '$startDate'",
        "SELECT SUM(supplier_amount) AS amount FROM supplier_paid WHERE status = 'bank1' AND date_time < '$startDate'",
        "SELECT SUM(discount_amount) AS amount FROM purchase WHERE paid_by = 'bank1' AND r_inv_id = '' AND date_time < '$startDate'"
    ];

    foreach ($queries as $query) {
        $result = mysqli_query($connection, $query);
        if ($result) {
            $row = mysqli_fetch_assoc($result);
            $amount =floatval($row['amount']);
            if (stripos($query, 'incash') !== false || stripos($query, 'credit_paid') !== false || stripos($query, 'supplier_paid') !== false) {
                $balance -= $amount; // Subtract outgoing cash
            } else {
                $balance += $amount; // Add incoming cash
            }
        }
    }

    return $balance;
}

// Define the get_opening_balance() function to retrieve the balance from previous transactions
function get_opening_balance($connection, $startDate) {
    return get_previous_closing_balance($connection, $startDate);
}

// Fetch and combine all transactions
$combinedData = [];
$queries = [
    
    'Opening Cash' => add_date_filter("SELECT open_cash AS amount, date_time FROM bank1_opening", $startDate, $endDate),
    'Sale Cash' => add_date_filter("SELECT discount_amount AS amount, date_time FROM log_user_sales WHERE paid_by = 'bank1' GROUP BY order_id", $startDate, $endDate),
    'Refund Cash' => add_date_filter("SELECT total_amount AS amount, date_time FROM order_detail WHERE order_status = 'refund' && paid_by = 'bank1'  GROUP BY order_id", $startDate, $endDate),
    'Purchase Return' => add_date_filter("SELECT discount_amount AS amount, date_time FROM purchase WHERE paid_by = 'bank1' AND status = 'Purchase_Return' GROUP BY r_inv_id", $startDate, $endDate),
    'Expense Cash' => add_date_filter("SELECT amount, date_time FROM incash where paid_by = 'bank1'", $startDate, $endDate),
    'Credit Recieved' => add_date_filter("SELECT amount, date_time FROM credit_paid WHERE paid_by = 'bank1'", $startDate, $endDate),
    'Supplier Paid' => add_date_filter("SELECT supplier_amount AS amount, date_time FROM supplier_paid WHERE status = 'bank1'", $startDate, $endDate),
    'loan Cash' => add_date_filter("SELECT loan_amount AS amount, date_time FROM loan WHERE paid = 'bank1'", $startDate, $endDate),
        'Transfer Cash' => add_date_filter("SELECT amount_i AS amount, date_time FROM transfer where from_i = 'bank1'", $startDate, $endDate),
     'Recieve Cash' => add_date_filter("SELECT amount_i AS amount, date_time FROM transfer where to_i = 'bank1'", $startDate, $endDate),
    'Withdraw Cash' => add_date_filter("SELECT amount, date_time FROM withdraw where paid_by = 'bank1'", $startDate, $endDate),
    'Purchase Cash' => add_date_filter("SELECT discount_amount AS amount, date_time FROM purchase WHERE paid_by = 'bank1' AND r_inv_id = '' GROUP BY inv_id", $startDate, $endDate),
];

foreach ($queries as $description => $query) {
    $result = mysqli_query($connection, $query);
    if ($result) {
        while ($row = mysqli_fetch_assoc($result)) {
            $row['description'] = $description;
            $combinedData[] = $row;
        }
    }
}

// Sort the combined data by date_time
usort($combinedData, function ($a, $b) {
    return strtotime($a['date_time']) - strtotime($b['date_time']);
});

// Calculate daily opening balances and update balances for each day
$currentDate = null;
$currentBalance = get_opening_balance($connection, $startDate); // Get opening balance from previous transactions
$dailyData = [];

foreach ($combinedData as $transaction) {
    $transactionDate = date('Y-m-d', strtotime($transaction['date_time']));
    
    // Check if the date has changed (new day)
    if ($currentDate !== $transactionDate) {
        // Display the opening balance for the new day
        $dailyData[] = [
            'date_time' => $transactionDate,
            'description' => 'Opening Balance',
            'amount' => 'N/A',
            'balance' => number_format($currentBalance, 2)
        ];
        $currentDate = $transactionDate;
    }
    
    // Update the balance with the current transaction amount
    $currentBalance += floatval($transaction['amount']);
    
    // Update the transaction with the new balance
    $transaction['balance'] = number_format($currentBalance, 2);
    $dailyData[] = $transaction;
}

// Output the daily data (this part depends on how you're displaying the data in HTML, so adjust accordingly)
ob_end_flush();



	if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['open_add'])){
	    
    	$open_cash = $_POST["amount"];
        $date_time = date("Y-m-d");
    	$date_timenew = date("Y-m-d");
    	mysqli_query($connection,"insert into bank1_opening(open_cash,login_user,user_role,outlet_name,outlet_address,date_time)
    	values('".$open_cash."','".$userName."','".$userRole."','".$outlet_name."','".$outlet_address."','".$date_time."')");
    	
    	echo "<script type='text/javascript'>window.location.href = 'report_bank.php';</script>";
	}

?>



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Daily Cash Book</title>
    <!-- Bootstrap CSS -->
    <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: 660px; /* 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(360deg, #060606, #3C2F23);
        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: #0A5064;
    }

    /* 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(90deg, #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);
        }
    }	
</style>

</style>
<body>
<?php include("common/hd.php");?>
<?php include("common/sd.php"); ?>

<div class="main-content">
<div class="container mt-5">
    <form method="post">
        <h2 class="mb-2">Bank 1 Book</h2>
        <div class="row">
            <div class="col-md-3">
                <label for="startDate">Start Date:</label>
                <input type="date" class="form-control" name="startDate" value="<?= $startDate ?>">
            </div>
            <div class="col-md-3">
                <label for="endDate">End Date:</label>
                <input type="date" class="form-control" name="endDate" value="<?= $endDate ?>">
            </div>
            <div class="col-md-1">
                <br>
                <button type="submit" class="btn btn-dark" style="margin-top:5px;" name="filter">Filter</button>
            </div>
            
            <div class="col-sm-5">
                
                <a href="report_all.php"><button type="button" class="btn btn-dark " style="margin-top:30px;" ><i class="fas fa-arrow-left fa-1x"></i></button>
                </a>
               
                <a href="report_bank.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>
                <button type="button" class="btn btn-dark "  data-toggle="modal"  style="margin-top:30px;" data-target="#addWithdrawModal">
                Add Opening Amount</button>
            </div>
        </div>
        
        <div id="table-container-wrapper" class="mt-4">
            <table id="patientTable" class="table table-stripped table-hover text-center table-sm">
                <thead class="bg-dark text-white">
                    <tr>
                        <th>Date</th>
                        <th>Description</th>
                        <th>Amount (Rs)</th>
                        <th>Balance (Rs)</th>
                    </tr>
                </thead>
                <tbody>
                <?php
// Display the transactions with updated balances
$previousDate = null;
$balance = get_previous_closing_balance($connection, $startDate);

foreach ($combinedData as $data) {
    $currentDate = date('Y-m-d', strtotime($data['date_time']));

    if ($previousDate !== $currentDate) {
        echo "<tr><td>$currentDate</td><td>Opening Balance</td><td></td><td> " . number_format(floatval($balance), 2) . "</td></tr>";
        $previousDate = $currentDate;
    }

   if (stripos($data['description'], 'Expense') !== false || 
        stripos($data['description'], 'Supplier') !== false || 
        stripos($data['description'], 'Withdraw') !== false || 
        stripos($data['description'], 'loan') !== false || 
         stripos($data['description'], 'Transfer') !== false || 
         stripos($data['description'], 'Purchase Cash') !== false ||
        stripos($data['description'], 'Refund') !== false) {
        $balance -= floatval($data['amount']);
    } else {
        // For other types, like sales or credits, increase the balance
        $balance += floatval($data['amount']);
    }

    echo "<tr>
            <td>{$currentDate}</td>
            <td>{$data['description']}</td>
            <td> " . number_format(floatval($data['amount']), 2) . "</td>
            <td> " . number_format(floatval($balance), 2) . "</td>
          </tr>";
}
?>
                </tbody>
            </table>
        </div>
    </form>
</div>

<div class="modal fade" id="addWithdrawModal" tabindex="-1" role="dialog" 
            aria-labelledby="addWithdrawModalLabel" aria-hidden="true" style="margin-top:80px;">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title text-capitalize" id="addWithdrawModalLabel">Add Opening Amount</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <!-- Form for adding purchase -->
                            <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
                               <input type="text" name="amount" placeholder="Amount" class="form-control" />
                                 <br>
                                <button type="submit"  class="btn btn-dark" name="open_add">Enter</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
</div>

</body>
</html>
<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, 'Bank_1_report.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://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, 'Sales_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://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script>
    $(document).ready(function(){
        $("#searchInput").on("keyup", function() {
            var value = $(this).val().toLowerCase();
            $("table tr").filter(function() {
                // Exclude header row from filtering
                if (!$(this).hasClass('header-row')) {
                    $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
                }
            });
        });
    });
	
	
document.addEventListener("DOMContentLoaded", function () {
    var sidebar = document.getElementById("sidebar");
    var overlay = document.createElement("div");
    overlay.classList.add("overlay");
    document.body.appendChild(overlay);

    function toggleSidebar() {
        sidebar.classList.toggle("hide");
        overlay.classList.toggle("hide");

        var mainContent = document.querySelector(".main-content");
        if (sidebar.classList.contains("hide")) {
            mainContent.style.marginLeft = "0";
        } else {
            mainContent.style.marginLeft = "100px"; // Width of the sidebar
        }
    }

    overlay.addEventListener("click", function () {
        toggleSidebar();
    });

    // Add toggle functionality to navbar toggler
    var navbarToggler = document.querySelector(".navbar-toggler");
    navbarToggler.addEventListener("click", function () {
        toggleSidebar();
    });

    // Automatically hide sidebar on all screen sizes
    // sidebar.classList.add("hide");
    // overlay.classList.add("hide");
    
    // Add class to body to prevent scrolling when sidebar is open
    // document.body.classList.add("noscroll");

    // Check if screen size is larger than a certain threshold (e.g., 768px for desktop screens)
    function checkScreenSize() {
        if (window.innerWidth > 768) {
            sidebar.classList.remove("hide");
            overlay.classList.remove("hide");
        } else {
            sidebar.classList.add("hide");
            overlay.classList.add("hide");
        }
    }

    // Check screen size on initial load and whenever the window is resized
    checkScreenSize();
    window.addEventListener("resize", checkScreenSize);
});
 
</script>
</body>
</html>