<?php
require_once 'config.php';

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

$fixed_timeline_steps = [
    'Label Created',
    'We Have Your Package',
    'On the Way',
    'Out for Delivery',
    'Delivered'
];

function process_tracking_data($history_raw) {
    global $fixed_timeline_steps;
    $processed_data = [];
    $history_reversed = array_reverse($history_raw);

    foreach ($history_reversed as $event) {
        $status_lower = strtolower($event['status_update']);
        $mapped_steps = [];

        if (strpos($status_lower, 'shipment information received') !== false) {
            $mapped_steps[] = 'Label Created';
            $mapped_steps[] = 'We Have Your Package';
        }

        elseif (strpos($status_lower, 'in transit') !== false || strpos($status_lower, 'on hold') !== false || strpos($status_lower, 'exception') !== false) {
            $mapped_steps[] = 'On the Way';
        }

        elseif (strpos($status_lower, 'pending') !== false || strpos($status_lower, 'out for delivery') !== false) {
            $mapped_steps[] = 'Out for Delivery';
        }

        elseif (strpos($status_lower, 'delivered') !== false) {
            $mapped_steps[] = 'Delivered';
        }

        elseif (strpos($status_lower, 'label created') !== false || strpos($status_lower, 'manifest') !== false) {
             $mapped_steps[] = 'Label Created';
        }
        elseif (strpos($status_lower, 'package received') !== false || strpos($status_lower, 'pickup scan') !== false) {
             $mapped_steps[] = 'We Have Your Package';
        }


        foreach ($mapped_steps as $mapped_step) {
             $processed_data[$mapped_step] = $event;


             if ($mapped_step === 'On the Way' && (strpos($status_lower, 'on hold') !== false || strpos($status_lower, 'exception') !== false)) {
                 $processed_data[$mapped_step]['is_on_hold_flag'] = true;
             }
        }
    }


    $final_timeline = [];
    $is_active_found = false;


    $last_mapped_key = array_key_last($processed_data);

    foreach ($fixed_timeline_steps as $step_title) {
        $event = $processed_data[$step_title] ?? null;
        $is_completed = (bool)$event;
        $is_active = false;
        $is_on_hold = false;


        if ($event && !$is_active_found && $step_title === $last_mapped_key) {
            $is_active = true;
            $is_active_found = true;
            $is_completed = false;


            $is_on_hold = $event['is_on_hold_flag'] ?? false;
        }


        if ($event && !$is_active) {
            $is_completed = true;
        }

        $final_timeline[] = [
            'title' => $step_title,
            'location' => $event['location'] ?? null,

            'updated_at' => ($event['updated_at'] ?? null) ? date('m/d/Y, h:i A', strtotime($event['updated_at'])) : null,
            'status_update' => $event['status_update'] ?? $step_title,
            'is_completed' => $is_completed,
            'is_active' => $is_active,
            'is_on_hold' => $is_on_hold
        ];
    }

    return $final_timeline;
}

