<?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="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>ATC 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">ATC Record</li>
                        </ol>
                    </nav>
                </div> 
                <div class="row g-3 mb-4"> <?php 
                    $query = "SELECT type, volume, COUNT(*) as count 
                              FROM atc_records
                              WHERE atc_status = 'Open' 
                              AND business_id = '$business_id'
                              GROUP BY type, volume 
                              ORDER BY volume DESC";
                    
                    $stmt = Querydb($query);
                    $grand_total_calc = 0;
                    $rows = [];

                    while ($row = mysqli_fetch_assoc($stmt)) {
                        $rows[] = $row;
                    }

                    if (!empty($rows)):
                        foreach($rows as $row) {
                            $base_vol = (float)$row['volume'];
                            $record_count = (int)$row['count'];

                            // Assigning color and multiplier labels based on volume
                            if ($base_vol >= 900) {
                                $label_color = "text-primary";
                                $bg_light = "bg-primary-soft";
                            } elseif ($base_vol >= 600) {
                                $label_color = "text-info";
                                $bg_light = "bg-info-soft";
                            } else {
                                $label_color = "text-secondary";
                                $bg_light = "bg-light";
                            }

                            // Calculation: Volume * Number of Records
                            $calculated_sum = $base_vol * $record_count;
                            $grand_total_calc += $calculated_sum;
                    ?>
                        <div class="col-lg-3"> 
                            <div class="card shadow-sm border-0">
                                <div class="card-body px-4">
                                    <div class="d-flex justify-content-between align-items-start mb-3">
                                        <div>
                                            <span class="responsive-text text-uppercase fw-bold text-muted tracking-wider">Product Type</span>
                                            <h3 class="fw-bold mb-0 <?php echo $label_color; ?>">
                                                <?php echo htmlspecialchars($row['type']); ?>
                                            </h3>
                                        </div>
                                        <span class="badge fs-4 fs-lg-1 rounded-pill <?php echo $bg_light; ?> <?php echo $label_color; ?> px-3">
                                            Size: <?php echo $base_vol; ?>
                                        </span>
                                    </div>

                                    <div class="pt-3 border-top">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <span class="d-block fw-bold text-dark fs-5"><?php echo number_format($record_count); ?></span>
                                                <small class="text-muted">Active Records</small>
                                            </div>
                                            <div class="text-end">
                                                <span class="d-block fw-bold text-dark fs-5"><?php echo number_format($calculated_sum); ?></span>
                                                <small class="text-muted">Total Volume</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-footer bg-light border-0 py-2">
                                    <small class="text-muted p-0 italic">Calculation: <?php echo $base_vol; ?> × <?php echo $record_count; ?></small>
                                </div>
                            </div>
                        </div>
                    <?php }; ?>
                    
                    <div class="col-12">
                        <div class="bg-dark text-white p-3 rounded shadow-sm d-flex justify-content-between align-items-center">
                            <span class="text-uppercase small fw-bold opacity-75">Aggregate Calculated Sum (All Products)</span>
                            <span class="h3 mb-0 fw-bold text-white"><?php echo number_format($grand_total_calc); ?> Units</span>
                        </div>
                    </div>

                    <?php else: ?>
                        <div class="col-12 text-center py-5">
                            <i class="bi bi-inbox text-muted fs-1"></i>
                            <p class="text-muted mt-2">No active records found for this business.</p>
                        </div>
                    <?php endif; ?>
                </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">ATC Record</h4>
                                    <div class="d-flex ">
                                        <button type="button" class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#addatcrecord"><i data-feather="plus"></i> Create New ATC</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>Units/Begs</th>
                                                    <th>Truck</th>
                                                    <th>Type</th>
                                                    <th>Status</th>
                                                    <th>Date</th>
                                                    <th>Action</th>

                                                </tr>
                                            </thead>
                                            <tbody class="text-center">
                                                <?php 
                                                $count = 1;
                                                $sql = Querydb("SELECT a.*, t.truck_id, t.driver_id, tr.license_plate, d.first_name, d.last_name from atc_records a left join trips t on a.atc_id = t.atc_id LEFT JOIN trucks tr ON t.truck_id = tr.truck_id LEFT JOIN drivers d ON t.driver_id = d.driver_id where a.business_id = '$business_id' ORDER BY a.atc_id DESC");
                                                foreach ($sql as $atc) {
                                                 ?>
                                                <tr>
                                                    <td><?php echo $count; ?></td>
                                                    <td><?php echo $atc['atc_number']; ?></td>
                                                    <td><?php echo $atc['volume']; ?></td>
                                                    <td>
                                                        <i class="fa fa-truck small me-1"></i> <?php echo $atc['license_plate'] ?? 'Unassigned'; ?><br>
                                                        <i class="fa fa-user small me-1"></i> <?php echo $atc['first_name'] ? $atc['first_name'].' '.$atc['last_name'] : 'No Driver'; ?></td>
                                                    <td><?php echo $atc['type']; ?></td>
                                                    <td><?php echo $atc['atc_status']; ?></td>
                                                    <td><?php echo date('Y-M-d', $atc['create_at']); ?></td>
                                                    <td>
                                                        <div class="btn-group"><?php
                                                            if($atc['atc_status'] == 'Open'){ ?>
                                                            <button type="submit" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#editatcModal<?php echo $atc['atc_id']; ?>"><i data-feather="edit"></i> Edit</button>
                                                            <button type="button" class="btn btn-outline-success" data-bs-toggle="modal" data-bs-target="#edittripModal<?php echo $count; ?>"><i data-feather="plus"></i> Assign Truck</button>
                                                            <?php } ?>
                                                            <button type="button" class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#viewatcModal<?php echo $atc['atc_id']; ?>"><i data-feather="eye"></i> Preview</button>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <!-- Edit ATC Modal -->
                                                <div class="modal" id="editatcModal<?php echo $atc['atc_id']; ?>">
                                                    <div class="modal-dialog modal-dialog-centered">
                                                        <div class="modal-content">
                                                        <div class="modal-header">
                                                            <h4 class="modal-title">Edit User</h4>
                                                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                        </div>
                                                        <div class="modal-body">
                                                            <form class="row g-3 needs-validation" novalidate>
                                                                <div class="col-12">
                                                                    <div class="row mt-3 mb-3">
                                                                        <input type="hidden" name="id" id="atc_id_<?php echo $count; ?>" value="<?php echo $atc['atc_id']; ?>">
                                                                        <div class="col-12">
                                                                            <label for="atc_num_" class="form-label">ATC Number</label>
                                                                            <input type="text" class="form-control" id="atc_num_<?php echo $count; ?>" value="<?php echo $atc['atc_number']; ?>">
                                                                        </div>
                                                                        <div class="col-6">
                                                                            <label for="volume_" class="form-label">Volume</label>
                                                                            <input type="text" class="form-control" id="volume_<?php echo $count; ?>" value="<?php echo $atc['volume']; ?>">
                                                                        </div>
                                                                        <div class="col-6">
                                                                            <label for="type_" class="form-label">Type of Product</label>
                                                                            <input type="text" class="form-control" id="type_<?php echo $count; ?>" value="<?php echo $atc['type']; ?>">
                                                                        </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="editatcModalbtn_<?php echo $count; ?>">Submit</button> 
                                                        </div>

                                                        </div>
                                                    </div>
                                                </div>
                                                <!-- View ATC Modal --> 
                                                <div class="modal fade" id="viewatcModal<?php echo $atc['atc_id']; ?>" tabindex="-1">
                                                    <div class="modal-dialog modal-dialog-centered">
                                                        <div class="modal-content border-0 shadow">
                                                            <div class="modal-header">
                                                                <h5 class="modal-title fw-bold text-dark">
                                                                    <i class="bi bi-file-earmark-text me-2"></i>ATC Record Details
                                                                </h5>
                                                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                            </div>
                                                            <div class="modal-body p-4">
                                                                <div class="d-flex justify-content-between border-bottom pb-2 mb-3">
                                                                    <span class="text-muted fw-medium">ATC Number</span>
                                                                    <span class="fw-bold text-primary">#<?php echo $atc['atc_number']; ?></span>
                                                                </div>

                                                                <div class="d-flex justify-content-between border-bottom pb-2 mb-3">
                                                                    <span class="text-muted fw-medium">Type of Product</span>
                                                                    <span class="text-dark"><?php echo $atc['type']; ?></span>
                                                                </div>

                                                                <div class="d-flex justify-content-between border-bottom pb-2 mb-3">
                                                                    <span class="text-muted fw-medium">Volume</span>
                                                                    <span class="badge bg-info-soft text-info px-3"><?php echo $atc['volume']; ?> Units</span>
                                                                </div>

                                                                <div class="d-flex justify-content-between border-bottom pb-2 mb-3">
                                                                    <span class="text-muted fw-medium">Status</span>
                                                                    <?php $statusClass = ($atc['atc_status'] == 'Active') ? 'bg-success' : 'bg-warning'; ?>
                                                                    <span class="badge <?php echo $statusClass; ?> rounded-pill"><?php echo $atc['atc_status']; ?></span>
                                                                </div>

                                                                <div class="mt-4 pt-2 border-top">
                                                                    <h6 class="fw-bold text-secondary mb-3"><i class="bi bi-truck me-2"></i>Logistics Assignment</h6>
                                                                    
                                                                    <?php 
                                                                    // Use the PHP function we created earlier
                                                                    $trip = getTripByAtcAndBusiness($atc['atc_id'], $atc['business_id']); 
                                                                    
                                                                    if ($trip) { ?>
                                                                        <div class="card bg-light border-0">
                                                                            <div class="card-body p-3">
                                                                                <div class="row align-items-center">
                                                                                    <div class="col-6 border-end">
                                                                                        <small class="text-muted d-block">Truck / Plate</small>
                                                                                        <span class="fw-bold"><?php echo $trip['license_plate']; ?></span>
                                                                                    </div>
                                                                                    <div class="col-6">
                                                                                        <small class="text-muted d-block">Driver</small>
                                                                                        <span class="fw-bold"><?php echo $trip['driver_name']; ?></span>
                                                                                    </div>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                    <?php } else { ?>
                                                                        <div class="alert alert-light border border-dashed d-flex align-items-center py-2">
                                                                            <i class="bi bi-exclamation-circle me-2"></i>
                                                                            <small class="text-muted">No truck or driver assigned to this trip.</small>
                                                                        </div>
                                                                    <?php } ?>
                                                                </div>

                                                                <div class="d-flex justify-content-between mt-4">
                                                                    <span class="text-muted fw-medium">Onboarded By</span>
                                                                    <?php $user = getUserId($atc['user_id']); ?>
                                                                    <span class="fw-bold text-dark">
                                                                        <i class="bi bi-person-circle me-1"></i>
                                                                        <?php echo $user['first_name'] . ' ' . $user['last_name']; ?>
                                                                    </span>
                                                                </div>
                                                            </div>
                                                            <div class="modal-footer border-0">
                                                                <button type="button" class="btn btn-secondary w-100 btn-sm" data-bs-dismiss="modal">Close</button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="modal" id="edittripModal<?php echo $count; ?>">
                                                    <div class="modal-dialog modal-dialog-centered">
                                                        <div class="modal-content">
                                                        <div class="modal-header">
                                                            <h4 class="modal-title">Add Truck/Drive</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="truck_no_column">Truck license Number</label>
                                                                            <select class="choices form-select truck_license_plate" id="truck_license_plate-<?php echo $count; ?>" name="truck_id">
                                                                                <option value="" disabled selected>Select Truck license Number</option>
                                                                                <?php 
                                                                                $sql = Querydb("select * from trucks where current_status = 'In Service' AND business_id = '$business_id'");
                                                                                foreach ($sql as $truck) { ?>
                                                                                <option value="<?php echo $truck['truck_id']; ?>" <?php if($atc['truck_id'] ==  $truck['truck_id']){echo 'selected';} ?> data-driver-id="<?php echo htmlspecialchars($truck['driver_id']); ?>"><?php echo $truck['license_plate']; ?></option>
                                                                                <?php } ?>
                                                                            </select>
                                                                            <input type="hidden" class="truck_driver_id" id="truck_driver_id-<?php echo $count; ?>" name="driver_id" value="">
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-md-6 col-12">
                                                                        <div class="form-group">
                                                                            <label for="atc-column">ATC Number</label>
                                                                            <input type="hidden" name="product_name" value="<?php echo $atc['type']; ?>">
                                                                            <input type="hidden" name="volume" value="<?php echo $atc['volume']; ?>">
                                                                            <input type="hidden" name="atc_id" value="<?php echo $atc['atc_id'] ;?>">
                                                                            <input class="choices form-control" id="atc_colum_<?php echo $count; ?>" value="<?php echo $atc['atc_number'] ?>" readonly>
                                                                        </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 type="button" class="btn btn-primary btn-submit-trip" data-form-id="createTripForm_<?php echo $count; ?>">
                                                                Assign Truck
                                                            </button> 
                                                        </div>

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