<?php include 'inc/funtions.php';
if (isset($_SESSION['user_type']) && $_SESSION['user_type'] == 'Admin' && $_SESSION['role_id'] == 1) {
    $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>Assigning Rates </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 mb-4 shadow-sm border-0">
                <div class="card-body">
                    <form method="GET" action="" class="row align-items-end g-3">
                        <div class="col-md-2">
                            <label class="form-label small fw-bold">Period</label>
                            <select name="period" class="form-select" onchange="toggleCustomDate(this.value)">
                                <option value="all" <?php echo (!isset($_GET['period']) || $_GET['period'] == 'all') ? 'selected' : ''; ?>>All Time</option>
                                <option value="day" <?php echo (isset($_GET['period']) && $_GET['period'] == 'day') ? 'selected' : ''; ?>>Today</option>
                                <option value="week" <?php echo (isset($_GET['period']) && $_GET['period'] == 'week') ? 'selected' : ''; ?>>This Week</option>
                                <option value="month" <?php echo (isset($_GET['period']) && $_GET['period'] == 'month') ? 'selected' : ''; ?>>This Month</option>
                                <option value="year" <?php echo (isset($_GET['period']) && $_GET['period'] == 'year') ? 'selected' : ''; ?>>This Year</option>
                                <option value="custom" <?php echo (isset($_GET['period']) && $_GET['period'] == 'custom') ? 'selected' : ''; ?>>Custom</option>
                            </select>
                        </div>

                        <div class="col-md-3">
                            <label class="form-label small fw-bold">Customer</label>
                            <select name="customer_id" class="form-select select2">
                                <option value="">All Customers</option>
                                <?php 
                                $customers = Querydb("SELECT customer_id as customers, name FROM customers WHERE business_id = $business_id");
                                foreach($customers as $c) {
                                    $selected = (isset($_GET['customers']) && $_GET['customers'] == $c['customers']) ? 'selected' : '';
                                    echo "<option value='".$c['customers']."' $selected>".$c['name']."</option>";
                                }
                                ?>
                            </select>
                        </div>
                        
                        <div id="customDateRange" class="col-md-4 <?php echo (isset($_GET['period']) && $_GET['period'] == 'custom') ? '' : 'd-none'; ?>">
                            <div class="row">
                                <div class="col-6">
                                    <label class="form-label small fw-bold">Start</label>
                                    <input type="date" name="start_date" class="form-control" value="<?php echo $_GET['start_date'] ?? ''; ?>">
                                </div>
                                <div class="col-6">
                                    <label class="form-label small fw-bold">End</label>
                        
                                    <input type="date" name="end_date" class="form-control" value="<?php echo $_GET['end_date'] ?? ''; ?>">
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="btn-group w-100">
                                <button type="submit" class="btn btn-dark">Filter</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <?php
            $filter_query = "";
            $date_column = "t.create_at";

            // 1. Handle Time Period
            $period = $_GET['period'] ?? 'all';
            switch ($period) {
                case 'day':   $filter_query .= " AND DATE($date_column) = CURDATE()"; break;
                case 'week':  $filter_query .= " AND YEARWEEK($date_column, 1) = YEARWEEK(CURDATE(), 1)"; break;
                case 'month': $filter_query .= " AND MONTH($date_column) = MONTH(CURDATE()) AND YEAR($date_column) = YEAR(CURDATE())"; break;
                case 'year':  $filter_query .= " AND YEAR($date_column) = YEAR(CURDATE())"; break;
                case 'custom':
                    $start = $_GET['start_date'] ?? '';
                    $end = $_GET['end_date'] ?? '';
                    if ($start && $end) { $filter_query .= " AND DATE($date_column) BETWEEN '$start' AND '$end'"; }
                    break;
            }

            // 2. Handle Customer Selection
            if (!empty($_GET['customer_id'])) {
                $cust_id = (int)$_GET['customer_id'];
                $filter_query .= " AND t.customer_id = $cust_id";
            }

            // 3. Final Query
            $sql = Querydb("SELECT t.*, c.name, tk.license_plate, 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 $filter_query
                            ORDER BY t.trip_id DESC");
        
            // Initialize variables
            $total_haulage = 0; $total_promo = 0; $total_incentive = 0;
            $pending_haulage = 0; $pending_promo = 0; $pending_incentive = 0;

            // We use the already fetched $sql array to calculate totals
            foreach ($sql as $sum_row) {
                // Add up the amounts
                $total_haulage += $sum_row['haulage_amount'];
                $total_promo += $sum_row['promo_amount'];
                $total_incentive += $sum_row['incentive_amount'];

                // Count how many are zero
                if ($sum_row['haulage_amount'] <= 0) $pending_haulage++;
                if ($sum_row['promo_amount'] <= 0) $pending_promo++;
                if ($sum_row['incentive_amount'] <= 0) $pending_incentive++;
            }

            // Calculate total pending as one (where any of the three are 0)
            $total_pending_all = $pending_haulage + $pending_promo + $pending_incentive;
            ?>
            <div class="row mb-4">
    <div class="col-md-3">
        <div class="card shadow-sm border-0 border-start border-primary border-4">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="text-uppercase mb-1 small fw-bold text-muted">Total Haulage</h6>
                        <h3 class="fw-bold mb-0 text-primary">₦ <?php echo number_format($total_haulage, 2); ?></h3>
                        <small class="text-muted"><?php echo $pending_haulage; ?> unset rates</small>
                    </div>
                    <div class="bg-light-primary p-3 rounded-circle">
                        <i class="fa fa-truck text-primary fs-4"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-md-3">
        <div class="card shadow-sm border-0 border-start border-success border-4">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="text-uppercase mb-1 small fw-bold text-muted">Total Promo</h6>
                        <h3 class="fw-bold mb-0 text-success">₦ <?php echo number_format($total_promo, 2); ?></h3>
                        <small class="text-muted"><?php echo $pending_promo; ?> unset promo</small>
                    </div>
                    <div class="bg-light-success p-3 rounded-circle">
                        <i class="fa fa-gift text-success fs-4"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-md-3">
        <div class="card shadow-sm border-0 border-start border-info border-4">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="text-uppercase mb-1 small fw-bold text-muted">Total Incentive</h6>
                        <h3 class="fw-bold mb-0 text-info">₦ <?php echo number_format($total_incentive, 2); ?></h3>
                        <small class="text-muted"><?php echo $pending_incentive; ?> unset incentive</small>
                    </div>
                    <div class="bg-light-info p-3 rounded-circle">
                        <i class="fa fa-coins text-info fs-4"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-md-3">
        <div class="card shadow-sm border-0 border-start border-warning border-4">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="text-uppercase mb-1 small fw-bold text-muted">Pending Updates</h6>
                        <h3 class="fw-bold mb-0 text-warning"><?php echo ($pending_haulage + $pending_promo + $pending_incentive); ?></h3>
                        <small class="text-muted">Fields requiring rates</small>
                    </div>
                    <div class="bg-light-warning p-3 rounded-circle">
                        <i class="fa fa-exclamation-circle text-warning fs-4"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
            <div class="card shadow rounded-4">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle" id="table1">
                            <thead>
                                <tr>
                                    <th>ATC / Customer</th>
                                    <th>Truck & Driver</th>
                                    <th>Volume (Units)</th>
                                    <th>Haulage</th>
                                    <th>Promo</th>
                                    <th>Incentive</th>
                                    <th class="text-center">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                $count = 0;
                                foreach ($sql as $row) { 
                                    // Logic: If haulage is 0, we need to set the rate
                                    $needs_rates = ($row['haulage_amount'] <= 0);
                                    $count +=1;
                                ?>
                                <tr>
                                    <td>
                                        <span class="fw-bold d-block"><?php echo $row['atc_number'] ? : 'N/A'; ?></span>
                                        <small class="text-muted"><?php echo $row['name']; ?></small>
                                    </td>
                                    <td>
                                        <div class="small"><i class="fa fa-truck me-1"></i> <?php echo $row['license_plate']; ?></div>
                                        <div class="small text-muted"><i class="fa fa-user me-1"></i> <?php echo $row['first_name']; ?></div>
                                    </td>
                                    <td><span class="badge bg-light text-dark border"><?php echo $row['unit']; ?> Units</span></td>
                                    <td>                                  
                                        <div class="small fw-bold">₦ <?php echo number_format($row['haulage_amount'], 2); ?></div>
                                    </td>
                                    <td>                                  
                                        <div class="small fw-bold">₦ <?php echo number_format($row['promo_amount'], 2); ?></div>
                                    </td>
                                    <td>                                  
                                        <div class="small fw-bold">₦ <?php echo number_format($row['incentive_amount'], 2); ?></div>
                                    </td>
                                    <td class="text-center">
                                        
                                            <button type="button" class="btn btn-primary btn-sm px-3 shadow-sm" data-bs-toggle="modal" data-bs-target="#rateModal<?php echo $row['trip_id']; ?>">
                                                <i class="fa fa-calculator me-1"></i> Set Rates
                                            </button>
                                    
                                            <button class="btn btn-outline-secondary btn-sm" data-bs-toggle="modal" data-bs-target="#rateModal<?php echo $row['trip_id']; ?>">
                                                <i class="fa fa-edit"></i> Edit
                                            </button>
                                        
                                    </td>
                                </tr>

                                <div class="modal fade" id="rateModal<?php echo $row['trip_id']; ?>" tabindex="-1" aria-hidden="true">
                                    <div class="modal-dialog modal-dialog-centered">
                                        <div class="modal-content border-0 shadow-lg">
                                            <div class="modal-header bg-dark text-white">
                                                <h5 class="modal-title"><i class="fa fa-coins me-2"></i>Configure Rates</h5>
                                                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                                            </div>
                                            <form class="process_rates_<?php echo $count; ?>" action="" method="POST">
                                                <div class="modal-body p-4">
                                                    <input type="hidden" id="trip_id_<?php echo $count; ?>" value="<?php echo $row['trip_id']; ?>">
                                                    <input type="hidden" name="units" value="<?php echo $row['unit']; ?>">

                                                    <div class="alert alert-secondary border-0 mb-4">
                                                        <div class="row">
                                                            <div class="col-6">
                                                                <small class="text-uppercase fw-bold d-block" style="font-size: 0.7rem;">ATC Number</small>
                                                                <span class="fw-bold text-dark"><?php echo $row['atc_number']; ?></span>
                                                            </div>
                                                            <div class="col-6 text-end">
                                                                <small class="text-uppercase fw-bold d-block" style="font-size: 0.7rem;">Volume</small>
                                                                <span class="fw-bold text-dark"><?php echo $row['unit']; ?> Units</span>
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <div class="mb-3">
                                                        <label class="form-label fw-bold">Haulage Rate (per unit)</label>
                                                        <div class="input-group">
                                                            <span class="input-group-text bg-white">₦</span>
                                                            <input type="number" step="0.01" id="haulage_rate_<?php echo $count; ?>" class="form-control" placeholder="0.00" value="<?php echo $row['haulage_amount']; ?>" required>
                                                        </div>
                                                    </div>

                                                    <div class="row g-3">
                                                        <div class="col-6">
                                                            <label class="form-label fw-bold small">Promo Amount</label>
                                                            <input type="number" step="0.01" id="promo_amount_<?php echo $count; ?>" class="form-control" placeholder="0.00" value="<?php echo $row['promo_amount']; ?>" required>
                                                        </div>
                                                        <div class="col-6">
                                                            <label class="form-label fw-bold small">Incentive</label>
                                                            <input type="number" step="0.01" id="incentive_amount_<?php echo $count; ?>" class="form-control" placeholder="0.00" value="<?php echo $row['incentive_amount']; ?>" required>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="modal-footer bg-light border-0">
                                                    <button type="button" class="btn btn-secondary px-4" data-bs-dismiss="modal">Close</button>
                                                    <button type="submit" name="update_finance" id="update_finance_<?php echo $count; ?>" class="btn btn-dark px-4">Apply & Save</button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>

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