<?php 
// Start the session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$user_id = $_SESSION['user_id'] ?? null;
$company_id = $_SESSION['company_id'] ?? null;

include('includes/dbconn.php'); // Database connection script

?>
<!DOCTYPE html>
<html lang="en">

<head>

    <?php $title = "Add Expense";
    include 'partials/title-meta.php'; ?>
    
    <!-- third party css -->
        <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet" type="text/css" />
        <link href="assets/libs/datatables.net-responsive-bs5/css/responsive.bootstrap5.min.css" rel="stylesheet" type="text/css" />
        <link href="assets/libs/datatables.net-buttons-bs5/css/buttons.bootstrap5.min.css" rel="stylesheet" type="text/css" />
        <link href="assets/libs/datatables.net-select-bs5/css//select.bootstrap5.min.css" rel="stylesheet" type="text/css" />
        <link href="assets/libs/select2/css/select2.min.css" rel="stylesheet" type="text/css" />
        <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
        <!-- third party css end -->

    <?php include 'partials/head-css.php'; ?>

</head>

<?php include 'partials/body.php'; ?>

<!-- Begin page -->
<div id="wrapper">

    <?php $pagetitle = "Add Expense";
    include 'partials/menu.php'; ?>
            
            <!-- ============================================================== -->
            <!-- Start Page Content here -->
            <!-- ============================================================== -->

            <div class="content-page">
                <div class="content">

                    <!-- Start Content-->
                    <div class="container-fluid">
                        
                        <div class="card">
                            <div class="card-body">
                                <h4 class="header-title">Expense Data Capture</h4>
                                <p class="sub-header">Capture basic expense data.</p>
                
                                <form class="needs-validation" novalidate action="save_expense.php" method="post">
                                    <div class="row">
                                        <div class="col-lg-6">
                                            <div class="mb-3">
                                                <label for="expense_name" class="form-label">Expense Name</label>
                                                <input type="text" class="form-control" id="expense_name" name="expense_name" placeholder="Expense Name" required />
                                            </div>
                                            <div class="mb-3">
                                                <label for="category" class="form-label">Expense Category</label>
                                                <select class="form-control" id="category" name="category" required>
                                                    <option>Select Category</option>
                                                    <select name="category" required>
                                                        <?php
                                                        include('includes/dbconn.php');
                                                        $company_id = $_SESSION['company_id']; // Make sure you have the company_id from the session or another source
                                                
                                                        // Fetch account names from the 'chart_of_accounts' table
                                                        $result = mysqli_query($conn, "SELECT account_id, account_name FROM chart_of_accounts WHERE company_id = '{$company_id}' AND account_type = 'Expense'");
                                                        
                                                        // Check if there are any rows
                                                        if ($result && mysqli_num_rows($result) > 0) {
                                                            // Output options for each account
                                                            while ($row = mysqli_fetch_assoc($result)) {
                                                                echo "<option value='{$row['account_id']}'>{$row['account_name']}</option>";
                                                            }
                                                        } else {
                                                            echo "<option value=''>No accounts found</option>";
                                                        }
                                                        ?>
                                                    </select>
                                                </select>
                                            </div>
                                            <div class="mb-3">
                                                <label for="expense_date" class="form-label">Expense Date</label>
                                                <input type="date" class="form-control" id="expense_date" name="expense_date" value="<?php echo date('Y-m-d'); ?>" required />
                                            </div>

                                            <div class="mb-3">
                                                <label for="description" class="form-label">Description</label>
                                                <textarea class="form-control" id="description" name="description" placeholder="Description" required></textarea>
                                            </div>
                                        </div>
                
                                        <div class="col-lg-6">
                                            <div class="mb-3">
                                                <label for="amount" class="form-label">Amount</label>
                                                <input type="text" class="form-control" id="amount" name="amount" placeholder="Amount" required />
                                            </div>
                                            <div class="mb-3">
                                                <label for="user_id" class="form-label">User</label>
                                                <input type="text" class="form-control" id="user_id" name="user_id" placeholder="User ID" value="<?php echo htmlspecialchars($user_id); ?>" readonly />
                                            </div>
                                            <div class="mb-3">
                                                <label for="company" class="form-label">Company</label>
                                                <select class="form-control" id="company" name="company_id" data-toggle="select2" required readonly>
                                                    <?php
                                                    // Assuming your db connection is still open
                                                    // Fetch company name based on the company_id from the session
                                                    $stmt = $conn->prepare("SELECT name FROM companies WHERE company_id = ?");
                                                    if (false === $stmt) {
                                                    // Handle error, possibly output $conn->error
                                                    exit('Prepare failed: ' . htmlspecialchars($conn->error));
                                                      }
                                                    $stmt->bind_param("i", $company_id);
                                                    $stmt->execute();
                                                    $result = $stmt->get_result();
                                                    if ($company = $result->fetch_assoc()) {
                                                        echo "<option value='" . htmlspecialchars($company_id) . "' selected>" . htmlspecialchars($company['name']) . "</option>";
                                                    } else {
                                                        echo "<option value='' selected>No company found</option>";
                                                    }
                                                    $stmt->close();
                                                    ?>
                                                </select>
                                            </div>
                                            <div class="mb-3">
                                                <label for="capture_date" class="form-label">Capture Date</label>
                                                <input type="text" class="form-control" id="capture_date" name="capture_date" placeholder="Capture Date" readonly />
                                            </div>
                                             
                                        </div>
                                    </div>
                
                                    <button class="btn btn-primary" type="submit">Submit form</button>
                                </form>
                
                            </div> <!-- end card-body-->
                        </div> <!-- end card-->
                        
                    </div> <!-- container -->
                    
                    <div class="row">
                            <div class="col-12">
                                <div class="card">
                                    <div class="card-body">
                                        <h4 class="mt-0 header-title">Expense List</h4>
                                        <br/>
                                        <table id="datatable-buttons" class="table table-striped table-bordered dt-responsive nowrap">
                                            <thead>
                                            <tr>
                                                <th>Expense Name</th>
                                                <th>Category</th>
                                                <th>Expense Date</th>
                                                <th>Description</th>
                                                <th>Amount</th>
                                                <th>Capture Date</th>
                                                <th>Actions</th>
                                            </tr>
                                            </thead>
    
    
                                            <tbody>
                                                <?php
                                                include('includes/dbconn.php');
                                            
                                                // Fetch data from the 'clients' table
                                                $result = mysqli_query($conn, "SELECT * FROM expenses");
                                            
                                                // Assuming $user_level is defined and contains the user's level
                                                $user_level = 9; // Example user level for admin
                                            
                                                // Loop through the result set and populate the table
                                                while ($row = mysqli_fetch_assoc($result)) {
                                                    echo "<tr>";
                                                    echo "<td>" . $row['expense_name'] . "</td>";
                                                    echo "<td>" . $row['category'] . "</td>";
                                                    echo "<td>" . $row['expense_date'] . "</td>";
                                                    echo "<td>" . $row['description'] . "</td>";
                                                    echo "<td>" . $row['amount'] . "</td>";
                                                    echo "<td>" . $row['capture_date'] . "</td>";
                                            
                                                    // Check if user has sufficient level (assuming you have user authentication)
                                                    if ($user_level >= 9) {
                                                        echo "<td class='text-center'>
                                                                  <ul class='list-inline me-auto mb-0'>
                                                                      <li class='list-inline-item align-bottom' data-bs-toggle='tooltip' title='Edit'>
                                                                          <a href='edit_expense.php?id=" . $row['expense_id'] . "' class='avtar avtar-xs btn-link-secondary btn-pc-default'>
                                                                              <i class='ti ti-pencil f-18'></i>
                                                                          </a>
                                                                      </li>
                                                                      <li class='list-inline-item align-bottom' data-bs-toggle='tooltip' title='View'>
                                                                          <a href='view_expense.php?id=" . $row['expense_id'] . "' class='avtar avtar-xs btn-link-secondary btn-pc-default'>
                                                                              <i class='ti ti-eye f-18'></i>
                                                                          </a>
                                                                      </li>
                                                                      <li class='list-inline-item align-bottom' data-bs-toggle='tooltip' title='Delete'>
                                                                          <a href='delete_expense.php?id=" . $row['expense_id'] . "' class='avtar avtar-xs btn-link-danger btn-pc-default'>
                                                                              <i class='ti ti-trash f-18'></i>
                                                                          </a>
                                                                      </li>
                                                                  </ul>
                                                              </td>";
                                                    } else {
                                                        // If user level is not sufficient, display a placeholder or message
                                                        echo "<td class='text-center'>Insufficient Privileges</td>";
                                                    }
                                            
                                                    echo "</tr>";
                                                }
                                            
                                                // Close the result set and connection
                                                mysqli_free_result($result);
                                                mysqli_close($conn);
                                                ?>
                                            </tbody>



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

                </div> <!-- content -->

                <?php include 'partials/footer.php'; ?>

            </div>

            <!-- ============================================================== -->
            <!-- End Page content -->
            <!-- ============================================================== -->


        </div>
        <!-- END wrapper -->

        <?php include 'partials/right-sidebar.php'; ?>

        <?php include 'partials/footer-scripts.php'; ?>

        <!-- Plugin js-->
        <script src="assets/libs/parsleyjs/parsley.min.js"></script>

        <!-- Validation init js-->
        <script src="assets/js/pages/form-validation.init.js"></script>

        <!-- App js -->
        <script src="assets/js/app.min.js"></script>
        <!-- third party js -->
        <script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
        <script src="assets/libs/datatables.net-bs5/js/dataTables.bootstrap5.min.js"></script>
        <script src="assets/libs/datatables.net-responsive/js/dataTables.responsive.min.js"></script>
        <script src="assets/libs/datatables.net-responsive-bs5/js/responsive.bootstrap5.min.js"></script>
        <script src="assets/libs/datatables.net-buttons/js/dataTables.buttons.min.js"></script>
        <script src="assets/libs/datatables.net-buttons-bs5/js/buttons.bootstrap5.min.js"></script>
        <script src="assets/libs/datatables.net-buttons/js/buttons.html5.min.js"></script>
        <script src="assets/libs/datatables.net-buttons/js/buttons.flash.min.js"></script>
        <script src="assets/libs/datatables.net-buttons/js/buttons.print.min.js"></script>
        <script src="assets/libs/datatables.net-keytable/js/dataTables.keyTable.min.js"></script>
        <script src="assets/libs/datatables.net-select/js/dataTables.select.min.js"></script>
        <script src="assets/libs/pdfmake/build/pdfmake.min.js"></script>
        <script src="assets/libs/pdfmake/build/vfs_fonts.js"></script>
        <script src="assets/libs/selectize/js/standalone/selectize.min.js"></script>
        <script src="assets/libs/mohithg-switchery/switchery.min.js"></script>
        <script src="assets/libs/multiselect/js/jquery.multi-select.js"></script>
        <script src="assets/libs/select2/js/select2.min.js"></script>
        <script src="assets/libs/jquery-mockjax/jquery.mockjax.min.js"></script>
        <script src="assets/libs/devbridge-autocomplete/jquery.autocomplete.min.js"></script>
        <script src="assets/libs/bootstrap-touchspin/jquery.bootstrap-touchspin.min.js"></script>
        <script src="assets/libs/bootstrap-maxlength/bootstrap-maxlength.min.js"></script>
        <!-- third party js ends -->

        <!-- Datatables init -->
        <script>
            $(document).ready(function() {
                $('#category').select2();
            });
        </script>
        <script>
            $(document).ready(function() {
                $('#datatable-buttons').DataTable({
                    "responsive": true,
                    "lengthChange": false,
                    "autoWidth": false,
                    "buttons": ["copy", "excel", "pdf", "colvis"]
                }).buttons().container().appendTo('#datatable-buttons_wrapper .col-md-6:eq(0)');
            });
        </script>
        <script>
            // Get today's date
            var today = new Date();
        
            // Format it as YYYY-MM-DD (which is the format commonly used in databases)
            var formattedDate = today.toISOString().substr(0, 10);
        
            // Set the default value of the input field to today's date
            document.getElementById("capture_date").value = formattedDate;
        </script>

        
    </body>
</html>