if (isset($_GET['tracking_number'])) {
    header('Content-Type: application/json');
    $tracking_number = trim($_GET['tracking_number']);

    $sql_id = "SELECT id, sender_address, receiver_address FROM shipments WHERE tracking_number = :tn";
    $stmt_id = $pdo->prepare($sql_id);
    $stmt_id->execute([':tn' => $tracking_number]);
    $shipment = $stmt_id->fetch(PDO::FETCH_ASSOC);

    if ($shipment) {
        $shipment_id = $shipment['id'];

        if (isset($_GET['fetch_history_map'])) {
            $sql_history_map = "SELECT updated_at, location, status_update
                                FROM tracking_history
                                WHERE shipment_id = :sid
                                AND location IS NOT NULL AND location != ''
                                ORDER BY updated_at ASC";
            $stmt_history_map = $pdo->prepare($sql_history_map);
            $stmt_history_map->execute([':sid' => $shipment_id]);
            $history_data = $stmt_history_map->fetchAll(PDO::FETCH_ASSOC);

            echo json_encode([
                'success' => true,
                'history' => $history_data,
                'origin' => $shipment['sender_address'],
                'destination' => $shipment['receiver_address']
            ]);
        } elseif (isset($_GET['fetch_location'])) {
            $sql = "SELECT location FROM tracking_history WHERE shipment_id = :sid ORDER BY updated_at DESC LIMIT 1";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([':sid' => $shipment_id]);
            $latest_status = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($latest_status && !empty($latest_status['location'])) {
                echo json_encode(['success' => true, 'location' => $latest_status['location']]);
            } else {
                echo json_encode(['success' => false, 'location' => 'No recent location data found.']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Invalid map request.']);
        }

    } else {
        echo json_encode(['success' => false, 'message' => 'Shipment not found.']);
    }
    exit;
}

$shipment_details = null;
$error_message = '';
$tracking_number_input = '';
$fixed_timeline = [];
$latest_location = 'World Map';

$tracking_number = null;

if (isset($_GET['awb'])) {
    $tracking_number = trim($_GET['awb']);
} elseif (isset($_GET['tn'])) {
    $tracking_number = trim($_GET['tn']);
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['tracking_number'])) {
    $tracking_number = trim($_POST['tracking_number']);
}

if ($tracking_number) {
    $tracking_number_input = $tracking_number;

    $sql_shipment = "SELECT * FROM shipments WHERE tracking_number = :tn";
    $stmt_shipment = $pdo->prepare($sql_shipment);
    $stmt_shipment->execute([':tn' => $tracking_number]);
    $shipment_details = $stmt_shipment->fetch(PDO::FETCH_ASSOC);

    if ($shipment_details) {
        $shipment_id = $shipment_details['id'];

        $image_paths = [];
        if (!empty($shipment_details['package_images'])) {
            $image_paths = explode(',', $shipment_details['package_images']);
        } else {
            // Default image if none uploaded
            $image_paths = ['assets/images/package.PNG'];
        }


        $sql_history = "SELECT * FROM tracking_history
                        WHERE shipment_id = :sid
                        ORDER BY updated_at DESC";
        $stmt_history = $pdo->prepare($sql_history);
        $stmt_history->execute([':sid' => $shipment_id]);
        $history_raw = $stmt_history->fetchAll(PDO::FETCH_ASSOC);


        $fixed_timeline = process_tracking_data($history_raw);


        $latest_location = $history_raw[0]['location'] ?? 'World Map';

    } else {
        $error_message = "Tracking number $tracking_number not found. Please verify and try again.";
    }
}


$on_hold_reason_display = 'An email has been sent to you with the necessary steps to facilitate a quick release. Kindly check your inbox and take prompt action to avoid further delays.';
$is_shipment_unpaid = false;

if ($shipment_details) {
    // Check for Unpaid Status
    if (isset($shipment_details['payment_status']) && strtolower($shipment_details['payment_status']) === 'unpaid') {
        $is_shipment_unpaid = true;
    }

    // Check for On Hold Reason
    foreach ($fixed_timeline as $step) {
        if ($step['is_active'] && $step['is_on_hold']) {
            // Find the raw event that caused this step to be active and on hold
            // This requires the original tracking_history entry.
            // Assuming the raw history data is available and the 'On the Way' step
            // has the required 'on_hold_reason' key set in process_tracking_data.

            // Since we don't have the logic for how on_hold_reason is pulled,
            // we will find the latest 'on hold' or 'exception' event from $history_raw
            // and use its 'on_hold_reason' column if it exists.

            if (!empty($history_raw)) {
                $latest_on_hold_event = null;
                foreach ($history_raw as $raw_event) {
                    $status_lower = strtolower($raw_event['status_update']);
                    if (strpos($status_lower, 'on hold') !== false || strpos($status_lower, 'exception') !== false) {
                        $latest_on_hold_event = $raw_event;
                        break; // Get the latest one (since $history_raw is ordered DESC)
                    }
                }
                if ($latest_on_hold_event && !empty($latest_on_hold_event['on_hold_reason'])) {
                    $on_hold_reason_display = htmlspecialchars($latest_on_hold_event['on_hold_reason']);
                }
            }

            break;
        }
    }
}

$service_type_map = [
    'Standard' => 'Standard Logistics',
    'Express' => 'Express Air Cargo',
    'International' => 'Global International',
    'Freight' => 'Heavy Freight Shipping',
    'Door-to-Door' => 'Door-to-Door Quick Delivery',
    'Specialized' => 'Specialized Handling (Fragile/Secure)',
    'Eco' => 'Eco-Friendly Shipping'
];

$currency_symbols = [
    'USD'=>'$','EUR'=>'€','GBP'=>'£','NGN'=>'₦','CAD'=>'C$','AUD'=>'A$','NZD'=>'NZ$','JPY'=>'¥','CNY'=>'¥','INR'=>'₹','ZAR'=>'R',
    'CHF'=>'CHF','SEK'=>'kr','NOK'=>'kr','DKK'=>'kr','RUB'=>'₽','BRL'=>'R$','MXN'=>'MX$','SAR'=>'﷼','AED'=>'د.إ','EGP'=>'E£',
    'KES'=>'KSh','GHS'=>'₵','UGX'=>'USh','TZS'=>'TSh','PKR'=>'₨','BDT'=>'৳','LKR'=>'Rs','THB'=>'฿','MYR'=>'RM','IDR'=>'Rp',
    'KRW'=>'₩','HKD'=>'HK$','SGD'=>'S$','TRY'=>'₺','PLN'=>'zł','CZK'=>'Kč','HUF'=>'Ft','RON'=>'lei','ILS'=>'₪','KWD'=>'KD',
    'QAR'=>'﷼','OMR'=>'﷼','BHD'=>'BD','JOD'=>'JD','MAD'=>'DH','DZD'=>'DA','TND'=>'DT','ETB'=>'Br','AOA'=>'Kz','MWK'=>'MK',
    'M Mozambique'=>'MT','Zambia'=>'ZK','Botswana'=>'P','Namibia'=>'N$','XOF'=>'CFA','XAF'=>'FCFA','LRD'=>'L$','SLL'=>'Le'
];
$currency_symbol = $currency_symbols[$shipment_details['currency'] ?? 'USD'] ?? '$';

require_once 'get_setting.php';
?>
<!DOCTYPE html>
<html lang="en">
   <head>
        
      <meta charset="UTF-8" />
        
      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        
      <title><?php echo htmlspecialchars($site_settings['site_title'] ?? 'ReliParcel Express'); ?> | Track Your Parcel</title>
	  <!-- Favicon -->
      <?php if ($use_favicon): ?>
      <link rel="icon" type="<?php echo $favicon_mime; ?>" href="<?php echo $favicon_path; ?>">
      <?php else: ?>
      <link rel="icon" type="image/x-icon" href="assets/images/favicon.ico">
      <?php endif; ?>
      <link rel="stylesheet" href="assets/css/gtranslate.css">
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
        
      <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
       <link rel="stylesheet" href="assets/css/font-awesome-pro.css">
	    <link rel="stylesheet" href="assets/css/track.css">
      <link rel="preconnect" href="https://fonts.googleapis.com">
      <link href="assets/css/style.css" rel="stylesheet">
      <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
      
      <link href="https://fonts.googleapis.com/css2?family=Dawning+of+a+New+Day&family=Epilogue:ital,wght@0,100..900;1,100..900&family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=JetBrains+Mono:ital,wght@0,100..800;1,100..800&family=Mulish:ital,wght@0,200..1000;1,200..1000&family=Open+Sans:ital,wght@0,300..800;1,300..800&family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&family=Raleway:ital,wght@0,100..900;1,100..900&family=Red+Hat+Text:ital,wght@0,300..700;1,300..700&family=Roboto:ital,wght@0,100..900;1,100..900&family=Space+Mono:ital,wght@0,400;0,700;1,400;1,700&family=Work+Sans:ital,wght@0,100..900;1,100..900&display=swap" rel="stylesheet">
      
      <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
      <style>
         /* Styling for the Full Scan History Log */
.timeline-detail-log .list-group-item {
    padding-left: 0.5rem;
    padding-right: 0.5rem;
    border-left: 3px solid transparent;
    transition: all 0.2s ease-in-out;
    border-color: #eee; /* Light border separating scans */
}

.timeline-detail-log .list-group-item:hover {
    background-color: #f8f9fa;
}

/* Highlight for critical items */
.timeline-detail-log .list-group-item-danger {
    border-left-color: #dc3545; /* Red border for exceptions/on hold */
    background-color: #fff3f3;
}

/* Styling to change the color of the final destination marker to green */
.destination-marker {
    /* Filters are used to change the color of the blue pin PNG to green */
    filter: hue-rotate(100deg) brightness(1.2); 
}
@media (max-width: 768px) {
    .btn-primary.btn-lg {
        font-size: 0.7rem !important;
    }
        .btn + .btn {
        margin-left: 0rem;
        font-size: 0.7rem !important;
    }
}
      </style>
   </head>
   <body>
      <?php include "nav.php" ?>
      <header class="hero-gradient-bg text-white text-center pt-5 pb-5 shadow-lg">
         <div class="container mt-5 pt-5">
		 <div class="mx-auto text-center" style="max-width: 800px;">
            <h2 class="fw-bolder mb-3">TRACK YOUR ITEM</h2>
            
               <p class="lead mb-0 fs-5 mb-4">
                  Enter your tracking number below to see your item’s current status and delivery progress.
               </p>
           </div>
            <form method="POST" action="track.php" class="row g-3 needs-validation" novalidate>
               <div class="col-md-7 mx-auto">
                  <label for="trackingNumber" class="form-label fw-bold visually-hidden">Enter Tracking Number</label>
                  <div class="input-group input-group-lg tracking-search-bar-modern shadow-sm">
                     <input 
                        type="text"
                        class="form-control border-end-0"
                        id="trackingNumber"
                        name="tracking_number"
                        placeholder="Enter Tracking Number.."
                        required
                        value="<?= htmlspecialchars($tracking_number_input ?? '') ?>">
                     <button type="submit" class="btn btn-green-search tracking-btn fw-bold">
                     <i class="fas fa-magnifying-glass fa-lg"></i>
                     </button>
                     <div class="invalid-feedback">
                        Please enter a valid tracking number.
                     </div>
                  </div>
               </div>
            </form>
         </div>
      </header>
      <section id="giveaways" class="py-5">
    <div class="container">
        <?php if (!empty($error_message)): ?>
        <div class="card p-5 mt-5 text-center error-page-card">
            <h4 class="fw-bold mb-4">Parcel tracking page.</h4>
            <div class="text-center mb-4">
                <i class="fas fa-question-circle error-icon mb-4"></i>
            </div>
            <h5 class="fw-bold mb-3">Tracking number not found.</h5>
            <p class="mb-5 text-muted">
                <strong class="text-dark"><?= htmlspecialchars($tracking_number_input ?? '') ?></strong> check the number or Track again.
            </p>
            <a href="index.php" class="btn btn-gradient btn-lg px-5 fw-bold mx-auto text-white">
            BACK TO HOME
            </a>
        </div>
        <?php endif; ?>
        <?php if (!empty($shipment_details)): ?>
        <div class="card p-4 pb-5">
            <p style="margin-bottom: 0.3rem;">Your Shipment</p>
            <div class="d-flex align-items-center mb-1">
                <h6 class="fw-bold mb-0 me-2"><?= htmlspecialchars($shipment_details['tracking_number'] ?? '') ?></h6>
                <?php 
                $payment_status = $shipment_details['payment_status'] ?? 'Unpaid';
                $badge_class = 'bg-secondary';
                $icon = 'bi-info-circle';
                
                if (strtolower($payment_status) === 'paid') {
                    $badge_class = 'bg-success';
                    $icon = 'bi-check-circle';
                } elseif (strtolower($payment_status) === 'unpaid') {
                    $badge_class = 'bg-danger';
                    $icon = 'bi-x-circle';
                } elseif (strtolower($payment_status) === 'payment on delivery') {
                    $badge_class = 'bg-primary';
                    $icon = 'bi-truck';
                }
                ?>
                <span class="badge <?php echo $badge_class; ?> text-white fw-bold py-2 px-3 shadow-sm border-0" style="letter-spacing: 0.5px; border-radius: 50px;">
                    <i class="bi <?php echo $icon; ?> me-1"></i> 
                    <span class="d-none d-md-inline"><?php echo strtoupper($payment_status); ?></span>
                    <span class="d-inline d-md-none"><?php echo (strtolower($payment_status) === 'payment on delivery') ? 'PAY ON DELIVERY' : strtoupper($payment_status); ?></span>
                </span>
            </div>
            <p class="mb-1 mt-2 text-muted">Estimated delivery</p>
            <h4 class="fw-bold mm" style="font-family: 'Montserrat' !important;">
                <?php
                if ($is_shipment_unpaid) {
                    // Change estimated delivery entirely if unpaid
                    echo '<span class="mm">Delivery Pending Payment</span>';
                } elseif (isset($shipment_details['estimated_delivery']) && !empty($shipment_details['estimated_delivery'])) {
                    echo date('l, M d Y', strtotime($shipment_details['estimated_delivery']));
                } else {
                    echo 'Date Not Available';
                }
                ?>
            </h4>
            <hr>
            <div class="mt-4">
                <p class="mb-0 fw-bold">Ship To</p>
                <p class="mb-3" style="color: #000;">
                    <?= htmlspecialchars($shipment_details['receiver_address'] ?? 'N/A') ?>
                </p>
            </div>
            <div class="mt-4">
                <?php foreach ($fixed_timeline as $step):
                    $step_class = 'not-pending';
                    $dot_icon = 'fa-long-arrow-right';
                    $title_class = 'unbold text-muted';

                    if (!empty($step['is_completed'])) {
                        $step_class = 'completed';
                        $dot_icon = 'fa-check';
                        $title_class = 'text-muted';
                    } elseif (!empty($step['is_active'])) {
                        $step_class = 'pending';
                        $dot_icon = 'fa-long-arrow-right';
                        $title_class = '';
                    }

                    $location_detail = $step['location'] ? htmlspecialchars($step['location']) : '';
                    $date_detail = $step['updated_at'] ?? '';
                    ?>
                <div class="tracking-step <?= $step_class ?>">
                    <div class="tracking-dot">
                        <i class="fas <?= $dot_icon ?>"></i>
                    </div>
                    <div>
                        <div class="d-flex align-items-center">
                            <p class="step-title <?= $title_class ?>"><?= htmlspecialchars($step['title']) ?></p>
                            <?php if (!empty($step['is_on_hold'])): ?>
                            <span data-bs-toggle="modal" data-bs-target="#onHoldModal" style="cursor: context-menu;">
                            <i class="fas fa-triangle-exclamation on-hold-icon"></i>
                            <span class="on-hold-text">On Hold</span>
                            </span>
                            <?php endif; ?>
                        </div>
                        <?php if (!empty($location_detail) || !empty($date_detail)): ?>
                        <p class="step-details text-muted">
                            <?= $location_detail ?><br><?= $date_detail ?>
                        </p>
                        <?php endif; ?>
                    </div>
                 </div>
                 <?php endforeach; ?>
            </div>
            <div class="d-flex flex-column gap-3 col-11 col-md-8 col-lg-6 mx-auto mt-5">
                <button class="btn btn-primary btn-lg w-100 shadow-sm" onclick="window.location.href='index.php';">BACK TO HOME</button>
                <div class="d-flex flex-column flex-md-row gap-3">
                    <button
                        type="button"
                        class="btn btn-outline-primary btn-lg w-100"
                        data-bs-toggle="modal"
                        data-bs-target="#mapModal"
                        data-tracking-number="<?= htmlspecialchars($shipment_details['tracking_number'] ?? '') ?>"
                        data-latest-location="<?= htmlspecialchars($latest_location ?? 'World Map') ?>">
                    LIVE MAP
                    </button>
                    <button
                        type="button"
                        class="btn btn-outline-primary btn-lg w-100"
                        onclick="window.open('view_invoice.php?awb=<?= urlencode($shipment_details['tracking_number'] ?? '') ?>', '_blank');">
                         INVOICE
                    </button>
                </div>
            </div>
        </div>

        <?php 
        $is_currently_on_hold = false;
        foreach ($fixed_timeline as $step) {
            if ($step['is_active'] && $step['is_on_hold']) {
                $is_currently_on_hold = true;
                break;
            }
        }
        ?>

        <?php if ($is_currently_on_hold): ?>
        <div class="card mt-4 p-4 shadow-sm" style="border-left: 5px solid #ffc107; background: #fffdf6; border-radius: 12px;">
            <div class="row align-items-center">
                <div class="col-md-1 d-none d-md-block text-center">
                    <i class="fas fa-circle-pause text-warning fs-1"></i>
                </div>
                <div class="col-md-11">
                    <h5 class="fw-bold text-dark mb-1" style="color: #856404 !important;">Shipment Temporarily Held</h5>
                    <p class="mb-0 text-muted" style="font-size: 0.95rem;">
                        <strong>Current Status:</strong> Your shipment is currently awaiting further action. 
                        <?php if (!empty($on_hold_reason_display)): ?>
                            <br><span class="text-danger fw-bold">Reason:</span> <?= $on_hold_reason_display ?>
                        <?php endif; ?>
                    </p>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <?php if (strtolower($shipment_details['payment_status'] ?? '') !== 'paid' && !empty($shipment_details['amount'])): ?>
        <div class="card mt-4 p-4 border-danger shadow-sm" style="border-left: 5px solid #dc3545; background: #fffdfd;">
            <div class="row align-items-center">
                <div class="col-md-1 d-none d-md-block text-center">
                    <i class="bi bi-exclamation-octagon-fill text-danger fs-1"></i>
                </div>
                <div class="col-md-7">
                    <h5 class="fw-bold text-danger mb-1">Payment Required</h5>
                    <p class="mb-0 text-muted">Kindly settle the outstanding balance of <strong><?= htmlspecialchars(($currency_symbol ?? '$') . number_format($shipment_details['amount'], 2)) ?></strong> to facilitate the next stage of your shipment's journey.</p>
                </div>
                <div class="col-md-4 text-md-end mt-3 mt-md-0">
                    <a href="payment.php?invoice=<?= urlencode($shipment_details['tracking_number']) ?>" class="btn btn-danger fw-bold px-4 py-2 rounded-pill">
                        <i class="bi bi-credit-card-fill me-2"></i> PAY SECURELY NOW
                    </a>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <div class="row">
        <div class="col-md-7">
        <div class="card p-4 mt-4">
            <h5 class="mb-3">Package Contents & Details</h5>
            <div class="row g-3">
                <div class="col-md-12">
                    <ul class="list-group list-group-flush">
                        <li class="list-group-item d-flex flex-column flex-md-row justify-content-md-between align-items-start align-items-md-center g-2 g-md-0">
                            <strong class="text-nowrap me-md-3">Description:</strong>
                            <span class="text-md-end text-break"><?= htmlspecialchars($shipment_details['package_description'] ?? 'N/A') ?></span>
                        </li>
                        <li class="list-group-item d-flex flex-column flex-md-row justify-content-md-between align-items-start align-items-md-center g-2 g-md-0">
                            <strong class="text-nowrap me-md-3">Total Weight:</strong>
                            <span class="text-md-end text-break"><?= htmlspecialchars(($shipment_details['weight'] ?? 'N/A') . ' kg') ?></span>
                        </li>
                        <li class="list-group-item d-flex flex-column flex-md-row justify-content-md-between align-items-start align-items-md-center g-2 g-md-0">
                            <strong class="text-nowrap me-md-3">Dimensions:</strong>
                            <span class="text-md-end text-break"><?= htmlspecialchars($shipment_details['dimensions'] ?? 'N/A') ?></span>
                        </li>
                        <li class="list-group-item d-flex flex-column flex-md-row justify-content-md-between align-items-start align-items-md-center g-2 g-md-0">
                            <strong class="text-nowrap me-md-3">Service:</strong>
                            <span class="text-md-end text-break"><?= htmlspecialchars($service_type_map[$shipment_details['service_type']] ?? $shipment_details['service_type'] ?? 'Standard Logistics') ?></span>
                        </li>
                        <?php if (strtolower($shipment_details['payment_status'] ?? '') !== 'paid' && !empty($shipment_details['amount'])): ?>
                        <li class="list-group-item d-flex flex-column flex-md-row justify-content-md-between align-items-start align-items-md-center g-2 g-md-0">
                            <strong class="text-nowrap me-md-3">Total Amount Due:</strong>
                            <div class="text-md-end">
                                <span class="text-danger fw-bold d-block"><?= htmlspecialchars(($currency_symbol ?? '$') . number_format($shipment_details['amount'], 2)) ?></span>
                                <a href="payment.php?invoice=<?= urlencode($shipment_details['tracking_number']) ?>" class="small fw-bold text-decoration-none"><i class="bi bi-arrow-right-circle me-1"></i> Pay Online</a>
                            </div>
                        </li>
                        <?php endif; ?>
                    </ul>
                </div>
                <div class="col-md-12">
                    <ul class="list-group list-group-flush">
                        <li class="list-group-item d-flex flex-column flex-md-row justify-content-md-between align-items-start align-items-md-center g-2 g-md-0">
                            <strong class="text-nowrap me-md-3">Sender:</strong>
                            <span class="text-md-end text-break"><?= htmlspecialchars($shipment_details['sender_name'] ?? 'N/A') ?></span>
                        </li>
                        <li class="list-group-item d-flex flex-column flex-md-row justify-content-md-between align-items-start align-items-md-center g-2 g-md-0">
                            <strong class="text-nowrap me-md-3">Receiver:</strong>
                            <span class="text-md-end text-break"><?= htmlspecialchars($shipment_details['receiver_name'] ?? 'N/A') ?></span>
                        </li>
                        <li class="list-group-item d-flex flex-column flex-md-row justify-content-md-between align-items-start align-items-md-center g-2 g-md-0">
                            <strong class="text-nowrap me-md-3">Origin:</strong>
                            <span class="text-md-end text-break"><?= htmlspecialchars($shipment_details['sender_address'] ?? 'N/A') ?></span>
                        </li>
                        <li class="list-group-item d-flex flex-column flex-md-row justify-content-md-between align-items-start align-items-md-center g-2 g-md-0">
                            <strong class="text-nowrap me-md-3">Destination:</strong>
                            <span class="text-md-end text-break"><?= htmlspecialchars($shipment_details['receiver_address'] ?? 'N/A') ?></span>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
        </div>
        <?php if (!empty($image_paths)): ?>

        <div class="col-md-5">
          <div class="card p-4 mt-4">
            <h5 class="mb-3">Package Photos</h5>
            <div id="packageImagesCarousel" class="carousel slide" data-bs-ride="carousel">
                <div class="carousel-indicators">
                    <?php foreach ($image_paths as $index => $path): ?>
                    <button type="button" data-bs-target="#packageImagesCarousel" data-bs-slide-to="<?= $index ?>"
                            class="<?= $index === 0 ? 'active' : '' ?>" aria-current="<?= $index === 0 ? 'true' : 'false' ?>"
                            aria-label="Slide <?= $index + 1 ?>"></button>
                    <?php endforeach; ?>
                </div>
                <div class="carousel-inner">
                    <?php foreach ($image_paths as $index => $path):
                        $full_path = htmlspecialchars($path);
                    ?>
                    <div class="carousel-item <?= $index === 0 ? 'active' : '' ?>">
                        <img src="<?= $full_path ?>" class="d-block w-100 package-image-carousel" alt="Package Image <?= $index + 1 ?>">
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php if (count($image_paths) > 1): ?>
                <button class="carousel-control-prev" type="button" data-bs-target="#packageImagesCarousel" data-bs-slide="prev">
                    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                    <span class="visually-hidden">Previous</span>
                </button>
                <button class="carousel-control-next" type="button" data-bs-target="#packageImagesCarousel" data-bs-slide="next">
                    <span class="carousel-control-next-icon" aria-hidden="true"></span>
                    <span class="visually-hidden">Next</span>
                </button>
                <?php endif; ?>
            </div> 
          </div> 
        </div> 
        <?php endif; ?>


        <div class="col-md-12">

        <div class="card mt-4 p-4">
    <h5 class="mb-3">
        <button class="btn btn-link p-0 fw-bold text-decoration-none" type="button" data-bs-toggle="collapse" data-bs-target="#fullHistoryCollapse" aria-expanded="false" aria-controls="fullHistoryCollapse" style="color: #9b0000;">
            <i class="fas fa-list-ul me-2"></i> Full Scan History Log (<?= count($history_raw); ?> Events)
        </button>
    </h5>

    <div class="collapse show" id="fullHistoryCollapse">
        <ul class="list-group list-group-flush timeline-detail-log">
            <?php if (!empty($history_raw)): ?>
                <?php
                // Display the history in reverse chronological order (newest first)
                $history_chronological = array_reverse($history_raw);
                foreach ($history_chronological as $event):
                    $timestamp = date('m/d/Y, h:i A', strtotime($event['updated_at']));
                    $is_critical = strpos(strtolower($event['status_update']), 'on hold') !== false || strpos(strtolower($event['status_update']), 'exception') !== false;
                    $list_class = $is_critical ? 'list-group-item-danger' : '';
                ?>
                <li class="list-group-item <?= $list_class ?>">
                    <div class="d-flex w-100 justify-content-between">
                        <small class="text-muted"><?= htmlspecialchars($timestamp) ?></small>
                        <?php if ($is_critical): ?>
                            <span class="badge bg-danger text-white" style="letter-spacing: 0px;"><i class="fas fa-exclamation-triangle me-1"></i> ATTENTION</span>
                        <?php endif; ?>
                    </div>
                    <p class="mb-1 fw-bold"><?= htmlspecialchars($event['status_update']) ?></p>
                    <?php if (!empty($event['on_hold_reason'])): ?>
                        <div class="alert alert-warning py-2 px-3 mt-2 mb-1" style="font-size: 0.85rem; border-left: 4px solid #ffc107;">
                            <i class="fas fa-circle-info me-1"></i> <strong>Reason:</strong> <?= htmlspecialchars($event['on_hold_reason']) ?>
                        </div>
                    <?php endif; ?>
                    <small class="text-secondary">
                        <i class="far fa-location-dot me-1"></i> <?= htmlspecialchars($event['location'] ?? 'N/A') ?>
                    </small>
                </li>
                <?php endforeach; ?>
            <?php else: ?>
                <li class="list-group-item text-muted">No detailed scan history available yet.</li>
            <?php endif; ?>
        </ul>
    </div>
</div>

</div>


        <div class="col-md-12">

            <div class="card mt-4 p-4">
                <p class="fw-bold">Get updates for your package</p>
                <p class="mb-0">
                    Never miss a delivery again or worry about packages being left unattended at your doorstep.
                    With <?php echo htmlspecialchars($site_settings['site_title']) ?> My Choice®, you'll receive real-time alerts, estimated delivery windows, and
                    the ability to reschedule or reroute shipments to a secure location — all from your phone or computer.
                </p>
            </div>
        </div>
        <?php endif; ?>
        <?php if (empty($error_message) && empty($shipment_details)): ?>
        <div class="card p-5 text-center mt-5" style="max-width: 600px; margin: 0 auto; box-shadow: none !important;">
            <h4 class="fw-bold mb-3" style="">WELCOME TO PARCEL TRACKING</h4>
            <div class="text-center mb-4">
                <i class="fas fa-route" style="font-size: 3rem; color: #9a0000;"></i>
            </div>
            <p class="lead mb-4 text-muted">
                Your package's journey is just a search away. Please enter your tracking number above to instantly view the latest status and detailed timeline.
            </p>
            <p class="mb-0 text-dark">
                Need a tracking number? Check your confirmation email.
            </p>
        </div>
        <?php endif; ?>
        <a href="index.php"
            class="btn btn-primary position-fixed bottom-0 end-0 m-4 rounded-circle shadow"
            style="width: 50px; height: 50px; display: flex; align-items: center; justify-content: center; z-index: 999;">
        <i class="fas fa-home"></i>
        </a>
        <div class="modal fade" id="mapModal" tabindex="-1" aria-labelledby="mapModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-xl modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header" style="background-color: #8b0000 !important;">
                        <h5 class="modal-title fw-bold" id="mapModalLabel">
                            Current Location of Parcel: <span id="map_tracking_number_display"></span>
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body p-4">
                        <p class="lead mb-3 text-dark">
                            <i class="fas fa-map-marker-alt mm me-2"></i> Latest Address:
                            <span id="map_location_display" class="fw-bold">...</span>
                        </p>
                        <div id="mapid"></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="modal fade" id="onHoldModal" tabindex="-1" aria-labelledby="onHoldModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header bg-danger">
                        <h5 class="modal-title" id="onHoldModalLabel">
                            <i class="fas fa-triangle-exclamation me-2"></i>Your Shipment is Temporarily Held
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <p class="mb-0 fw-bold">Reason for Hold:</p>
                        <p class="mb-3">
                            <?= $on_hold_reason_display ?>
                        </p>
                        <p class="mb-0 text-muted small">
                            Please contact customer support immediately.
                        </p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" style="font-size: 13px;">Close</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
      <?php include "footer.php" ?>
      <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
      <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
    var shipmentMap = null;

    // --- 1. Geocoding Function (Used for Origin/Destination or History Fallback) ---
    async function geocodeAddress(address) {
        if (!address) return null;
        const nominatimUrl = `https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(address)}&limit=1`;
        try {
            const response = await fetch(nominatimUrl, { headers: { 'Accept-Language': 'en' } });
            const data = await response.json();
            if (data && data.length > 0) {
                return { lat: parseFloat(data[0].lat), lon: parseFloat(data[0].lon), address: data[0].display_name };
            }
        } catch (error) {
            console.error('Nominatim Geocoding error for:', address, error);
        }
        return null;
    }

    // --- 2. Main Plotting Function (Coordinate Priority Logic) ---
    async function plotShipmentRoute(locations, originAddress, destinationAddress, mapContainerId, mapLocationDisplay) {
        $(mapLocationDisplay).text('Plotting detailed route...');

        // Initialize Map
        if (shipmentMap === null) {
            shipmentMap = L.map(mapContainerId).setView([0, 0], 2);
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                maxZoom: 19,
                attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
            }).addTo(shipmentMap);
        } else {
            // Clear previous layers
            shipmentMap.eachLayer(layer => {
                if (layer instanceof L.Marker || layer instanceof L.Polyline || layer instanceof L.Circle) {
                    shipmentMap.removeLayer(layer);
                }
            });
        }
        
        let allCoords = [];
        let bounds = new L.LatLngBounds();

        // A. Process All Tracking History Points
        for (const event of locations) {
            let latlng = null;
            let locationName = event.location;
            
            // 1. **PRIORITIZE DB COORDINATES** (lat/lon)
            if (event.lat && event.lon && event.lat != 0 && event.lon != 0) {
                // Use coordinates directly
                latlng = [parseFloat(event.lat), parseFloat(event.lon)];
            } else {
                // 2. Fallback to Nominatim Geocoding
                const result = await geocodeAddress(event.location);
                if (result) {
                    latlng = [result.lat, result.lon];
                    locationName = result.address;
                }
            }
            
            // Plot the point if we have coordinates
            if (latlng) {
                allCoords.push(latlng);
                bounds.extend(latlng);

                // Add marker for each stop (Uses default blue icon)
                L.marker(latlng).addTo(shipmentMap)
                    .bindPopup(`<strong>${event.status_update}</strong><br>${locationName}<br>@ ${new Date(event.updated_at).toLocaleString()}`);
            }
        }

        // B. Plot the Route Line
        if (allCoords.length > 1) {
            const polyline = L.polyline(allCoords, { color: '#dc3545', weight: 4, opacity: 0.7 }).addTo(shipmentMap);
            bounds.extend(polyline.getBounds());
        }

        // C. Geocode and Plot Destination
        const destination = await geocodeAddress(destinationAddress);
        if (destination) {
            const destLatlng = [destination.lat, destination.lon];
            bounds.extend(destLatlng);
            
            // Use default icon but add a CSS class for coloring
            const marker = L.marker(destLatlng).addTo(shipmentMap)
                .bindPopup(`<strong>Final Destination</strong><br>${destination.address}`).openPopup();
            
            // Apply the custom class to the marker's HTML element
            if (marker.getElement()) {
                marker.getElement().classList.add('destination-marker'); 
            }

            // Draw a Geofence Circle (5km radius)
            L.circle(destLatlng, {
                color: '#1d8348',
                fillColor: '#2ecc71',
                fillOpacity: 0.1,
                radius: 5000 
            }).addTo(shipmentMap);
        }

        // D. Fit map to show all relevant points
        if (bounds.isValid()) {
            shipmentMap.fitBounds(bounds, { padding: [50, 50] });
        } else {
            // Fallback view
            shipmentMap.setView([0, 0], 2);
        }
        
        // Update latest location display
        const latestLocation = locations.length > 0 ? locations[locations.length - 1].location : 'N/A';
        $(mapLocationDisplay).text(latestLocation);
    }

    // --- 3. Document Ready (Modal Handlers) ---
    $(document).ready(function() {
        $('#mapModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget);
            var trackingNumber = button.data('tracking-number');
            var modal = $(this);
            modal.find('#map_tracking_number_display').text(trackingNumber);

            // AJAX CALL to fetch ALL history for mapping (from track.php)
            $.ajax({
                url: 'track.php',
                type: 'GET',
                dataType: 'json',
                data: { fetch_history_map: 1, tracking_number: trackingNumber },
                success: function(response) {
                    if (response.success && response.history && response.history.length > 0) {
                        plotShipmentRoute(
                            response.history, 
                            response.origin, 
                            response.destination, 
                            'mapid', 
                            '#map_location_display'
                        );
                    } else {
                        let msg = response.message || "No map data available. Showing world map.";
                        modal.find('#map_location_display').text(msg);
                        if (shipmentMap === null) {
                            shipmentMap = L.map('mapid').setView([0, 0], 2);
                            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                                attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
                            }).addTo(shipmentMap);
                        } else {
                            shipmentMap.setView([0, 0], 2);
                        }
                    }
                }
            });
        });

        $('#mapModal').on('shown.bs.modal', function() {
            // Fixes rendering issues that occur when a map is initialized in a hidden element
            if (shipmentMap !== null) {
                shipmentMap.invalidateSize();
            }
        });
    });
</script>
	  
	  <?php include "custom_script.php" ?>
   </body>
</html>