<?php include 'inc/funtions.php';
if (isset($_SESSION['user_type'])) {
    $user_id = $_SESSION['user_id'];
    $business_id = $_SESSION['business_id'];
    $user = getUserId($user_id);
    $pages_allowed = check_page_access();
?>

<!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="stylesheet" href="assets/vendors/select2/select2.min.css"> -->
    <link rel="shortcut icon" href="assets/images/favicon.png" type="image/x-icon">
</head>
<body>
    <div id="app">
        <?php include('inc/header.php'); ?>            
            <div class="main-content container-fluid">
                <div class="mb-4">
                    <h3>Logistics</h3>
                    <nav aria-label="breadcrumb" class='breadcrumb-header'>
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                            <li class="breadcrumb-item active" aria-current="page">Logistics</li>
                        </ol>
                    </nav>
                </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']; ?>">
                                                                    <input type="hidden" id="order_id_<?php echo $count; ?>" value="<?php echo $trip['order_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>

            </div>
<?php  include('inc/footer.php'); 
} else {
    header('Location: pages-error-404.html');
    exit;
}?>
