<?php
session_start();

// Redirect to login page if user is not logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: auth-login.php");
    exit;
}

$companyId = $_SESSION['company_id'];

// Include your database connection file
include 'includes/dbconn.php';

// Initialize the variables
$totalRevenue = 0;
$salesAnalytics = 0;
$statistics = 0;

// Fetch total revenue
$totalRevenueQuery = "SELECT SUM(total_amount) AS total_revenue FROM invoices WHERE DATE(due_date) = CURDATE()";
$totalRevenueResult = $conn->query($totalRevenueQuery);
if ($totalRevenueResult && $totalRevenueResult->num_rows > 0) {
    $row = $totalRevenueResult->fetch_assoc();
    $totalRevenue = $row['total_revenue'];
}

// Fetch sales analytics data
$salesAnalyticsQuery = "SELECT SUM(total_amount) AS sales_today FROM invoices WHERE DATE(due_date) = CURDATE()";
$salesAnalyticsResult = $conn->query($salesAnalyticsQuery);
if ($salesAnalyticsResult && $salesAnalyticsResult->num_rows > 0) {
    $row = $salesAnalyticsResult->fetch_assoc();
    $salesAnalytics = $row['sales_today'];
}

// Fetch statistics
$statisticsQuery = "SELECT COUNT(*) AS total_sales FROM invoices WHERE DATE(due_date) = CURDATE()";
$statisticsResult = $conn->query($statisticsQuery);
if ($statisticsResult && $statisticsResult->num_rows > 0) {
    $row = $statisticsResult->fetch_assoc();
    $statistics = $row['total_sales'];
}

// Close the connection
$conn->close();
?>



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

<head>

    <?php $title = "Dashboard";
    include 'partials/title-meta.php'; ?>

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

