<?php
session_start();

// 5 minutes in seconds
$expire_time = 15 * 60;

// Check if "last_activity" is set
if (isset($_SESSION['last_activity'])) {
    // Check the time since the last activity
    if (time() - $_SESSION['last_activity'] > $expire_time) {
        // User has been inactive for too long.
        session_unset(); // unset $_SESSION variable
        session_destroy(); // destroy session data
        header('Location: ../auth-login.php'); // redirect to login page
        exit();
    }
}

// Set last activity time for next check
$_SESSION['last_activity'] = time();

$companyId = $_SESSION['company_id'];

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

// Initialize the variables
$totalRevenue = 0;
$totalExpenses = 0;
$totalPaid = 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'; ?>
    
    <!-- DataTables CSS -->
<link href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/buttons/2.0.0/css/buttons.dataTables.min.css" rel="stylesheet">
<!-- DataTables Buttons JS -->
<script type="text/javascript" src="https://cdn.datatables.net/buttons/2.0.0/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/2.0.0/js/buttons.flash.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/2.0.0/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/2.0.0/js/buttons.print.min.js"></script>

        <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" />

</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">

                
                <!-- end row -->
                
                <div class="row">

                    <div class="col-md-4">
                        <div class="card border border-secondary" data-section="sales">
                            <div class="card-body text-secondary">
                                <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">
                                        <!-- Use classes instead of ids -->
                                        <a href="javascript:void(0);" class="dropdown-item sales-option">Daily</a>
                                        <a href="javascript:void(0);" class="dropdown-item sales-option">Weekly</a>
                                        <a href="javascript:void(0);" class="dropdown-item sales-option">Monthly</a>
                                    </div>

                                </div>
                                <h4 class="header-title mt-0 mb-3">Sales</h4>
                                <div class="widget-chart-1">
                                    <div class="widget-detail-1 text-end">
                                        <h3 class="my-3"> <?php echo number_format((float)$totalRevenue, 2, '.', ''); ?> </h3>
                                        <p class="text-muted mb-1">Sales today</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="card border border-secondary" data-section="expenses">
                            <div class="card-body text-secondary">
                                <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">
                                        <!-- Use classes instead of ids -->
                                        <a href="javascript:void(0);" class="dropdown-item expenses-option">Daily</a>
                                        <a href="javascript:void(0);" class="dropdown-item expenses-option">Weekly</a>
                                        <a href="javascript:void(0);" class="dropdown-item expenses-option">Monthly</a>
                                    </div>
                                </div>
                                <h4 class="header-title mt-0 mb-3">Expenses</h4>
                                
                                <div class="widget-chart-1">
                                    <div class="widget-detail-1 text-end">
                                        <h3 class="my-3"> <?php echo number_format((float)$totalExpenses, 2, '.', ''); ?> </h3>
                                        <p class="text-muted mb-1">Expenses today</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="card border border-secondary" data-section="paid-invoices">
                            <div class="card-body text-secondary">
                                <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>    
                                    <div class="dropdown-menu dropdown-menu-end">
                                        <!-- Use classes instead of ids -->
                                        <a href="javascript:void(0);" class="dropdown-item paid-invoices-option">Daily</a>
                                        <a href="javascript:void(0);" class="dropdown-item paid-invoices-option">Weekly</a>
                                        <a href="javascript:void(0);" class="dropdown-item paid-invoices-option">Monthly</a>
                                    </div>
                                <h4 class="header-title mt-0 mb-3"> Invoices</h4>

                                <div class="widget-chart-1">
                                    <div class="widget-detail-1 text-end">
                                        <h3 class="my-3"> <?php echo number_format((float)$totalPaid, 2, '.', ''); ?> </h3>
                                        <p class="text-muted mb-1">Paid Invoices</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
                
                <!-- added this -->
                
                <div class="row">
                            <div class="col-12">
                                <div class="card">
                                    <div class="card-body">
                                        <h4 class="mt-0 header-title">Chart of Accounts</h4>

                                        <?php
                                        // Your PHP code from display_coa.php
                                        include('includes/dbconn.php'); // Database connection script
                            
                                        $companyId = $_SESSION['company_id']; // From session
                            
                                        $sql = "SELECT a.account_id, a.account_name, IFNULL(SUM(CASE WHEN t.type = 'Debit' THEN t.amount ELSE -t.amount END), 0) as balance 
                                                FROM chart_of_accounts a 
                                                LEFT JOIN transactions t ON a.account_id = t.account_id AND a.company_id = t.company_id 
                                                WHERE a.company_id = ? 
                                                GROUP BY a.account_id, a.account_name";
                                        $stmt = $conn->prepare($sql);
                                        $stmt->bind_param("i", $companyId);
                                        $stmt->execute();
                                        $result = $stmt->get_result();
                                        ?>
    
                                        <table id="datatable2" class="table table-striped table-bordered dt-responsive nowrap">
                                            <thead>
                                            <tr>
                                                <th>Account ID</th>
                                                <th>Account Name</th>
                                                <th>Balance</th>
                                            </tr>
                                            </thead>
    
    
                                            <tbody>
                                                <?php
                                                while ($row = $result->fetch_assoc()) {
                                                    echo "<tr><td>" . htmlspecialchars($row['account_id']) . "</td>";
                                                    echo "<td>" . htmlspecialchars($row['account_name']) . "</td>";
                                                    echo "<td>" . number_format($row['balance'], 2) . "</td></tr>";
                                                }
                                                $stmt->close();
                                                ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                               
                            </div>
                        </div>
                        <!-- end row -->
                
                <!-- upto here -->
                
                
                        <!-- end row -->
                        
                        
                        <div class="row">
                            <div class="col-12">
                                <div class="card">
                                    <div class="card-body">
                                        <h4 class="mt-0 header-title">Latest Transactions</h4>
                                        <p class="text-muted font-14 mb-3">
                                            Latest Transactions for your company
                                        </p>
                                        <?php
                                        // latest_transactions.php
                                        include('includes/dbconn.php'); // Database connection script
                                        
                                        $companyId = $_SESSION['company_id']; // From session
                                        
                                        // SQL to fetch the latest transactions for the company
                                        $sql = "SELECT transaction_id, account_id, amount, type, transaction_date, description 
                                                FROM transactions 
                                                WHERE company_id = ? 
                                                ORDER BY transaction_date DESC, transaction_id DESC 
                                                LIMIT 10"; // Assuming you want the latest 10 transactions
                                        $stmt = $conn->prepare($sql);
                                        $stmt->bind_param("i", $companyId);
                                        $stmt->execute();
                                        $result = $stmt->get_result();
                                        ?>
                                        <table id="datatable" class="table table-bordered dt-responsive table-responsive nowrap">
                                            <thead>
                                            <tr>
                                                <th>Transaction ID</th>
                                                <th>Account ID</th>
                                                <th>Amount</th>
                                                <th>Type</th>
                                                <th>Transaction Date</th>
                                                <th>Description</th>
                                            </tr>
                                            </thead>
    
    
                                            <tbody>
                                                <?php
                                                while ($row = $result->fetch_assoc()) {
                                                    echo "<tr>";
                                                    echo "<td>" . htmlspecialchars($row['transaction_id']) . "</td>";
                                                    echo "<td>" . htmlspecialchars($row['account_id']) . "</td>";
                                                    echo "<td>" . number_format($row['amount'], 2) . "</td>";
                                                    echo "<td>" . htmlspecialchars($row['type']) . "</td>";
                                                    echo "<td>" . htmlspecialchars($row['transaction_date']) . "</td>";
                                                    echo "<td>" . htmlspecialchars($row['description']) . "</td>";
                                                    echo "</tr>";
                                                }
                                                ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                               
                            </div>
                        </div> <!-- end row -->

                <!-- 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>
