<?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>Assign Logistics & Fuel</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" type="text/css" 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>Assign Logistics & Fuel Record</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">Assign Logistics & Fuel</li>
                        </ol>
                    </nav>
                </div>
                
                <div class="card shadow rounded-4">
                    <div class="card-body">
                        <h5 class="card-title">Active Logistics & Fueling</h5>
                        <div class="table-responsive">
                            <table class="table table-hover align-middle mt-3" id="table1">
                                <thead>
                                    <tr>
                                        <th>ATC / Trip</th>
                                        <th>Truck & Driver</th>
                                        <th>Fuel Info</th>
                                        <th>Date</th>
                                        <th>Status</th>
                                        <th class="text-center">Action</th>
                                    </tr>
                                </thead>
                                <tbody class="text-center">
                                    <?php 
                                    $sql = Querydb("SELECT t.*, c.name, tk.license_plate, tk.initial_fuel, d.first_name, d.last_name, a.atc_number 
                                                   FROM trips t
                                                   LEFT JOIN trucks tk ON t.truck_id = tk.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
                                                   JOIN customers c ON t.customer_id = c.customer_id
                                                   WHERE t.business_id = $business_id
                                                   ORDER BY t.trip_id DESC");

                                    foreach ($sql as $row) { ?>
                                    <tr>
                                        <td>
                                            <span class="fw-bold d-block"><?php echo $row['atc_number']; ?></span>
                                            <small class="text-muted">Customer Name: <?php echo $row['name']; ?></small>
                                        </td>
                                        <td>
                                            <i class="fa fa-truck small me-1"></i> <?php echo $row['license_plate'] ?? 'Unassigned'; ?><br>
                                            <i class="fa fa-user small me-1"></i> <?php echo $row['first_name'] ? $row['first_name'].' '.$row['last_name'] : 'No Driver'; ?>
                                        </td>
                                        <td>
                                            <span class="badge bg-soft-info text-info">
                                                <?php echo $row['liters_filled']; ?> Ltrs @ <?php echo $row['filling_station'] ?: 'N/A'; ?>
                                            </span>
                                            <div class="small fw-bold mt-1">₦<?php echo number_format($row['cost_per_liter'], 2); ?></div>
                                        </td>
                                        <td><?php echo $row['date_filled'] ?: 'N/A'; ?></td>
                                        <td>
                                            <span class="badge <?php echo ($row['status'] == 'In Progress') ? 'bg-primary' : 'bg-success'; ?>">
                                                <?php echo $row['status']; ?>
                                            </span>
                                        </td>
                                        <td class="text-center ">
                                            <?php if ($_SESSION['user_type'] == 'Admin') { ?>
                                            <div class="btn-group">
                                                <button class="btn btn-sm btn-outline-primary px-3" 
                                                        onclick="openEditModal(<?php echo htmlspecialchars(json_encode($row)); ?>)">
                                                    <i class="fa fa-edit"></i> Edit
                                                </button>
                                                <button type="button" onclick="previewAssignment(<?php echo htmlspecialchars(json_encode($row)); ?>)" class="btn btn-outline-dark w-100 py-2 fw-bold">
                                                    <i class="fa fa-eye"></i> Preview 
                                                </button>
                                            </div>
                                            <?php } else if ($row['liters_filled'] != 0.00 && $_SESSION['user_type'] != 'Admin') { ?>
                                            <div class="btn-group">
                                                <button type="button" onclick="previewAssignment(<?php echo htmlspecialchars(json_encode($row)); ?>)" class="btn btn-outline-dark w-100 py-2 fw-bold">
                                                    <i class="fa fa-eye"></i> Preview 
                                                </button>
                                            </div>
                                            <?php } else { ?>
                                            <div class="btn-group">
                                                <button class="btn btn-sm btn-outline-primary px-3" 
                                                        onclick="openEditModal(<?php echo htmlspecialchars(json_encode($row)); ?>)">
                                                    <i class="fa fa-edit"></i> Edit
                                                </button>
                                                <button type="button" onclick="previewAssignment(<?php echo htmlspecialchars(json_encode($row)); ?>)" class="btn btn-outline-dark w-100 py-2 fw-bold">
                                                    <i class="fa fa-eye"></i> Preview 
                                                </button>
                                            </div>
                                            <?php } ?>                                                
                                        </td>
                                    </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <div class="modal fade" id="editAssignmentModal" tabindex="-1" aria-hidden="true">
                    <div class="modal-dialog modal-lg">
                        <form id="updateAssignmentForm" class="modal-content">
                            <div class="modal-header text-white">
                                <h5 class="modal-title">Modify Trip Assignment & Fuel</h5>
                                <button type="button" class="btn-close btn-close-dark" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                <input type="hidden" name="trip_id" id="edit_trip_id">
                                
                                <div class="mb-4 p-3 bg-light rounded">
                                    <label class="form-label fw-bold text-primary">ATC / Trip Reference</label>
                                    <input type="text" class="form-control-plaintext fw-bold text-white fs-5" id="edit_atc_display" readonly>
                                </div>

                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label class="form-label fw-bold">Assign Truck</label>
                                        <select class="form-select" name="truck_id" id="edit_truck_id" disabled>
                                            <?php 
                                            $current_tid = $row['truck_id'];
                                            $trucks = Querydb("SELECT * FROM trucks WHERE business_id = '$business_id' AND current_status = 'In Service' OR (truck_id = '$current_tid')");

                                            foreach($trucks as $tk) {
                                                $selected = ($tk['truck_id'] == $current_tid) ? 'selected' : '';
                                                $plate = htmlspecialchars($tk['license_plate']);
                                                $tid = htmlspecialchars($tk['truck_id']);
                                                echo "<option value='{$tid}' {$selected}>{$plate}</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label fw-bold">Assign Driver</label>
                                        <select class="form-select" name="driver_id" id="edit_driver_id" required>
                                            <?php 
                                            echo $current_driver_id = $row['driver_id'] ?? 0;                                            
                                            $drivers = Querydb("SELECT * FROM drivers WHERE business_id = '$business_id' AND (driver_id = '$current_driver_id') OR is_active = 0");
                                            
                                            foreach($drivers as $dr) {
                                               $full_name = htmlspecialchars($dr['first_name'] . ' ' . $dr['last_name']);
                                               $selected = ($dr['driver_id'] == $current_driver_id) ? 'selected' : '';
                                                
                                                echo "<option value='{$dr['driver_id']}' {$selected}>{$full_name}</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>

                                    <div class="col-md-12 mt-4">
                                        <h6 class="border-bottom pb-2 text-muted">Fueling Details</h6>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label fw-bold">Fuel Station</label>
                                        <input type="text" class="form-control" name="filling_station" id="edit_filling_station" placeholder="e.g. TotalEnergies">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label fw-bold">Date Filled</label>
                                        <input type="date" class="form-control" name="date_filled" id="edit_date_filled" required>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label fw-bold">Initial Fuel (Ltrs)</label>
                                        <input type="number" step="0.01" class="form-control calc-trigger" name="initial_fuel" id="edit_initial_fuel" placeholder="Current in tank" required>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label fw-bold">Liters Filled</label>
                                        <input type="number" step="0.01" class="form-control calc-trigger" name="liters_filled" id="edit_liters_filled" required>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label fw-bold">Cost Per Liter (₦)</label>
                                        <input type="number" step="0.01" class="form-control calc-trigger" name="cost_per_liter" id="edit_cost_per_liter" required>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label small fw-bold">Liters Used</label>
                                        <input type="number" step="0.01" class="form-control fw-bold" name="used_liters" id="edit_used_liters" required>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label fw-bold">Total Balance (Ltrs)</label>
                                        <input type="text" class="form-control fw-bold text-success" id="edit_fuel_balance" readonly>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label fw-bold">Total Cost (₦)</label>
                                        <input type="text" class="form-control" id="edit_total_cost" readonly>
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                <button type="submit" class="btn btn-primary px-4">Save Changes</button>
                            </div>
                        </form>
                    </div>
                </div>
                <div class="modal fade" id="previewTripModal" tabindex="-1" aria-hidden="true">
                    <div class="modal-dialog modal-dialog-centered modal-lg">
                        <div class="modal-content border-0 shadow-lg">
                            <div class="modal-header text-white">
                                <h5 class="modal-title"><i class="fa fa-file-invoice me-2"></i>Trip Dispatch Preview</h5>
                                <button type="button" class="btn-close btn-close-dark" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body p-4" id="printArea">
                                <div class="d-flex justify-content-between border-bottom pb-3 mb-4">
                                    <div>
                                        <h6 class="text-uppercase text-muted mb-1">ATC Number</h6>
                                        <h3 class="fw-bold text-primary" id="p_atc">---</h3>
                                    </div>
                                    <div class="text-end">
                                        <h6 class="text-uppercase text-muted mb-1">Current Status</h6>
                                        <span id="p_status" class="badge fs-6">---</span>
                                    </div>
                                </div>

                                <div class="row g-4">
                                    <div class="col-md-6">
                                        <div class="p-3 border rounded-3">
                                            <h6 class="fw-bold mb-3"><i class="fa fa-truck me-2"></i> Logistics</h6>
                                            <p class="mb-1 text-muted">Truck Assigned:</p>
                                            <h5 id="p_truck" class="fw-bold">---</h5>
                                            <hr>
                                            <p class="mb-1 text-muted">Driver Name:</p>
                                            <h5 id="p_driver" class="fw-bold">---</h5>
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="p-3 border rounded-3">
                                            <h6 class="fw-bold mb-3"><i class="fa fa-gas-pump me-2"></i> Fuel Details</h6>
                                            <div class="d-flex justify-content-between">
                                                <span>Initial:</span> <strong id="p_initial">0.00</strong>
                                            </div>
                                            <div class="d-flex justify-content-between">
                                                <span>Liter used:</span> <strong id="p_used">₦0.00</strong>
                                            </div>
                                            <div class="d-flex justify-content-between">
                                                <span>Liters:</span> <strong id="p_liters">0.00</strong>
                                            </div>
                                            <div class="d-flex justify-content-between">
                                                <span>Rate:</span> <strong id="p_rate">₦0.00</strong>
                                            </div>
                                            <hr>
                                            <div class="d-flex justify-content-between">
                                                <span>Total Cost:</span> <h5 class="text-success fw-bold" id="p_total">₦0.00</h5>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="mt-4">
                                    <p class="text-muted small"><i class="fa fa-map-marker-alt me-1"></i> Station: <span id="p_station" class="text-dark fw-bold">---</span></p>
                                    <p class="text-muted small"><i class="fa fa-calendar-alt me-1"></i> Date: <span id="p_date" class="text-dark fw-bold">---</span></p>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary w-100 px-4" data-bs-dismiss="modal">Close Preview</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php  include('inc/footer.php'); 
            } else {
                header('Location: pages-error-404.html');
                exit;
            }
        ?>
