<?php include 'inc/funtions.php';

if (isset($_SESSION['user_type']) && $_SESSION['user_type'] == 'Admin') {
    $user_id = $_SESSION['user_id'];
    $business_id = $_SESSION['business_id'];
    $user = getUserId($user_id);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard</title>
    
    <link rel="stylesheet" href="assets/css/bootstrap.css">
    
    <link rel="stylesheet" href="assets/vendors/chartjs/Chart.min.css">
    <link rel="stylesheet" href="assets/vendors/simple-datatables/style.css">
    <link rel="stylesheet" href="assets/vendors/perfect-scrollbar/perfect-scrollbar.css">
    <link rel="stylesheet" href="assets/css/app.css">
    <link rel="shortcut icon" href="assets/images/favicon.png" type="image/x-icon">
    <script src="assets/vendors/chartjs/chart.umd.min.js"></script>
</head>
<body>
    <div id="app">
        <?php include('inc/header.php'); ?>
            <div class="main-content container-fluid">
                <div class="page-title">
                    <h3>Dashboard</h3>
                    <p class="text-subtitle text-muted"></p>
                </div> 
                <section class="section">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="card p-3 shadow-sm border-0 bg-primary text-white" style="height: 140px;">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <small class="text-uppercase font-weight-bold" style="opacity: 0.8; font-size: 1rem;">Total Revenue</small>
                                        <h2 class="mb-0">₦ <?php echo number_format($gross_revenue, 2); ?></h2>
                                    </div>
                                    <div class="text-right">
                                        <i class="fas <?php echo ($rev_diff_percent >= 0) ? 'fa-arrow-up' : 'fa-arrow-down'; ?>"></i>
                                        <small class="d-block" ><?php echo round(abs($rev_diff_percent)); ?>%</small>
                                    </div>
                                </div>

                                <div class="progress mt-3" style="height: 6px; background: rgba(255,255,255,0.2);">
                                    <div class="progress-bar bg-white" 
                                         role="progressbar" 
                                         style="width: <?php echo $bar_width; ?>%" 
                                         aria-valuenow="<?php echo $bar_width; ?>" 
                                         aria-valuemin="0" 
                                         aria-valuemax="100">
                                    </div>
                                </div>
                                
                                <small class="mt-2 d-block" style="opacity: 0.7; font-size: 0.75rem;">
                                    vs Prev. <?php echo ucfirst($filter); ?>: ₦<?php echo number_format($prev_revenue); ?>
                                </small>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="card p-3 shadow-sm border-0 bg-info text-white" style="height: 140px;">
                                <small class="text-uppercase" style="opacity: 0.7; font-size: 1rem;">Maintenance Costs</small>
                                <h3 class="font-weight-bold mb-1">
                                    ₦ <?php echo number_format($total_maintenance); ?>
                                </h3>
                                
                                <div class="d-flex align-items-center">
                                    <small class="mr-2">
                                        Prev: ₦ <?php echo number_format($prev_total_maintenance); ?>
                                    </small>
                                    
                                    <small class="<?php echo $maint_trend_color; ?> font-weight-bold" style="opacity: 0.7; font-size: 1rem;">
                                        <?php echo ($total_maintenance > $prev_total_maintenance) ? '↑' : '↓'; ?> 
                                        ₦<?php echo number_format(abs($maint_diff)); ?>
                                    </small>
                                </div>
                            </div>                            
                        </div>

                        <div class="col-md-3">
                            <div class="card p-3 shadow-sm border-0 bg-primary text-white" style="height: 140px;">
                                <small style="opacity: 0.7; font-size: 1rem;">TOTAL SALES VOLUME</small>
                                <h2><?php echo number_format($total_sales_vol); ?></h2>
                                <small style="opacity: 0.7; font-size: 1rem;">From <?php echo $total_trips; ?> ATC Records</small>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="card p-3 shadow-sm border-0 bg-info text-white" style="height: 140px;">
                                <small style="opacity: 0.7; font-size: 1rem;">TOTAL TRIPS</small>
                                <h3><?php echo number_format($curr_trips); ?></h3>
                                <small class="<?php echo $trend_color; ?>" style="opacity: 0.7; font-size: 1rem;">
                                    <?php echo $trend_icon . round(abs($diff)); ?>% vs Previous <?php echo ucfirst($filter); ?>
                                </small>
                            </div>
                        </div>
                    </div>
                    <div class="row mb-4">
                        <div class="col-md-8">
                            <div class="card" style="height: 100%;">
                                <div class="card-header">
                                    <h3 class='card-heading p-1 pl-3'>Monthly Maintenance Cost</h3>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-4 col-12">
                                            <div class="pl-3">
                                                <h1 class='mt-5'>&#8358; <?php echo number_format($current_total, 0, '.', ','); ?></h1> 
                                                
                                                <p class='text-xs'><?php echo $trend_text; ?> than last month</p>
                                                
                                                <div class="legends">
                                                    <div class="legend d-flex flex-row align-items-center">
                                                        <div class='w-3 h-3 rounded-full bg-info me-2'></div><span class='text-xs'>Last Month</span>
                                                    </div>
                                                    <div class="legend d-flex flex-row align-items-center">
                                                        <div class='w-3 h-3 rounded-full bg-blue me-2'></div><span class='text-xs'>Current Month</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-8 col-12">
                                            <canvas id="maintenanceChart" style="height: 50vh;"></canvas>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card" style="height: 100%;">
                                <div class="card-header">
                                    <h4>Your Earnings</h4>
                                </div>
                                <div class="card-body">
                                    <div id="radialBars" data-radial-value="<?php echo $radial_value; ?>" data-total-earnings="<?php echo $formatted_current_total; ?>"></div> 
                                    
                                    <div class="text-center mb-5">
                                        <h6>Change from last month: <span class='<?php echo $trend_class; ?>'><?php echo $trend_text_earn; ?></span></h6>
                                        
                                        <h1 class='text-green'>₦ <?php echo $formatted_current_total; ?></h1> 
                                    </div>
                                    
                                    <div class="text-center">
                                         <p class="text-muted">Last Month Total: ₦ <?php echo $formatted_last_total; ?></p>
                                     </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <section class="section">
                        <div class="row mb-4">
                            <div class="">
                                <div class="card">
                                    <div class="card-header d-flex justify-content-between align-items-center">
                                        <h4 class="card-title">Logistics</h4>
                                       <!--  <div class="d-flex ">
                                            <button type="button" class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#addtriprecord"><i data-feather="plus"></i> Create Logistics</button>
                                        </div> -->
                                    </div>
                                    <div class="card-body px-0 pb-0">
                                        <div class="table-responsive p-3">
                                            <table class='table table-striped mb-0' id="table1">
                                                <thead>
                                                    <tr>
                                                        <th>#</th>
                                                        <th>ATC Number</th>
                                                        <th>Unit</th>
                                                        <th>Total Cost Price</th>
                                                        <th>Total Selling Price</th>
                                                        <th>Customer Name</th>
                                                        <th>Location</th>
                                                        <th>Status</th>
                                                        <th>Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody class="text-center">
                                                    <?php 
                                                    $all_modals = "";
                                                    $count = 1;
                                                    $query = "SELECT t.*, 
                                                              tr.license_plate, tr.make, tr.model,
                                                              CONCAT(d.first_name, ' ', d.last_name) as driver_name, d.phone_number as driver_phone,
                                                              CONCAT(u1.first_name, ' ', u1.last_name) as processed_by,
                                                              CONCAT(u.first_name, ' ', u.last_name) as edit_by,
                                                              a.atc_number, a.volume, a.type as atc_type,
                                                              c.name as customer_name, c.phone as customer_phone, c.address as customer_address, c.wallet_balance
                                                              FROM trips t
                                                              LEFT JOIN trucks tr ON t.truck_id = tr.truck_id
                                                              LEFT JOIN drivers d ON t.driver_id = d.driver_id
                                                              LEFT JOIN atc_records a ON t.atc_id = a.atc_id
                                                              LEFT JOIN customers c ON t.customer_id = c.customer_id
                                                              LEFT JOIN users u1 ON t.user_id = u1.user_id
                                                              LEFT JOIN users u ON t.edit_user_id = u.user_id
                                                              WHERE t.business_id = '$business_id' 
                                                              ORDER BY t.trip_id DESC";

                                                    $all_trips = Querydb($query);

                                                    // 2. Loop through the results
                                                    foreach ($all_trips as $trip) {
                                                        // Everything is now inside the $trip variable!
                                                        // Access them directly:
                                                        $license = $trip['license_plate'] ?? 'N/A';
                                                        $driver  = $trip['driver_name']    ?? 'No Driver Assigned';
                                                        $atc_num = $trip['atc_number']    ?? 'N/A';
                                                        $c_name  = $trip['customer_name']  ?? 'Unassigned';
                                                    ?>
                                                    <tr>
                                                        <td><?php echo $count; ?></td>
                                                        <td><?php echo $trip['atc_number']; ?></td>
                                                        <td><?php echo $trip['unit']; ?></td>
                                                        <td><?php echo '&#8358; '. number_format($trip['cost_price'] * $trip['unit'],2); ?></td>
                                                        <td><?php echo '&#8358; '. number_format($trip['selling_price'] * $trip['unit'],2); ?></td>
                                                        <td><?php echo $c_name; ?></td>
                                                        <td><?php echo $trip['location']; ?></td>
                                                        <td><?php echo $trip['status']; ?></td>                                                    
                                                        <td>
                                                            <div class="btn-group">
                                                                <?php 
                                                                if($trip['status'] != 'Completed' && $trip['status'] != 'Canceled'){ ?>
                                                                    <button type="submit" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#edittripModal<?php echo $trip['trip_id']; ?>">
                                                                        <i data-feather="edit"></i> Edit
                                                                    </button>
                                                                    <button type="button" class="btn btn-sm btn-success" onclick="toggleTripStatus(<?php echo htmlspecialchars(json_encode($trip)); ?>)">
                                                                        <i data-feather="check-circle"></i> Completed
                                                                    </button>

                                                                    <button type="button" class="btn btn-sm btn-danger" onclick="cancelTrip(<?php echo htmlspecialchars(json_encode($trip)); ?>)">
                                                                        <i data-feather="x-circle"></i> Cancelled
                                                                    </button>
                                                                <?php } ?>
                                                                <button type="button" class="btn btn-secondary" data-bs-toggle="modal" data-bs-target="#viewtripModal<?php echo $trip['trip_id']; ?>">
                                                                    <i data-feather="eye"></i> Preview
                                                                </button>
                                                            </div>

                                                        </td>
                                                    </tr>
                                                    <div class="modal" id="edittripModal<?php echo $trip['trip_id']; ?>">
                                                        <div class="modal-dialog modal-dialog-centered">
                                                            <div class="modal-content">
                                                            <div class="modal-header">
                                                                <h4 class="modal-title">Edit Logistics</h4>
                                                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                            </div>
                                                            <div class="modal-body">
                                                                <form class="trip_form_<?php echo $count; ?>" id="createTripForm_<?php echo $count; ?>">
                                                                    <div class="row">
                                                                        <input type="hidden" id="trip_id_<?php echo $count; ?>" value="<?php echo $trip['trip_id']; ?>">
                                                                        <div class="col-md-6 col-12">
                                                                            <div class="form-group">
                                                                                <label for="atc-column">ATC Number</label>
                                                                                <select class="choices form-select" id="atc_colum_<?php echo $count; ?>" readonly disabled selected>
                                                                                    <?php 
                                                                                    $sql = Querydb("SELECT * FROM atc_records WHERE business_id = '$business_id' AND atc_id = {$trip['atc_id']}");
                                                                                    foreach ($sql as $atc) { ?>
                                                                                    <option value="<?php echo $atc['atc_id']; ?>" <?php if($atc['atc_id'] == $trip['atc_id']){ echo 'selected';} ?>><?php echo $atc['atc_number']." (".$atc['type'].")"; ?></option>
                                                                                    <?php } ?>
                                                                                </select>
                                                                            </div>
                                                                        </div> 
                                                                        <div class="col-lg-6 col-12">  
                                                                            <div class="form-group">
                                                                                <label for="customer-colum">Customer</label>
                                                                                <select class="choices form-select customer-select-trigger" id="customer_colum_<?php echo $count; ?>"> 
                                                                                    <option value="" disabled selected>Select Customer</option>
                                                                                    <?php 
                                                                                    $sql = Querydb("SELECT * from customers WHERE business_id = '$business_id'");
                                                                                    foreach ($sql as $customer) { ?>
                                                                                    <option value="<?php echo $customer['customer_id']; ?>" <?php if($customer['customer_id'] == $trip['customer_id']){ echo 'selected';} ?>><?php echo $customer['name']; ?></option>
                                                                                    <?php } ?>
                                                                                </select>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-6">
                                                                            <div class="form-group">
                                                                                <label for="location-column">Unit</label>
                                                                                <input type="text" id="unit_<?php echo $count; ?>" class="form-control" value="<?php echo $trip['unit']; ?>">
                                                                            </div>
                                                                        </div>

                                                                        <div class="col-6">
                                                                            <div class="form-group">
                                                                                <label for="location-column">Sell price</label>
                                                                                <input type="text" id="sell_<?php echo $count; ?>" class="form-control" value="<?php echo $trip['selling_price']; ?>">
                                                                            </div>
                                                                        </div>

                                                                        <div class="col-6">
                                                                            <div class="form-group">
                                                                                <label for="location-column">Cost price</label>
                                                                                <input type="text" id="cost_<?php echo $count; ?>" class="form-control" value="<?php echo $trip['cost_price']; ?>">
                                                                            </div>
                                                                        </div>

                                                                        <div class="col-6">
                                                                            <div class="form-group">
                                                                                <label for="location-column">Driver Allowence</label>
                                                                                <input type="text" id="allowance_<?php echo $count; ?>" class="form-control" value="<?php echo $trip['driver_allowence']; ?>">
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-12">
                                                                            <div class="form-group">
                                                                                <label for="location-column">Location</label>
                                                                                <textarea type="text" rows="5" id="location_column_<?php echo $count; ?>" class="form-control"><?php echo $trip['location']; ?></textarea>
                                                                            </div>
                                                                        </div>

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

                                                            <!-- Modal footer -->
                                                            <div class="modal-footer">
                                                                <button type="button" class="btn bt n-danger" data-bs-dismiss="modal">Close</button>
                                                                <button class="btn btn-primary" type="submit" id="edittripModalbtn_<?php echo $count; ?>">Submit</button> 
                                                            </div>

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

                                                    <?php 
                                                    // 3. CAPTURE MODALS IN A VARIABLE (Buffered)
                                                    ob_start(); ?> 
                                                    <div class="modal" id="viewtripModal<?php echo $trip['trip_id']; ?>">
                                                        <div class="modal-dialog modal-dialog-centered modal-lg">
                                                            <div class="modal-content">
                                                            <div class="modal-header">
                                                                <h4 class="modal-title">Preview Logistics </h4>
                                                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                            </div>
                                                            <div class="modal-body">
                                                                <div class="card-body p-4">
                                                                    <div class="row align-items-center mb-4">
                                                                        <div class="col-8">
                                                                            <h4 class="text-primary mb-0">Trip Manifest: <?php echo $atc['atc_number']; ?></h4>
                                                                            <small class="text-muted">Status: <span class="badge bg-<?php echo ($trip['status'] == 'Completed') ? 'success' : 'warning'; ?>"><?php echo $trip['status']; ?></span></small>
                                                                        </div>
                                                                    </div>

                                                                    <div class="row g-4">
                                                                        <div class="col-md-6 border-end">
                                                                            <h6 class="fw-bold text-uppercase small text-muted mb-3">Logistics Details</h6>
                                                                            <div class="d-flex justify-content-between mb-2">
                                                                                <span class="text-secondary">Truck License:</span>
                                                                                <span class="fw-bold"><?php echo $trip['license_plate']; ?></span>
                                                                            </div>
                                                                            <div class="d-flex justify-content-between mb-2">
                                                                                <span class="text-secondary">Driver:</span>
                                                                                <span class="fw-bold"><?php echo $trip['driver_name']; ?></span>
                                                                            </div>
                                                                            <div class="d-flex justify-content-between mb-2">
                                                                                <span class="text-secondary">Location: </span>
                                                                                <span class="fw-bold"><?php echo $trip['location']; ?></span>
                                                                            </div>
                                                                            <div class="d-flex justify-content-between mb-2">
                                                                                <span class="text-secondary">Total Units:</span>
                                                                                <span class="fw-bold text-primary"><?php echo number_format($trip['unit']); ?></span>
                                                                            </div>
                                                                        </div>

                                                                        <div class="col-md-6">
                                                                            <h6 class="fw-bold text-uppercase small text-muted mb-3">Customer Information</h6>
                                                                            <div class="mb-2"><i data-feather="user" class="icon-xs"></i><strong><?php echo (isset($trip['customer_name']))? $trip['customer_name'] : 'Unassigned'; ?></strong></div>
                                                                            <div class="text-muted small mb-2"><i data-feather="phone" class="icon-xs"></i> <?php echo (isset($trip['customer_phone']))? $trip['customer_phone'] : 'Unassigned'; ?></div>
                                                                            <div class="text-muted small mb-2"><i data-feather="map-pin" class="icon-xs"></i> <?php echo (isset($trip['customer_address']))? $trip['customer_address'] : 'Unassigned'; ?></div>
                                                                        </div>

                                                                        <div class="col-12">
                                                                            <div class="table-responsive">
                                                                                <table class="table table-bordered bg-light">
                                                                                    <thead class="table-dark">
                                                                                        <tr>
                                                                                            <th>Description</th>
                                                                                            <th class="text-end">Rate</th>
                                                                                            <th class="text-end">Total</th>
                                                                                        </tr>
                                                                                    </thead>
                                                                                    <tbody>
                                                                                        <tr>
                                                                                            <td>Cost Price (Expense)</td>
                                                                                            <td class="text-end">₦ <?php echo number_format($trip['cost_price'], 1); ?></td>
                                                                                            <td class="text-end fw-bold text-danger">₦ <?php echo number_format($trip['cost_price'] * $trip['unit'], 1); ?></td>
                                                                                        </tr>
                                                                                        <tr>
                                                                                            <td>Selling Price (Revenue)</td>
                                                                                            <td class="text-end">₦ <?php echo number_format($trip['selling_price'], 1); ?></td>
                                                                                            <td class="text-end fw-bold text-success">₦ <?php echo number_format($trip['selling_price'] * $trip['unit'], 1); ?></td>
                                                                                        </tr>
                                                                                        <tr>
                                                                                            <td>Driver Allowance</td>
                                                                                            <td class="text-end">-</td>
                                                                                            <td class="text-end text-danger">₦ <?php echo number_format($trip['driver_allowence'], 2); ?></td>
                                                                                        </tr>
                                                                                    </tbody>
                                                                                    <tfoot class="bg-white">
                                                                                        <tr class="fs-5">
                                                                                            <?php 
                                                                                                $net_profit = ($trip['selling_price'] * $trip['unit']) - ($trip['cost_price'] * $trip['unit']) - $trip['driver_allowence'];
                                                                                            ?>
                                                                                            <th colspan="2" class="text-end">Net Trip Profit:</th>
                                                                                            <th class="text-end text-primary">₦ <?php echo number_format($net_profit, 2); ?></th>
                                                                                        </tr>
                                                                                    </tfoot>
                                                                                </table>
                                                                            </div>
                                                                        </div>

                                                                        <div class="col-12 mt-0">
                                                                            <div class="p-3 bg-light rounded d-flex justify-content-between fs-6">
                                                                                <span><strong>Scheduled:</strong> <?php echo date('d/m/Y', strtotime($trip['scheduled_start_time'])); ?></span>
                                                                                <span><strong>Completed:</strong> <?php echo (!empty($trip['actual_end_time']) && $trip['actual_end_time'] !== '0000-00-00 00:00:00' && $trip['actual_end_time'] !== '0000-00-00') ? date('d-m-Y', strtotime($trip['actual_end_time'])) : '<span class="badge bg-warning text-dark">Pending</span>'; ?>
                                                                                </span>
                                                                                <div class="d-flex flex-column">
                                                                                    <span class="fw-bold">Processed By: <?php echo $trip['processed_by']; ?></span>
                                                                                    <span class="text-muted">Edited By: <?php echo $trip['edit_by'] ?? 'Not Edited'; ?></span>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>

                                                            </div>
                                                        </div>
                                                    </div>
                                                    <?php 
                                                    $all_modals .= ob_get_clean(); 
                                                    $count++;} ?>
                                                </tbody>
                                            </table>
                                            <?php 
                                            // 4. ECHO MODALS AFTER TABLE IS CLOSED
                                            echo $all_modals; 
                                            ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </section>
                </section>

            </div>
<?php  include('inc/footer.php'); 
} else if (isset($_SESSION['user_type']) && $_SESSION['user_type'] == 'Manager') {
    $user_id = $_SESSION['user_id'];
    $business_id = $_SESSION['business_id'];
    $user = getUserId($user_id);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard</title>
    
    <link rel="stylesheet" href="assets/css/bootstrap.css">
    
    <link rel="stylesheet" href="assets/vendors/chartjs/Chart.min.css">
    <link rel="stylesheet" href="assets/vendors/simple-datatables/style.css">
    <link rel="stylesheet" href="assets/vendors/perfect-scrollbar/perfect-scrollbar.css">
    <link rel="stylesheet" href="assets/css/app.css">
    <link rel="shortcut icon" href="assets/images/favicon.png" type="image/x-icon">
    <script src="assets/vendors/chartjs/chart.umd.min.js"></script>
</head>
<body>
    <div id="app">
        <?php include('inc/header.php'); ?>
            <div class="main-content container-fluid">
                <div class="page-title">
                    <h3>Dashboard</h3>
                    <p class="text-subtitle text-muted"></p>
                </div> 
                <section class="section">
                    <div class="row">
                        <div class="col-md-4">
                            <div class="card p-3 shadow-sm border-0 bg-info text-white" style="height: 140px;">
                                <small class="text-uppercase" style="opacity: 0.7; font-size: 1.5rem;">Maintenance Costs</small>
                                <h3 class="font-weight-bold mb-1">
                                    ₦ <?php echo number_format($total_maintenance); ?>
                                </h3>
                                
                                <div class="d-flex align-items-center">
                                    <small class="mr-2">
                                        Prev: ₦ <?php echo number_format($prev_total_maintenance); ?>
                                    </small>
                                    
                                    <small class="<?php echo $maint_trend_color; ?> font-weight-bold" style="opacity: 0.7; font-size: 1.50rem;">
                                        <?php echo ($total_maintenance > $prev_total_maintenance) ? '↑' : '↓'; ?> 
                                        ₦<?php echo number_format(abs($maint_diff)); ?>
                                    </small>
                                </div>
                            </div>                            
                        </div>

                        <div class="col-md-4">
                            <div class="card p-3 shadow-sm border-0 bg-primary text-white" style="height: 140px;">
                                <small style="opacity: 0.7; font-size: 1.5rem;">TOTAL SALES VOLUME</small>
                                <h2><?php echo number_format($total_sales_vol); ?></h2>
                                <small style="opacity: 0.7; font-size: 1rem;">From <?php echo $total_trips; ?> ATC Records</small>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="card p-3 shadow-sm border-0 bg-info text-white" style="height: 140px;">
                                <small style="opacity: 0.7; font-size: 1.5rem;">TOTAL TRIPS</small>
                                <h3><?php echo number_format($curr_trips); ?></h3>
                                <small class="<?php echo $trend_color; ?>" style="opacity: 0.7; font-size: 1.5rem;">
                                    <?php echo $trend_icon . round(abs($diff)); ?>% vs Previous <?php echo ucfirst($filter); ?>
                                </small>
                            </div>
                        </div>
                    </div>
                    <div class="row mb-4">
                        <div class="col-md-12">
                            <div class="card" style="height: 100%;">
                                <div class="card-header">
                                    <h3 class='card-heading p-1 pl-3'>Monthly Maintenance Cost</h3>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-4 col-12">
                                            <div class="pl-3">
                                                <h1 class='mt-5'>&#8358; <?php echo number_format($current_total, 0, '.', ','); ?></h1> 
                                                
                                                <p class='text-xs'><?php echo $trend_text; ?> than last month</p>
                                                
                                                <div class="legends">
                                                    <div class="legend d-flex flex-row align-items-center">
                                                        <div class='w-3 h-3 rounded-full bg-info me-2'></div><span class='text-xs'>Last Month</span>
                                                    </div>
                                                    <div class="legend d-flex flex-row align-items-center">
                                                        <div class='w-3 h-3 rounded-full bg-blue me-2'></div><span class='text-xs'>Current Month</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-8 col-12">
                                            <canvas id="maintenanceChart" style="height: 50vh;"></canvas>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <section class="section">
                        <div class="row mb-4">
                            <div class="">
                                <div class="card">
                                    <div class="card-header d-flex justify-content-between align-items-center">
                                        <h4 class="card-title">Logistics</h4>
                                    </div>
                                    <div class="card-body px-0 pb-0">
                                        <div class="table-responsive p-3">
                                            <table class='table table-striped mb-0' id="table1">
                                                <thead>
                                                    <tr>
                                                        <th>#</th>
                                                        <th>ATC Number</th>
                                                        <th>Unit</th>
                                                        <th>Total Cost Price</th>
                                                        <th>Total Selling Price</th>
                                                        <th>Customer Name</th>
                                                        <th>Location</th>
                                                        <th>Status</th>
                                                        <th>Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody class="text-center">
                                                    <?php 
                                                    $all_modals = "";
                                                    $count = 1;
                                                    $query = "SELECT t.*, 
                                                              tr.license_plate, tr.make, tr.model,
                                                              CONCAT(d.first_name, ' ', d.last_name) as driver_name, d.phone_number as driver_phone,
                                                              CONCAT(u1.first_name, ' ', u1.last_name) as processed_by,
                                                              CONCAT(u.first_name, ' ', u.last_name) as edit_by,
                                                              a.atc_number, a.volume, a.type as atc_type,
                                                              c.name as customer_name, c.phone as customer_phone, c.address as customer_address, c.wallet_balance
                                                              FROM trips t
                                                              LEFT JOIN trucks tr ON t.truck_id = tr.truck_id
                                                              LEFT JOIN drivers d ON t.driver_id = d.driver_id
                                                              LEFT JOIN atc_records a ON t.atc_id = a.atc_id
                                                              LEFT JOIN customers c ON t.customer_id = c.customer_id
                                                              LEFT JOIN users u1 ON t.user_id = u1.user_id
                                                              LEFT JOIN users u ON t.edit_user_id = u.user_id
                                                              WHERE t.business_id = '$business_id' 
                                                              ORDER BY t.trip_id DESC";

                                                    $all_trips = Querydb($query);

                                                    // 2. Loop through the results
                                                    foreach ($all_trips as $trip) {
                                                        // Everything is now inside the $trip variable!
                                                        // Access them directly:
                                                        $license = $trip['license_plate'] ?? 'N/A';
                                                        $driver  = $trip['driver_name']    ?? 'No Driver Assigned';
                                                        $atc_num = $trip['atc_number']    ?? 'N/A';
                                                        $c_name  = $trip['customer_name']  ?? 'Unassigned';
                                                    ?>
                                                    <tr>
                                                        <td><?php echo $count; ?></td>
                                                        <td><?php echo $trip['atc_number']; ?></td>
                                                        <td><?php echo $trip['unit']; ?></td>
                                                        <td><?php echo '&#8358; '. number_format($trip['cost_price'] * $trip['unit'],2); ?></td>
                                                        <td><?php echo '&#8358; '. number_format($trip['selling_price'] * $trip['unit'],2); ?></td>
                                                        <td><?php echo $c_name; ?></td>
                                                        <td><?php echo $trip['location']; ?></td>
                                                        <td><?php echo $trip['status']; ?></td>                                                    
                                                        <td>
                                                            <div class="btn-group">
                                                                <?php 
                                                                if($trip['status'] != 'Completed' && $trip['status'] != 'Canceled'){ ?>
                                                                    <button type="submit" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#edittripModal<?php echo $trip['trip_id']; ?>">
                                                                        <i data-feather="edit"></i> Edit
                                                                    </button>
                                                                    <button type="button" class="btn btn-sm btn-success" onclick="toggleTripStatus(<?php echo htmlspecialchars(json_encode($trip)); ?>)">
                                                                        <i data-feather="check-circle"></i> Completed
                                                                    </button>

                                                                    <button type="button" class="btn btn-sm btn-danger" onclick="cancelTrip(<?php echo htmlspecialchars(json_encode($trip)); ?>)">
                                                                        <i data-feather="x-circle"></i> Cancelled
                                                                    </button>
                                                                <?php } ?>
                                                                <button type="button" class="btn btn-secondary" data-bs-toggle="modal" data-bs-target="#viewtripModal<?php echo $trip['trip_id']; ?>">
                                                                    <i data-feather="eye"></i> Preview
                                                                </button>
                                                            </div>

                                                        </td>
                                                    </tr>
                                                    <div class="modal" id="edittripModal<?php echo $trip['trip_id']; ?>">
                                                        <div class="modal-dialog modal-dialog-centered">
                                                            <div class="modal-content">
                                                            <div class="modal-header">
                                                                <h4 class="modal-title">Edit Logistics</h4>
                                                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                            </div>
                                                            <div class="modal-body">
                                                                <form class="trip_form_<?php echo $count; ?>" id="createTripForm_<?php echo $count; ?>">
                                                                    <div class="row">
                                                                        <input type="hidden" id="trip_id_<?php echo $count; ?>" value="<?php echo $trip['trip_id']; ?>">
                                                                        <div class="col-md-6 col-12">
                                                                            <div class="form-group">
                                                                                <label for="atc-column">ATC Number</label>
                                                                                <select class="choices form-select" id="atc_colum_<?php echo $count; ?>" readonly disabled selected>
                                                                                    <?php 
                                                                                    $sql = Querydb("SELECT * FROM atc_records WHERE business_id = '$business_id' AND atc_id = {$trip['atc_id']}");
                                                                                    foreach ($sql as $atc) { ?>
                                                                                    <option value="<?php echo $atc['atc_id']; ?>" <?php if($atc['atc_id'] == $trip['atc_id']){ echo 'selected';} ?>><?php echo $atc['atc_number']." (".$atc['type'].")"; ?></option>
                                                                                    <?php } ?>
                                                                                </select>
                                                                            </div>
                                                                        </div> 
                                                                        <div class="col-lg-6 col-12">  
                                                                            <div class="form-group">
                                                                                <label for="customer-colum">Customer</label>
                                                                                <select class="choices form-select customer-select-trigger" id="customer_colum_<?php echo $count; ?>"> 
                                                                                    <option value="" disabled selected>Select Customer</option>
                                                                                    <?php 
                                                                                    $sql = Querydb("SELECT * from customers WHERE business_id = '$business_id'");
                                                                                    foreach ($sql as $customer) { ?>
                                                                                    <option value="<?php echo $customer['customer_id']; ?>" <?php if($customer['customer_id'] == $trip['customer_id']){ echo 'selected';} ?>><?php echo $customer['name']; ?></option>
                                                                                    <?php } ?>
                                                                                </select>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-6">
                                                                            <div class="form-group">
                                                                                <label for="location-column">Unit</label>
                                                                                <input type="text" id="unit_<?php echo $count; ?>" class="form-control" value="<?php echo $trip['unit']; ?>">
                                                                            </div>
                                                                        </div>

                                                                        <div class="col-6">
                                                                            <div class="form-group">
                                                                                <label for="location-column">Sell price</label>
                                                                                <input type="text" id="sell_<?php echo $count; ?>" class="form-control" value="<?php echo $trip['selling_price']; ?>">
                                                                            </div>
                                                                        </div>

                                                                        <div class="col-6">
                                                                            <div class="form-group">
                                                                                <label for="location-column">Cost price</label>
                                                                                <input type="text" id="cost_<?php echo $count; ?>" class="form-control" value="<?php echo $trip['cost_price']; ?>">
                                                                            </div>
                                                                        </div>

                                                                        <div class="col-6">
                                                                            <div class="form-group">
                                                                                <label for="location-column">Driver Allowence</label>
                                                                                <input type="text" id="allowance_<?php echo $count; ?>" class="form-control" value="<?php echo $trip['driver_allowence']; ?>">
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-12">
                                                                            <div class="form-group">
                                                                                <label for="location-column">Location</label>
                                                                                <textarea type="text" rows="5" id="location_column_<?php echo $count; ?>" class="form-control"><?php echo $trip['location']; ?></textarea>
                                                                            </div>
                                                                        </div>

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

                                                            <!-- Modal footer -->
                                                            <div class="modal-footer">
                                                                <button type="button" class="btn bt n-danger" data-bs-dismiss="modal">Close</button>
                                                                <button class="btn btn-primary" type="submit" id="edittripModalbtn_<?php echo $count; ?>">Submit</button> 
                                                            </div>

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

                                                    <?php 
                                                    // 3. CAPTURE MODALS IN A VARIABLE (Buffered)
                                                    ob_start(); ?> 
                                                    <div class="modal" id="viewtripModal<?php echo $trip['trip_id']; ?>">
                                                        <div class="modal-dialog modal-dialog-centered modal-lg">
                                                            <div class="modal-content">
                                                            <div class="modal-header">
                                                                <h4 class="modal-title">Preview Logistics </h4>
                                                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                            </div>
                                                            <div class="modal-body">
                                                                <div class="card-body p-4">
                                                                    <div class="row align-items-center mb-4">
                                                                        <div class="col-8">
                                                                            <h4 class="text-primary mb-0">Trip Manifest: <?php echo $atc['atc_number']; ?></h4>
                                                                            <small class="text-muted">Status: <span class="badge bg-<?php echo ($trip['status'] == 'Completed') ? 'success' : 'warning'; ?>"><?php echo $trip['status']; ?></span></small>
                                                                        </div>
                                                                    </div>

                                                                    <div class="row g-4">
                                                                        <div class="col-md-6 border-end">
                                                                            <h6 class="fw-bold text-uppercase small text-muted mb-3">Logistics Details</h6>
                                                                            <div class="d-flex justify-content-between mb-2">
                                                                                <span class="text-secondary">Truck License:</span>
                                                                                <span class="fw-bold"><?php echo $trip['license_plate']; ?></span>
                                                                            </div>
                                                                            <div class="d-flex justify-content-between mb-2">
                                                                                <span class="text-secondary">Driver:</span>
                                                                                <span class="fw-bold"><?php echo $trip['driver_name']; ?></span>
                                                                            </div>
                                                                            <div class="d-flex justify-content-between mb-2">
                                                                                <span class="text-secondary">Location: </span>
                                                                                <span class="fw-bold"><?php echo $trip['location']; ?></span>
                                                                            </div>
                                                                            <div class="d-flex justify-content-between mb-2">
                                                                                <span class="text-secondary">Total Units:</span>
                                                                                <span class="fw-bold text-primary"><?php echo number_format($trip['unit']); ?></span>
                                                                            </div>
                                                                        </div>

                                                                        <div class="col-md-6">
                                                                            <h6 class="fw-bold text-uppercase small text-muted mb-3">Customer Information</h6>
                                                                            <div class="mb-2"><i data-feather="user" class="icon-xs"></i><strong><?php echo (isset($trip['customer_name']))? $trip['customer_name'] : 'Unassigned'; ?></strong></div>
                                                                            <div class="text-muted small mb-2"><i data-feather="phone" class="icon-xs"></i> <?php echo (isset($trip['customer_phone']))? $trip['customer_phone'] : 'Unassigned'; ?></div>
                                                                            <div class="text-muted small mb-2"><i data-feather="map-pin" class="icon-xs"></i> <?php echo (isset($trip['customer_address']))? $trip['customer_address'] : 'Unassigned'; ?></div>
                                                                        </div>

                                                                        <div class="col-12">
                                                                            <div class="table-responsive">
                                                                                <table class="table table-bordered bg-light">
                                                                                    <thead class="table-dark">
                                                                                        <tr>
                                                                                            <th>Description</th>
                                                                                            <th class="text-end">Rate</th>
                                                                                            <th class="text-end">Total</th>
                                                                                        </tr>
                                                                                    </thead>
                                                                                    <tbody>
                                                                                        <tr>
                                                                                            <td>Cost Price (Expense)</td>
                                                                                            <td class="text-end">₦ <?php echo number_format($trip['cost_price'], 1); ?></td>
                                                                                            <td class="text-end fw-bold text-danger">₦ <?php echo number_format($trip['cost_price'] * $trip['unit'], 1); ?></td>
                                                                                        </tr>
                                                                                        <tr>
                                                                                            <td>Selling Price (Revenue)</td>
                                                                                            <td class="text-end">₦ <?php echo number_format($trip['selling_price'], 1); ?></td>
                                                                                            <td class="text-end fw-bold text-success">₦ <?php echo number_format($trip['selling_price'] * $trip['unit'], 1); ?></td>
                                                                                        </tr>
                                                                                        <tr>
                                                                                            <td>Driver Allowance</td>
                                                                                            <td class="text-end">-</td>
                                                                                            <td class="text-end text-danger">₦ <?php echo number_format($trip['driver_allowence'], 2); ?></td>
                                                                                        </tr>
                                                                                    </tbody>
                                                                                    <tfoot class="bg-white">
                                                                                        <tr class="fs-5">
                                                                                            <?php 
                                                                                                $net_profit = ($trip['selling_price'] * $trip['unit']) - ($trip['cost_price'] * $trip['unit']) - $trip['driver_allowence'];
                                                                                            ?>
                                                                                            <th colspan="2" class="text-end">Net Trip Profit:</th>
                                                                                            <th class="text-end text-primary">₦ <?php echo number_format($net_profit, 2); ?></th>
                                                                                        </tr>
                                                                                    </tfoot>
                                                                                </table>
                                                                            </div>
                                                                        </div>

                                                                        <div class="col-12 mt-0">
                                                                            <div class="p-3 bg-light rounded d-flex justify-content-between fs-6">
                                                                                <span><strong>Scheduled:</strong> <?php echo date('d/m/Y', strtotime($trip['scheduled_start_time'])); ?></span>
                                                                                <span><strong>Completed:</strong> <?php echo (!empty($trip['actual_end_time']) && $trip['actual_end_time'] !== '0000-00-00 00:00:00' && $trip['actual_end_time'] !== '0000-00-00') ? date('d-m-Y', strtotime($trip['actual_end_time'])) : '<span class="badge bg-warning text-dark">Pending</span>'; ?>
                                                                                </span>
                                                                                <div class="d-flex flex-column">
                                                                                    <span class="fw-bold">Processed By: <?php echo $trip['processed_by']; ?></span>
                                                                                    <span class="text-muted">Edited By: <?php echo $trip['edit_by'] ?? 'Not Edited'; ?></span>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>

                                                            </div>
                                                        </div>
                                                    </div>
                                                    <?php 
                                                    $all_modals .= ob_get_clean(); 
                                                    $count++;} ?>
                                                </tbody>
                                            </table>
                                            <?php 
                                            // 4. ECHO MODALS AFTER TABLE IS CLOSED
                                            echo $all_modals; 
                                            ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </section>
                </section>

            </div>
<?php  include('inc/footer.php'); 
} else if (isset($_SESSION['user_type']) && $_SESSION['user_type'] == 'User') {
    $user_id = $_SESSION['user_id'];
    $business_id = $_SESSION['business_id'];
    $user = getUserId($user_id); ?>

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard</title>
    
    <link rel="stylesheet" href="assets/css/bootstrap.css">
    
    <link rel="stylesheet" href="assets/vendors/chartjs/Chart.min.css">
    <link rel="stylesheet" href="assets/vendors/simple-datatables/style.css">
    <link rel="stylesheet" href="assets/vendors/perfect-scrollbar/perfect-scrollbar.css">
    <link rel="stylesheet" href="assets/css/app.css">
    <link rel="shortcut icon" href="assets/images/favicon.png" type="image/x-icon">
</head>
<body>
    <div id="app">
        <?php include('inc/header.php'); ?>
        <main>
    <div class="container">

      <section class="section error-404 min-vh-100 d-flex flex-column align-items-center justify-content-center">
        <div class="text-center">
            <h1 class="fw-bold">The road to efficiency starts here.</h1>
            <h5 class="text-muted">Your dashboard is a blank canvas. Let's fuel your </br> fleet and get your records moving.</h5>
        </div>
      </section>

    </div>
  </main><!-- End #main -->
        
<?php include('inc/footer.php'); } else if (isset($_SESSION['user_type']) && $_SESSION['user_type'] == 'Vendor') {
$user_id = $_SESSION['user_id'];
$business_id = $_SESSION['business_id']; 
$user = getUserId($user_id);
    ?>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard</title>
    
    <link rel="stylesheet" href="assets/css/bootstrap.css">
    
    <link rel="stylesheet" href="assets/vendors/chartjs/Chart.min.css">
    <link rel="stylesheet" href="assets/vendors/simple-datatables/style.css">
    <link rel="stylesheet" href="assets/vendors/perfect-scrollbar/perfect-scrollbar.css">
    <link rel="stylesheet" href="assets/css/app.css">
    <link rel="shortcut icon" href="assets/images/favicon.png" type="image/x-icon">
</head>
<body>
    <div id="app">
        <?php 
        include'inc/header.php';// Main Query: Filter strictly by the logged-in vendor's ID
        $count = 1;
        $total_fleet_cost = 0; 
        $all_modals = ""; 

        $filter = $_GET['filter'] ?? 'month'; // Default to month
        $date_filter = ""; 

        // Handle Preset Filters
        if ($filter == 'day') {
            $date_filter = " AND DATE(date_performed) = CURDATE()";
        } elseif ($filter == 'week') {
            $date_filter = " AND YEARWEEK(date_performed, 1) = YEARWEEK(CURDATE(), 1)";
        } elseif ($filter == 'month') {
            $date_filter = " AND MONTH(date_performed) = MONTH(CURDATE()) AND YEAR(date_performed) = YEAR(CURDATE())";
        } elseif ($filter == 'year') {
            $date_filter = " AND YEAR(date_performed) = YEAR(CURDATE())";
        } 
        // Handle Custom Range
        elseif ($filter == 'custom' && !empty($_GET['start_date']) && !empty($_GET['end_date'])) {
            $start = mysqli_real_escape_string($conn, $_GET['start_date']);
            $end = mysqli_real_escape_string($conn, $_GET['end_date']);
            $date_filter = " AND date_performed BETWEEN '$start' AND '$end'";
        }
                                                            

        // Optimized Query: Gets latest record AND total spent per truck
        $query = "SELECT m.*, 
          tr.license_plate,
          stats.total_spent_on_this_truck
          FROM maintenance m
          LEFT JOIN trucks tr ON m.truck_id = tr.truck_id
          LEFT JOIN (
              SELECT vendor_id, SUM(cost) as total_spent_on_this_truck 
              FROM maintenance 
              WHERE vendor_id = '$user_id' AND vendor_status = 1
          ) stats ON m.vendor_id = stats.vendor_id
          WHERE m.vendor_id = '$user_id' $date_filter
          ORDER BY m.date_performed DESC";

        $main_sql = Querydb($query);
        $main_sql_r = mysqli_fetch_assoc($main_sql);
        $total_pending = 0;
        $total_paid = 0;

        foreach ($main_sql as $maintence) {
            if ($maintence['vendor_status'] == 1) {
                $total_paid += $maintence['cost'];
            } else {
                $total_pending += $maintence['cost'];
            }
        }

         ?>
    <div class="container-fluid">
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card bg-warning text-dark shadow border-0">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="text-uppercase mb-1 small fw-bold">Total Pending</h6>
                                <h3 class="mb-0">₦ <?php echo number_format($total_pending, 2); ?></h3>
                            </div>
                            <i data-feather="clock" class="text-dark-50"></i>
                        </div>
                        <div class="mt-2">
                            <small>For the <?php echo ucfirst($filter); ?></small>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-6">
                <div class="card bg-success text-white shadow border-0">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="text-uppercase mb-1 small fw-bold">Total Paid</h6>
                                <h3 class="mb-0">₦ <?php echo number_format($total_paid, 2); ?></h3>
                            </div>
                            <i data-feather="check-circle"></i>
                        </div>
                        <div class="mt-2">
                            <small>Received payments</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    <!-- <div class="card shadow-sm">
        <div class="card-header bg-white">
            <h5 class="mb-0">My Service Records</h5>
        </div>
        <div class="table-responsive p-3">
            <table class="table table-hover" id="vendorTable">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Truck License</th>
                        <th>Service Provided</th>
                        <th>Cost</th>
                        <th>Description</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($vendor_data as $row): ?>
                    <tr>
                        <td><?php echo date('d M, Y', strtotime($row['date_performed'])); ?></td>
                        <td><span class="badge bg-light text-dark border"><?php echo $row['license_plate']; ?></span></td>
                        <td><?php echo $row['service_type']; ?></td>
                        <td class="fw-bold">₦ <?php echo number_format($row['cost'], 2); ?></td>
                        <td><small class="text-muted"><?php echo $row['description']; ?></small></td>
                        <td>
                            <?php if($row['is_paid'] == 1): ?>
                                <span class="badge bg-success">Paid</span>
                            <?php else: ?>
                                <span class="badge bg-warning text-dark">Pending</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div> -->
        <section class="section">
            <div class="row mb-4">
                <div class="">
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h4 class="card-title"> Expense Record</h4>
                            <!-- <div class="d-flex ">
                                <button type="button" class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#maintencemodal"><i data-feather="plus"></i> Create New Expense</button>
                            </div> -->
                        </div>
                        <div class="row mb-3 align-items-end">
                            <div class="col-md-12">
                                <form id="filterForm" method="GET" action="" class="p-3 rounded border">
                                    <div class="row align-items-end g-2">
                                        <div class="col-md-3">
                                            <label class="small fw-bold text-muted">Filter Type</label>
                                            <select name="filter" id="filterSelect" class="form-select form-select-sm" onchange="toggleDateInputs()">
                                                <option value="day" <?php if($filter == 'day') echo 'selected'; ?>>Today</option>
                                                <option value="week" <?php if($filter == 'week') echo 'selected'; ?>>This Week</option>
                                                <option value="month" <?php if($filter == 'month') echo 'selected'; ?>>This Month</option>
                                                <option value="year" <?php if($filter == 'year') echo 'selected'; ?>>This Year</option>
                                                <option value="custom" <?php if($filter == 'custom') echo 'selected'; ?>>Custom Range</option>
                                            </select>
                                        </div>

                                        <div id="customDates" class="col-md-7 <?php echo ($filter == 'custom') ? '' : 'd-none'; ?>">
                                            <div class="row g-2">
                                                <div class="col-6">
                                                    <label class="small fw-bold text-muted">Start Date</label>
                                                    <input type="date" name="start_date" class="form-control form-control-sm" value="<?php echo $_GET['start_date'] ?? ''; ?>">
                                                </div>
                                                <div class="col-6">
                                                    <label class="small fw-bold text-muted">End Date</label>
                                                    <input type="date" name="end_date" class="form-control form-control-sm" value="<?php echo $_GET['end_date'] ?? ''; ?>">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-2">
                                            <button type="submit" class="btn btn-sm btn-dark w-100">Apply Filter</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                        <div class="card-body px-0 pb-0">
                            <div class="" id="">
                                <div class="table-responsive p-3">
                                    <table class="table" id="table1">
                                        <thead>
                                            <tr>
                                                <th>Date</th>
                                                <th>Truck License</th>
                                                <th>Service Provided</th>
                                                <th>Cost</th>
                                                <th>Description</th>
                                                <th>Status</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($main_sql as $row): ?>
                                            <tr>
                                                <td><?php echo date('d M, Y', strtotime($row['date_performed'])); ?></td>
                                                <td><span class="badge bg-light text-dark border"><?php echo $row['license_plate']; ?></span></td>
                                                <td><?php echo $row['service_type']; ?></td>
                                                <td class="fw-bold">₦ <?php echo number_format($row['cost'], 2); ?></td>
                                                <td><small class="text-muted"><?php echo $row['description']; ?></small></td>
                                                <td>
                                                    <?php if($row['vendor_status'] == 1): ?>
                                                        <span class="badge bg-success">Paid</span>
                                                    <?php else: ?>
                                                        <span class="badge bg-warning text-dark">Pending</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php if ($row['vendor_status'] == 0) { ?>
                                                    <button type="button" class="btn btn-sm btn-success" id="btn-pay" data-id="<?php echo $row['maintenance_id']; ?>">
                                                        Mark as Paid
                                                    </button>
                                                    <?php } ?>
                                                    <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#viewModal<?php echo $count; ?>">
                                                        <i data-feather="eye"></i> View
                                                    </button>
                                                </td>
                                            </tr>   

                                                <?php 
                                                // 3. CAPTURE MODALS IN A VARIABLE (Buffered)
                                                ob_start(); ?>
                                                <div class="modal fade" id="viewModal<?php echo $count; ?>" tabindex="-1">
                                                    <div class="modal-dialog modal-dialog-centered">
                                                        <div class="modal-content">
                                                        <div class="modal-header">
                                                            <h4 class="modal-title">View maintence</h4>
                                                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                        </div>
                                                        <div class="modal-body">
                                                            <div class="card-body">
                                                                    <div class="row mb-3">
                                                                        <div class="col-lg-4 col-md-4 text-muted small fw-bold">Truck License</div>
                                                                        <div class="col-lg-8 col-md-8">
                                                                            <h5 class="fw-bold text-dark"><?php echo $row['license_plate']; ?></h5>
                                                                        </div>
                                                                    </div>

                                                                    <div class="row mb-3">
                                                                        <div class="col-lg-4 col-md-4 text-muted small fw-bold">Service Type</div>
                                                                        <div class="col-lg-8 col-md-8">
                                                                            <span class="badge bg-light-primary text-primary"><?php echo $row['service_type']; ?></span>
                                                                        </div>
                                                                    </div>

                                                                    <div class="row mb-3">
                                                                        <div class="col-lg-4 col-md-4 text-muted small fw-bold">This Service Cost</div>
                                                                        <div class="col-lg-8 col-md-8 text-danger fw-bold">
                                                                            ₦ <?php echo number_format($row['cost'], 2); ?>
                                                                        </div>
                                                                    </div>

                                                                    <div class="row mb-3">
                                                                        <div class="col-lg-4 col-md-4 text-muted small fw-bold">Vendor Details</div>
                                                                        
                                                                        <?php 
                                                                            $v_id = $row['vendor_id'];
                                                                            
                                                                            // Only add the ID filter if it's a specific registered vendor (not 0 or empty)
                                                                            $AND = (!empty($v_id) && $v_id != 0) ? " AND user_id = '$v_id'" : " AND user_id = -1"; // -1 ensures no match if it's 'Other'
                                                                            
                                                                            $vendor_d = Querydb("SELECT * FROM users WHERE role_id = 3 $AND LIMIT 1");
                                                                            $vendor_chk = mysqli_fetch_assoc($vendor_d);
                                                                        ?>

                                                                        <div class="col-lg-8 col-md-8 text-success fw-bold">
                                                                            <?php 
                                                                                if ($v_id == 0 || !$vendor_chk) {
                                                                                    echo "Other / External Vendor";
                                                                                } else {
                                                                                    echo htmlspecialchars($vendor_chk['first_name'] . ' ' . $vendor_chk['last_name']); 
                                                                                }
                                                                            ?>
                                                                        </div>
                                                                    </div>

                                                                    <div class="row mb-3">
                                                                        <div class="col-lg-4 col-md-4 text-muted small fw-bold">Date Performed</div>
                                                                        <div class="col-lg-8 col-md-8">
                                                                            <?php echo date('M d, Y', strtotime($row['date_performed'])); ?>
                                                                        </div>
                                                                    </div>

                                                                    <div class="row mb-3">
                                                                        <div class="col-lg-4 col-md-4 text-muted small fw-bold">Work Description</div>
                                                                        <div class="col-lg-8 col-md-8">
                                                                            <p class="text-secondary small bg-light p-2 rounded"><?php echo $row['description']; ?></p>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>

                                                        </div>
                                                    </div>
                                                    
                                                </div>
                                                <?php 
                                                $all_modals .= ob_get_clean(); 
                                                $count++; 
                                            endforeach; ?>
                                        </tbody>
                                    </table>

                                    <?php 
                                    // 4. ECHO MODALS AFTER TABLE IS CLOSED
                                    echo $all_modals; 
                                    ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
</div>
<?php include('inc/footer.php'); } else {
    session_unset();
    session_destroy();
    header('Location: auth-login.html');
    exit;
}
?>