<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>

<!-- App js-->
<script src="assets/js/app.min.js"></script>
<script>
$(document).ready(function() {
    $('#datatable').DataTable({
        dom: 'Bfrtip',
        buttons: [
            'excelHtml5',
            'csvHtml5',
            'pdfHtml5'
        ]
    });
});
</script>
<script>
$(document).ready(function() {
    $('#datatable2').DataTable({
        dom: 'Bfrtip',
        buttons: [
            'excelHtml5',
            'csvHtml5',
            'pdfHtml5'
        ]
    });
});
</script>

<script>
document.addEventListener("DOMContentLoaded", function() {
    document.querySelectorAll('.dropdown-menu .dropdown-item').forEach(item => {
        item.addEventListener('click', function() {
            const period = this.textContent.trim().toLowerCase();
            const section = this.closest('.card').dataset.section;

            let endpoint = '';
            switch (section) {
                case 'sales':
                    endpoint = 'sales_data.php';
                    break;
                case 'expenses':
                    endpoint = 'expenses_data.php';
                    break;
                case 'paid-invoices':
                    endpoint = 'paid_invoices_data.php';
                    break;
                case 'unpaid-invoices':
                    endpoint = 'unpaid_invoices_data.php';
                    break;
                // Add more cases as needed
            }

            if (endpoint) {
                console.log(`Fetching data for ${section} - Period: ${period}`);
                fetchData(endpoint, period, section);
            } else {
                console.error(`No endpoint found for section: ${section}`);
            }
        });
    });
});

function fetchData(endpoint, period, section) {
    fetch(`${endpoint}?option=${period}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('Response:', response); // Log the response
            console.log('Data received:', data); // Log the data to inspect its structure

            const card = document.querySelector(`[data-section="${section}"]`);
            const widgetDetail = card.querySelector('.widget-detail-1');

            if (data.total !== undefined) {
                widgetDetail.querySelector('h2').textContent = `$${data.total}`;
                widgetDetail.querySelector('p').textContent = `Total ${period}`;
            } else {
                console.error('Total key is not present in the response');
                // Handle the absence of the 'total' key appropriately
            }
        })
        .catch(error => {
            console.error('Fetch Error:', error);
            // Implement user-visible error reporting
        });
}


</script>
</body>

</html>