</head>

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

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


    <?php $pagetitle = "Dashboard"; include 'partials/menu.php';  ?>


    <!-- ============================================================== -->
    <!-- Start Page Content here -->
    <!-- ============================================================== -->

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

            <!-- Start Content-->
            <div class="container-fluid">

                <div class="row">

                    <div class="col-xl-3 col-md-6">
                        <div class="card">
                            <div class="card-body">
                                <h4 class="header-title mt-0 mb-4">Total Revenue</h4>
                                <div class="widget-chart-1">
                <div class="widget-detail-1 text-end">
                    <h2 class="fw-normal pt-2 mb-1"> <?php echo number_format((float)$totalRevenue, 2, '.', ''); ?> </h2>
                    <p class="text-muted mb-1">Revenue today</p>
                </div>
            </div>
                            </div>
                        </div>
                    </div><!-- end col -->

                    <div class="col-xl-3 col-md-6">
                        <div class="card">
                            <div class="card-body">

                                <h4 class="header-title mt-0 mb-3">Sales Analytics</h4>

                                <div class="widget-box-2">
                                    <div class="widget-detail-2 text-end">
                                        <span class="badge bg-success rounded-pill float-start mt-3">32% <i class="mdi mdi-trending-up"></i> </span>
                                        <h2 class="fw-normal mb-1"> 8451 </h2>
                                        <p class="text-muted mb-3">Revenue today</p>
                                    </div>
                                    <div class="progress progress-bar-alt-success progress-sm">
                                        <div class="progress-bar bg-success" role="progressbar" aria-valuenow="77" aria-valuemin="0" aria-valuemax="100" style="width: 77%;">
                                            <span class="visually-hidden">77% Complete</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div><!-- end col -->

                    <div class="col-xl-3 col-md-6">
                        <div class="card">
                            <div class="card-body">

                                <h4 class="header-title mt-0 mb-4">Statistics</h4>

                                <div class="widget-chart-1">
                                    <div class="widget-detail-1 text-end">
                                        <h2 class="fw-normal pt-2 mb-1"> <?php echo number_format($statistics); ?> </h2>
                                        <p class="text-muted mb-1">Sales today</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div><!-- end col -->

                    <div class="col-xl-3 col-md-6">
                        <div class="card">
                            <div class="card-body">

                                <h4 class="header-title mt-0 mb-3">Daily Sales</h4>

                                <div class="widget-box-2">
                                    <div class="widget-detail-2 text-end">
                                        <h2 class="fw-normal mb-1"> <?php 
                                        echo number_format((float)$salesAnalytics, 2, '.', ''); 
                                        ?>
                                         </h2>
                                        <p class="text-muted mb-3">Revenue today</p>
                                    </div>
                                </div>
                            </div>
                        </div>

                    </div><!-- end col -->

                </div>
                <!-- end row -->

                <div class="row">
                    <div class="col-xl-4">
                        <div class="card">
                            <div class="card-body">
                                <div class="dropdown float-end">
                                    <a href="#" class="dropdown-toggle arrow-none card-drop" data-bs-toggle="dropdown" aria-expanded="false">
                                        <i class="mdi mdi-dots-vertical"></i>
                                    </a>
                                    <div class="dropdown-menu dropdown-menu-end">
                                        <!-- item-->
                                        <a href="javascript:void(0);" class="dropdown-item">Action</a>
                                        <!-- item-->
                                        <a href="javascript:void(0);" class="dropdown-item">Another action</a>
                                        <!-- item-->
                                        <a href="javascript:void(0);" class="dropdown-item">Something else</a>
                                        <!-- item-->
                                        <a href="javascript:void(0);" class="dropdown-item">Separated link</a>
                                    </div>
                                </div>

                                <h4 class="header-title mt-0">Profit and Loss (P&L) Summary</h4>

                                <div class="widget-chart text-center">
                                    <div id="morris-donut-example" dir="ltr" style="height: 245px;" class="morris-chart"></div>
                                    <ul class="list-inline chart-detail-list mb-0">
                                        <li class="list-inline-item">
                                            <h5 style="color: #ff8acc;"><i class="fa fa-circle me-1"></i>Loss</h5>
                                        </li>
                                        <li class="list-inline-item">
                                            <h5 style="color: #5b69bc;"><i class="fa fa-circle me-1"></i>Profit</h5>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div><!-- end col -->

                    <div class="col-xl-4">
                        <div class="card">
                            <div class="card-body">
                                <div class="dropdown float-end">
                                    <a href="#" class="dropdown-toggle arrow-none card-drop" data-bs-toggle="dropdown" aria-expanded="false">
                                        <i class="mdi mdi-dots-vertical"></i>
                                    </a>
                                    <div class="dropdown-menu dropdown-menu-end">
                                        <!-- item-->
                                        <a href="javascript:void(0);" class="dropdown-item">Action</a>
                                        <!-- item-->
                                        <a href="javascript:void(0);" class="dropdown-item">Another action</a>
                                        <!-- item-->
                                        <a href="javascript:void(0);" class="dropdown-item">Something else</a>
                                        <!-- item-->
                                        <a href="javascript:void(0);" class="dropdown-item">Separated link</a>
                                    </div>
                                </div>
                                <h4 class="header-title mt-0">User Activity & Engagement</h4>
                                <div id="morris-bar-example" dir="ltr" style="height: 280px;" class="morris-chart"></div>
                            </div>
                        </div>
                    </div><!-- end col -->

                    <div class="col-xl-4">
                        <div class="card">
                            <div class="card-body">
                                <div class="dropdown float-end">
                                    <a href="#" class="dropdown-toggle arrow-none card-drop" data-bs-toggle="dropdown" aria-expanded="false">
                                        <i class="mdi mdi-dots-vertical"></i>
                                    </a>
                                    <div class="dropdown-menu dropdown-menu-end">
                                        <!-- item-->
                                        <a href="javascript:void(0);" class="dropdown-item">Action</a>
                                        <!-- item-->
                                        <a href="javascript:void(0);" class="dropdown-item">Another action</a>
                                        <!-- item-->
                                        <a href="javascript:void(0);" class="dropdown-item">Something else</a>
                                        <!-- item-->
                                        <a href="javascript:void(0);" class="dropdown-item">Separated link</a>
                                    </div>
                                </div>
                                <h4 class="header-title mt-0">Total Accounts Receivable & Payable</h4>
                                <div id="morris-line-example" dir="ltr" style="height: 280px;" class="morris-chart"></div>
                            </div>
                        </div>
                    </div><!-- end col -->
                </div>
                <!-- end row -->

                <div class="row">
                    
                    <div class="col-xl-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="dropdown float-end">
                                    <a href="#" class="dropdown-toggle arrow-none card-drop" data-bs-toggle="dropdown" aria-expanded="false">
                                        <i class="mdi mdi-dots-vertical"></i>
                                    </a>
                                    <div class="dropdown-menu dropdown-menu-end">
                                        <!-- item-->
                                        <a href="javascript:void(0);" class="dropdown-item">Action</a>
                                        <!-- item-->
                                        <a href="javascript:void(0);" class="dropdown-item">Another action</a>
                                        <!-- item-->
                                        <a href="javascript:void(0);" class="dropdown-item">Something else</a>
                                        <!-- item-->
                                        <a href="javascript:void(0);" class="dropdown-item">Separated link</a>
                                    </div>
                                </div>

                                <h4 class="header-title mt-0 mb-3">Latest Invoices</h4>

                                <div class="table-responsive">
                                    <table class="table table-hover mb-0">
                                        <thead>
                                            <tr>
                                                <th>Client Name</th>
                                                <th>Invoice Number</th>
                                                <th>Total Amount</th>
                                                <th>Due Date</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                                <?php
                                                include('includes/dbconn.php');
                                            
                                                // Fetch data from the 'clients' table
                                                $query = "SELECT invoices.*, clients.client_name FROM invoices JOIN clients ON invoices.client_id = clients.client_id";
                                                $result = mysqli_query($conn, $query);
                                            
                                                // 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['client_name'] . "</td>";
                                                    echo "<td>" . $row['invoice_number'] . "</td>";
                                                    echo "<td>" . $row['total_amount'] . "</td>";
                                                    echo "<td>" . $row['due_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_invoice.php?id=" . $row['invoice_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='invoice_details.php?invoice_id=" . $row['invoice_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_invoice.php?invoice_id=" . $row['invoice_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><!-- end col -->

                </div>
                <!-- end row -->

            </div> <!-- container-fluid -->

        </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'; ?>

<!-- knob plugin -->
<script src="assets/libs/jquery-knob/jquery.knob.min.js"></script>

<!--Morris Chart-->
<script src="assets/libs/morris.js06/morris.min.js"></script>
<script src="assets/libs/raphael/raphael.min.js"></script>

<!-- Dashboar init js-->
<script src="assets/js/pages/dashboard.init.js"></script>

<!-- App js-->
<script src="assets/js/app.min.js"></script>

</body>

</html>