<?php
// track_shipment.php
session_start();

// --- 1. Dependencies and Setup ---
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

require_once '../config.php';
require_once '../get_setting.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

require_once 'vendor/PHPMailer/src/Exception.php';
require_once 'vendor/PHPMailer/src/PHPMailer.php';
require_once 'vendor/PHPMailer/src/SMTP.php';

if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    header("location: admin_login.php");
    exit;
}

$shipments = [];
$message = null;
$message_type = 'info';

if (isset($_SESSION['message'])) {
    $message = $_SESSION['message'];
    $message_type = $_SESSION['message_type'];
    unset($_SESSION['message']);
    unset($_SESSION['message_type']);
}

// Global variable for site settings (assuming get_setting.php populates $site_settings)
$site_settings = get_site_settings($pdo);





// --- 2. Email Template Function for Updates (Updated to handle new reason field) ---

/**
 * Generates the HTML for the tracking update email.
 */
function get_tracking_update_email_body($shipment_data, $settings) {
    $logo_url = !empty($settings['site_logo']) ? $settings['site_url'] . '/assets/images/' . $settings['site_logo'] : 'https://via.placeholder.com/150x50?text=Logo';
    $update_time = date('F j, Y, g:i a');

    // Determine the message to display: reason if on hold, otherwise status update message
    $display_message = !empty($shipment_data['on_hold_reason']) 
                       ? "Reason: " . $shipment_data['on_hold_reason'] 
                       : $shipment_data['status_update'];
    
    // Add a label that reflects the displayed content
    $status_detail_label = !empty($shipment_data['on_hold_reason']) 
                            ? 'On Hold Reason:' 
                            : 'Status Details:';

    $html_body = "
    <div style='font-family:Tahoma, Verdana, sans-serif; background-color: #f4f4f4; padding: 20px;'>
        <div style='max-width: 600px; margin: 0 auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.1);'>
            <div style='background-color: #B00000; padding: 20px; text-align: center;'>
                <img src='{$logo_url}' alt='{$settings['site_title']} Logo' style='max-height: 40px; width: auto; display: block; margin: 0 auto; border-radius: 4px; filter: brightness(2);'>
                <h1 style='color: white; font-size: 24px; margin-top: 15px; margin-bottom: 0;'>Shipment Status Updated!</h1>
            </div>
            
            <div style='padding: 30px; border-bottom: 1px solid #eeeeee;'>
                <p style='color: #555555; font-size: 16px; margin-bottom: 20px;'>
                    Dear {$shipment_data['receiver_name']},<br>
                    Your shipment with Tracking Number **{$shipment_data['tracking_number']}** has been updated.
                </p>

                <div style='background-color: #f8f8f8; padding: 15px; border-radius: 6px; border: 1px solid #e0e0e0;'>
                    <h3 style='font-size: 18px; color: #B00000; margin-top: 0; margin-bottom: 10px;'>New Tracking Information</h3>
                    <table width='100%' cellpadding='5' cellspacing='0' border='0' style='font-size: 14px;'>
                        <tr>
                            <td style='color: #777777; width: 40%;'>Current Status:</td>
                            <td style='font-weight: bold; color: #28a745;'>{$shipment_data['current_shipment_status']}</td>
                        </tr>
                        <tr>
                            <td style='color: #777777;'>Latest Location:</td>
                            <td style='font-weight: bold; color: #333333;'>{$shipment_data['location']}</td>
                        </tr>
                        <tr>
                            <td style='color: #777777;'>{$status_detail_label}</td>
                            <td style='color: #333333;'>{$display_message}</td>
                        </tr>
                        <tr>
                            <td style='color: #777777;'>Time of Update:</td>
                            <td style='color: #333333;'>{$update_time}</td>
                        </tr>
                    </table>
                </div>
            </div>

            <div style='padding: 30px; text-align: center;'>
                <a href='{$settings['site_url']}/track.php?awb={$shipment_data['tracking_number']}' style='display: inline-block; padding: 10px 25px; background-color: #ffc107; color: #333333; text-decoration: none; border-radius: 5px; font-weight: bold; font-size: 16px;'>
                    View Full Tracking History
                </a>
            </div>

            <div style='background-color: #f4f4f4; padding: 20px; text-align: center; color: #777777; font-size: 12px; border-top: 1px solid #e0e0e0;'>
                <p>&copy; " . date('Y') . " {$settings['site_title']}. All rights reserved.</p>
                <p style='margin: 0;'>This is an automated notification, please do not reply.</p>
            </div>
        </div>
    </div>
    ";
    return $html_body;
}

// --- 3. Email Sending Function ---

/**
 * Sends an email notification using PHPMailer with fallback to PHP mail() function.
 */
function send_email_notification($settings, $recipient_email, $subject, $html_body, &$smtp_config_missing) {
    $smtp_config_missing = false;
    $mail = new PHPMailer(true);

    $from_email = !empty($settings['smtp_from_email']) ? $settings['smtp_from_email'] : 'no-reply@' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
    $from_name = !empty($settings['smtp_from_name']) ? $settings['smtp_from_name'] : ($settings['site_title'] ?? 'Shipping System');

    try {
        if (!empty($settings['use_smtp']) && $settings['use_smtp'] === '1' && !empty($settings['smtp_host'])) {
            $mail->isSMTP();
            $mail->Host       = $settings['smtp_host'];
            $mail->SMTPAuth   = true;
            $mail->Username   = $settings['smtp_username'];
            $mail->Password   = $settings['smtp_password'];
            
            $encryption = strtolower($settings['smtp_encryption'] ?? '');
            if ($encryption === 'ssl') {
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            } elseif ($encryption === 'tls') {
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            } else {
                $mail->SMTPAutoTLS = false;
                $mail->SMTPSecure = '';
            }
            $mail->Port       = !empty($settings['smtp_port']) ? (int)$settings['smtp_port'] : 465;
            $from_email = !empty($settings['smtp_from_email']) ? $settings['smtp_from_email'] : $settings['smtp_username'];
        } else {
            $smtp_config_missing = true;
            $mail->isMail();
        }

        $mail->setFrom($from_email, $from_name);
        $mail->addAddress($recipient_email);
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $html_body;

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Mailer Error: {$mail->ErrorInfo}");
        
        // Fallback to PHP mail() if SMTP fails (common on DMCA/offshore hosts)
        if ($mail->Mailer == 'smtp') {
            try {
                $fallbackMail = new PHPMailer(true);
                $fallbackMail->isMail();
                $fallbackMail->setFrom($from_email, $from_name);
                $fallbackMail->addAddress($recipient_email);
                $fallbackMail->isHTML(true);
                $fallbackMail->Subject = $subject;
                $fallbackMail->Body    = $html_body;
                $fallbackMail->send();
                return true;
            } catch (Exception $e2) {
                error_log("Fallback Mailer Error: {$fallbackMail->ErrorInfo}");
            }
        }
        return false;
    }
}





// --- 4. Shipment Update Logic (Modified to use new on_hold_reason column) ---

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_shipment'])) {
    $shipment_id = filter_var($_POST['shipment_id'], FILTER_VALIDATE_INT);
    $tracking_number = filter_var(trim($_POST['tracking_number_display']), FILTER_SANITIZE_SPECIAL_CHARS);
    $location = filter_var(trim($_POST['location']), FILTER_SANITIZE_SPECIAL_CHARS);
    
    // Status Update Message from dropdown (always present)
    $status_update_message = filter_var(trim($_POST['status_update'] ?? ''), FILTER_SANITIZE_SPECIAL_CHARS);
    
    // NEW: On Hold Reason from text area (only present if "On Hold" is selected)
    $on_hold_reason = filter_var(trim($_POST['on_hold_reason_field'] ?? ''), FILTER_SANITIZE_SPECIAL_CHARS);
    
    $current_shipment_status = filter_var(trim($_POST['current_shipment_status']), FILTER_SANITIZE_SPECIAL_CHARS);

    // Final message check: If status is On Hold, we must have a reason.
    if ($current_shipment_status === 'On Hold' && empty($on_hold_reason)) {
        $message = "Error: When status is 'On Hold', the On Hold Reason field cannot be empty.";
        $message_type = 'danger';
    } elseif ($shipment_id === false || empty($location) || empty($status_update_message) || empty($current_shipment_status)) {
        $message = "Error: Invalid shipment ID or missing data.";
        $message_type = 'danger';
    } else {
        $pdo->beginTransaction();
        try {
            // 1. Update Shipment Status
            $sql_update = "UPDATE shipments SET status = :status WHERE id = :shipment_id";
            $stmt_update = $pdo->prepare($sql_update);
            $stmt_update->bindParam(':status', $current_shipment_status);
            $stmt_update->bindParam(':shipment_id', $shipment_id, PDO::PARAM_INT);
            $stmt_update->execute();

            // 2. Insert Tracking History
            $sql_insert = "INSERT INTO tracking_history (shipment_id, location, status_update, on_hold_reason) 
                             VALUES (:shipment_id, :location, :status_update, :on_hold_reason)";
            $stmt_insert = $pdo->prepare($sql_insert);
            $stmt_insert->bindParam(':shipment_id', $shipment_id, PDO::PARAM_INT);
            $stmt_insert->bindParam(':location', $location);
            $stmt_insert->bindParam(':status_update', $status_update_message);
            
            $reason_to_save = ($current_shipment_status === 'On Hold') ? $on_hold_reason : NULL;
            $stmt_insert->bindParam(':on_hold_reason', $reason_to_save);
            $stmt_insert->execute();

            $pdo->commit();
            
            $sql_fetch = "SELECT receiver_name, receiver_email, tracking_number FROM shipments WHERE id = :shipment_id";
            $stmt_fetch = $pdo->prepare($sql_fetch);
            $stmt_fetch->bindParam(':shipment_id', $shipment_id, PDO::PARAM_INT);
            $stmt_fetch->execute();
            $shipment_info = $stmt_fetch->fetch(PDO::FETCH_ASSOC);

            if ($shipment_info && !empty($shipment_info['receiver_email'])) {
                $shipment_data = [
                    'tracking_number' => $shipment_info['tracking_number'],
                    'receiver_name' => $shipment_info['receiver_name'],
                    'current_shipment_status' => $current_shipment_status,
                    'location' => $location,
                    'status_update' => $status_update_message,
                    'on_hold_reason' => $reason_to_save
                ];
                $smtp_config_missing = false;
                $subject = "Shipment Tracking Update - #" . $shipment_info['tracking_number'];
                $html_body = get_tracking_update_email_body($shipment_data, $site_settings);
                send_email_notification($site_settings, $shipment_info['receiver_email'], $subject, $html_body, $smtp_config_missing);
            }
            
            $display_id = $tracking_number ?: $shipment_id;
            $message = "Tracking for shipment **#$display_id** updated to **$current_shipment_status** successfully!";
            $message_type = 'success';
        } catch (Exception $e) {
            if ($pdo->inTransaction()) { $pdo->rollBack(); }
            $message = "Database Error: Could not update tracking. " . $e->getMessage();
            $message_type = 'danger';
        }
    }
}

// --- 5. Shipment Deletion Logic ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['delete_shipment'])) {
    $shipment_id = filter_var($_POST['shipment_id'], FILTER_VALIDATE_INT);
    if ($shipment_id !== false) {
        $pdo->beginTransaction();
        try {
            $sql_del_history = "DELETE FROM tracking_history WHERE shipment_id = :id";
            $stmt_del_history = $pdo->prepare($sql_del_history);
            $stmt_del_history->bindParam(':id', $shipment_id, PDO::PARAM_INT);
            $stmt_del_history->execute();

            $sql_del_proof = "DELETE FROM payment_proofs WHERE shipment_id = :id";
            $stmt_del_proof = $pdo->prepare($sql_del_proof);
            $stmt_del_proof->bindParam(':id', $shipment_id, PDO::PARAM_INT);
            $stmt_del_proof->execute();

            $sql_del_shipment = "DELETE FROM shipments WHERE id = :id";
            $stmt_del_shipment = $pdo->prepare($sql_del_shipment);
            $stmt_del_shipment->bindParam(':id', $shipment_id, PDO::PARAM_INT);
            
            if ($stmt_del_shipment->execute()) {
                $pdo->commit();
                $_SESSION['message'] = "Shipment deleted successfully.";
                $_SESSION['message_type'] = 'success';
            } else {
                $pdo->rollBack();
                $_SESSION['message'] = "Error: Could not delete shipment.";
                $_SESSION['message_type'] = 'danger';
            }
        } catch (Exception $e) {
            if ($pdo->inTransaction()) { $pdo->rollBack(); }
            $_SESSION['message'] = "Database Error: " . $e->getMessage();
            $_SESSION['message_type'] = 'danger';
        }
    } else {
        $_SESSION['message'] = "Invalid Shipment ID.";
        $_SESSION['message_type'] = 'danger';
    }
    header("Location: shipment_manager.php");
    exit;
}

// --- Rest of the Existing Code (Shipment Retrieval and AJAX Location Fetch) ---

// --- Pagination Logic ---
$limit = 6;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$page = max(1, $page);
$offset = ($page - 1) * $limit;

try {
    // 1. Get total results count
    $total_count_sql = "SELECT COUNT(*) FROM shipments";
    $total_count_stmt = $pdo->query($total_count_sql);
    $total_records = $total_count_stmt->fetchColumn();
    $total_pages = ceil($total_records / $limit);

    // 2. Fetch paginated records
    $sql = "SELECT id AS shipment_id, tracking_number, sender_name, receiver_name, service_type, status, created_at, 
                   weight, dimensions, package_description, quantity, payment_status, amount, currency 
             FROM shipments 
             ORDER BY created_at DESC 
             LIMIT :limit OFFSET :offset";
    
    $stmt = $pdo->prepare($sql);
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $shipments = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $message = "Error retrieving shipments: " . $e->getMessage();
    $message_type = 'danger';
    $shipments = [];
    $total_pages = 1;
}

if (isset($_GET['fetch_location']) && isset($_GET['shipment_id'])) {
    $shipment_id = filter_var($_GET['shipment_id'], FILTER_VALIDATE_INT);
    $response = ['success' => false, 'location' => ''];

    if ($shipment_id !== false) {
        try {
            
            $sql_location = "SELECT location
                              FROM tracking_history 
                              WHERE shipment_id = :shipment_id 
                              ORDER BY updated_at DESC  
                              LIMIT 1";
            $stmt_location = $pdo->prepare($sql_location);
            $stmt_location->bindParam(':shipment_id', $shipment_id, PDO::PARAM_INT);
            $stmt_location->execute();
            $latest_track = $stmt_location->fetch(PDO::FETCH_ASSOC);

            if ($latest_track) {
                $response['success'] = true;
                $response['location'] = htmlspecialchars_decode($latest_track['location']); 
            } else {
                $response['location'] = "No tracking history found for this shipment.";
            }
        } catch (Exception $e) {
            $response['location'] = "Database error: " . $e->getMessage();
        }
    } else {
        $response['location'] = "Invalid shipment ID.";
    }

    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Shipments</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <?php if ($use_favicon): ?>
    <link rel="icon" type="<?php echo $favicon_mime; ?>" href="../<?php echo $favicon_path; ?>">
    <?php endif; ?>
	<link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
	
    <link href="https://fonts.googleapis.com/css2?family=Work+Sans:ital,wght@0,100..900;1,100..900&display=swap" rel="stylesheet">
	<link href="assets/css/style.css" rel="stylesheet">
	<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        :root {--bs-crimson-faded: #b000001a;} .btn-sm {padding: .5rem 1rem;font-size: .8125rem;min-height: 36px;}#mapid {height: 400px;width: 100%;border-radius: 8px;border: 1px solid #ccc;margin-top: 15px;}
        #wrapper { display: flex; width: 100%; min-height: 100vh; }
        .main-content-wrapper { flex-grow: 1; min-width: 0; position: relative; }
        @media (max-width: 768px) { #wrapper { display: block; } }
    
    @media (max-width: 768px) {
        .table-enhanced thead { display: none; }
        .table-responsive { overflow: visible !important; }
        .table-enhanced { background: transparent; box-shadow: none; border: none; min-width: 100% !important; }
        .table-enhanced tbody { display: flex; flex-direction: column; gap: 20px; width: 100%; }
        .table-enhanced tr { display: flex !important; flex-direction: column; border-radius: 18px; background: #fff; box-shadow: 0 8px 30px rgba(0,0,0,0.08); overflow: hidden; border: 1px solid #edf2f7; margin-bottom: 0px !important; }
        
        /* Layout Header */
        .table-enhanced td[data-label="Tracking ID"] { order: 1; display: flex; flex-direction: column; background: #212529; padding: 20px !important; color: white; border: none; }
        .table-enhanced td[data-label="Tracking ID"]::before { content: "TRACKING ID"; font-size: 0.6rem; color: #adb5bd; letter-spacing: 2px; flex: none; text-align: left; }
        .table-enhanced td[data-label="Tracking ID"] .mobile-row-value { font-size: 1.15rem; color: var(--bs-gold); text-align: left; font-family: 'JetBrains Mono', monospace; flex: none; width: 100%; }

        /* Status Row (Fixed at Top) */
        .table-enhanced td[data-label="Status"] { order: 2; padding: 10px 20px; background: #f8fafc; border-bottom: 1px solid #edf2f7; justify-content: center; }
        .table-enhanced td[data-label="Status"]::before { display: none; }
        .table-enhanced td[data-label="Status"] .badge { width: 100%; padding: 8px; border-radius: 8px; font-size: 0.8rem; }

        /* Sub-Details Grid */
        .table-enhanced td { order: 3; display: flex; justify-content: space-between; align-items: center; padding: 12px 20px; border-bottom: 1px solid #f8fafc; font-size: 0.85rem; }
        .table-enhanced td::before { content: attr(data-label); font-weight: 700; color: #64748b; font-size: 0.65rem; text-transform: uppercase; letter-spacing: 0.5px; }
        .mobile-row-value { font-weight: 700; color: #1e293b; text-align: right; }
        
        /* Actions Footer */
        .table-enhanced td.action-column { order: 4; display: grid !important; grid-template-columns: repeat(2, 1fr); gap: 10px; padding: 20px !important; background: #fff; border: none; margin-top: 10px; }
        .table-enhanced td.action-column::before { display: none; }
        .table-enhanced td.action-column .btn, .table-enhanced td.action-column form { width: 100% !important; height: 46px; margin: 0 !important; }

        .main-content-wrapper { padding: 20px 10px; background: #f1f5f9; }
    }
    .action-column { display: flex; align-items: center; justify-content: center; gap: 8px; }
 
    /* Premium Pagination Styles */
    .pagination .page-link {
        border: none;
        color: #495057;
        padding: 8px 16px;
        margin: 0 3px;
        border-radius: 8px !important;
        font-weight: 600;
        transition: all 0.3s;
    }
    .pagination .page-item.active .page-link {
        background: var(--bs-crimson-light);
        color: white;
        box-shadow: 0 4px 10px rgba(176,0,0,0.2);
    }
    .pagination .page-link:hover:not(.active) {
        background: #eef2f7;
        color: var(--bs-crimson-light);
    }
    </style>
</head>
<body>

     <?php include "nav.php" ?>
	
	 <div id="wrapper">
	 
	  <?php include "header.php" ?>
	  
 <div class="main-content-wrapper">
    <div id="main-content" class="container-fluid">
        <h4 class="fw-bolder mb-4">Manage Shipments</h4>

        <?php if ($message): ?>
            <script>
                const Toast = Swal.mixin({
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 4000,
                    timerProgressBar: true
                });
                Toast.fire({
                    icon: '<?php echo $message_type == "danger" ? "error" : $message_type; ?>',
                    title: '<?php echo addslashes($message); ?>'
                });
            </script>
        <?php endif; ?>

        <div class="card-enhanced shadow-lg mb-4">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table-enhanced table-hover table-striped align-middle">
                        <thead class="table-dark">
                            <tr>
                                <th>Tracking #</th>
                                <th>Sender</th>
                                <th>Receiver</th>
                                <th class="d-none d-md-table-cell">Service</th>
                                <th>Status</th>
                                <th>Date Created</th>
                                <th class="text-center">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($shipments)): ?>
                            <tr>
                                <td colspan="7" class="text-center py-4 text-muted">No shipments found.</td>
                            </tr>
                            <?php else: ?>
                                <?php foreach ($shipments as $shipment): ?>
                                 <tr>
                                    <td data-label="Tracking ID" class="fw-bold">
                                        <span class="mobile-row-value tracking-copy" 
                                              data-tn="<?php echo htmlspecialchars($shipment['tracking_number']); ?>" 
                                              style="cursor: pointer;" 
                                              title="Click to copy">
                                            <?php echo htmlspecialchars($shipment['tracking_number']); ?>
                                            <i class="bi bi-copy ms-1 text-muted" style="font-size: 0.8rem;"></i>
                                        </span>
                                    </td>
                                    <td data-label="Sender"><span class="mobile-row-value"><?php echo htmlspecialchars($shipment['sender_name']); ?></span></td>
                                    <td data-label="Receiver"><span class="mobile-row-value"><?php echo htmlspecialchars($shipment['receiver_name']); ?></span></td>
                                    <td data-label="Weight / Qty" class="d-md-none"><span class="mobile-row-value"><?php echo htmlspecialchars($shipment['weight']); ?>kg / <?php echo htmlspecialchars($shipment['quantity']); ?> pcs</span></td>
                                    <td data-label="Payment Status" class="d-md-none"><span class="mobile-row-value <?php echo ($shipment['payment_status'] == 'Paid') ? 'text-success' : 'text-danger'; ?>"><?php echo htmlspecialchars($shipment['payment_status']); ?></span></td>
                                    <td data-label="Description" class="d-md-none"><span class="mobile-row-value"><?php echo htmlspecialchars($shipment['package_description']); ?></span></td>
                                    <td data-label="Service" class="d-none d-md-table-cell"><span class="mobile-row-value"><?php echo htmlspecialchars($shipment['service_type']); ?></span></td>
                                    <?php

$status = htmlspecialchars($shipment['status']);
switch (strtolower($status)) {
    case 'pending':
        $badgeClass = 'badge badge-secondary';
        break;
    case 'in transit':
        $badgeClass = 'badge badge-info';
        break;
    case 'on hold':
        $badgeClass = 'badge badge-warning';
        break;
    case 'delivered':
        $badgeClass = 'badge badge-success';
        break;
    case 'out for delivery':
        $badgeClass = 'badge badge-primary';
        break;
    case 'exception':
    case 'failed delivery attempt':
        $badgeClass = 'badge badge-danger';
        break;
    default:
        $badgeClass = 'badge-dark';
        break;
}
?>
<td data-label="Status">
    <span class="badge <?php echo $badgeClass; ?> mobile-row-value">
        <?php echo $status; ?>
    </span>
</td>

                                    <td data-label="Date Created"><span class="mobile-row-value"><?php echo date('Y-m-d', strtotime(htmlspecialchars($shipment['created_at']))); ?></span></td>
                                    <td data-label="Actions" class="action-column">
    <button type="button" class="btn btn-sm btn-info text-white map-btn"
        data-bs-toggle="modal" 
        data-bs-target="#mapModal"
        data-id="<?php echo htmlspecialchars($shipment['shipment_id']); ?>"
        data-track="<?php echo htmlspecialchars($shipment['tracking_number']); ?>">
        <i class="bi bi-geo-alt-fill"></i>
    </button>

    <button type="button" class="btn btn-sm btn-secondary update-btn"
        data-bs-toggle="modal" 
        data-bs-target="#updateStatusModal"
        data-id="<?php echo htmlspecialchars($shipment['shipment_id']); ?>"
        data-track="<?php echo htmlspecialchars($shipment['tracking_number']); ?>"
        data-current-status="<?php echo htmlspecialchars($shipment['status']); ?>"
        title="Update Status">
        <i class="bi bi-activity"></i>
    </button>

    <a href="edit_shipment.php?id=<?php echo htmlspecialchars($shipment['shipment_id']); ?>" 
       class="btn btn-sm btn-primary" title="Full Edit">
        <i class="bi bi-pencil-fill"></i>
    </a>

    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST" class="delete-shipment-form" style="display:inline-block;">
        <input type="hidden" name="shipment_id" value="<?php echo htmlspecialchars($shipment['shipment_id']); ?>">
        <input type="hidden" name="delete_shipment" value="1">
        <button type="button" class="btn btn-sm btn-danger delete-shipment-btn" data-track="<?php echo htmlspecialchars($shipment['tracking_number']); ?>">
            <i class="bi bi-trash3-fill"></i>
        </button>
    </form>
</td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- --- Pagination UI --- -->
                <?php if ($total_pages > 1): ?>
                <nav aria-label="Page navigation" class="mt-4">
                    <ul class="pagination justify-content-center">
                        <li class="page-item <?php echo ($page <= 1) ? 'disabled' : ''; ?>">
                            <a class="page-link" href="?page=<?php echo $page - 1; ?>"><i class="bi bi-chevron-left"></i></a>
                        </li>
                        
                        <?php 
                        $start = max(1, $page - 2);
                        $end = min($total_pages, $page + 2);
                        
                        if ($start > 1) {
                            echo '<li class="page-item"><a class="page-link" href="?page=1">1</a></li>';
                            if ($start > 2) echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                        }
                        
                        for ($i = $start; $i <= $end; $i++): ?>
                            <li class="page-item <?php echo ($page == $i) ? 'active' : ''; ?>">
                                <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                            </li>
                        <?php endfor; 
                        
                        if ($end < $total_pages) {
                            if ($end < $total_pages - 1) echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                            echo '<li class="page-item"><a class="page-link" href="?page='.$total_pages.'">'.$total_pages.'</a></li>';
                        }
                        ?>

                        <li class="page-item <?php echo ($page >= $total_pages) ? 'disabled' : ''; ?>">
                            <a class="page-link" href="?page=<?php echo $page + 1; ?>"><i class="bi bi-chevron-right"></i></a>
                        </li>
                    </ul>
                </nav>
                <?php endif; ?>
                <!-- ---------------------- -->

            </div>
        </div>
    </div> <!-- #main-content -->
  </div> <!-- .main-content-wrapper -->
</div> <!-- #wrapper -->
    
    <div class="modal fade" id="updateStatusModal" tabindex="-1" aria-labelledby="updateStatusModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
                    <input type="hidden" name="update_shipment" value="1">
                    
                    <div class="modal-header">
                        <h5 class="modal-title" id="updateStatusModalLabel">Update Shipment Status</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="shipment_id" id="modal_shipment_id">
                        <input type="hidden" name="tracking_number_display" id="modal_tracking_number_hidden">

                        <div class="mb-3">
                            <label for="modal_tracking_number" class="form-label fw-bold">Tracking Number</label>
                            <input type="text" class="form-control bg-light" id="modal_tracking_number" readonly>
                        </div>
                        
                        <div class="mb-3">
                            <label for="location" class="form-label">New Location (City, State/Country) *</label>
                            <input type="text" class="form-control" id="location" name="location" placeholder="e.g., London, UK" required>
                            <div class="form-text">This location will be added to the tracking history.</div>
                        </div>

                        <div class="mb-3">
                            <label for="status_update" class="form-label">Tracking History Update Message *</label>
                            <select class="form-select" id="status_update" name="status_update" required>
                                <option value="" disabled selected>Select an event...</option>
                                 <option value="In Transit">In Transit</option>
                                 <option value="Out for Delivery">Out for Delivery</option>
                                 <option value="On Hold">On Hold</option>
                                 <option value="Delivered">Delivered</option>
                                 <option value="Exception">Exception</option>
                            </select>
                            <div class="form-text">This text goes into the tracking timeline.</div>
                        </div>

                        <!-- Overall Shipment Status (locked) -->
<div class="mb-3">
  <label for="current_shipment_status" class="form-label fw-bold">Overall Shipment Status *</label>
  <select class="form-select" id="current_shipment_status" disabled></select>
  <input type="hidden" name="current_shipment_status" id="hidden_status" required>
  <div class="form-text text-danger">This updates the main status column in the table.</div>
</div>


<div class="mb-3" id="onHoldReasonBox" style="display: none;">
        <label for="on_hold_reason" class="form-label text-warning fw-bold">On Hold Reason *</label>
        <textarea class="form-control" id="on_hold_reason" name="on_hold_reason_field" rows="3" placeholder="Enter the detailed reason for the shipment being on hold (e.g., Missing documentation, Customs clearance delay)." required></textarea>
        <div class="form-text">This detailed reason will be recorded as the <strong>Tracking History Update Message</strong> if selected.</div>
    </div>
						
						
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-crimson fw-bold shadow-sm"><i class="bi bi-save me-1"></i> Save Update</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
	
	
	<div class="modal fade" id="mapModal" tabindex="-1" aria-labelledby="mapModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mapModalLabel">Current Location: <span id="map_tracking_number_display" class="fw-bold"></span></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p class="text-muted">Last reported location: <strong id="map_location_display">Loading...</strong></p>
                    <div id="mapid"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
</div>
	
	</div>
    <?php include "footer.php" ?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <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://code.jquery.com/jquery-3.6.0.min.js"></script>
    
   
    <script>
    
    var shipmentMap = null;

  
function geocodeLocation(locationString, mapContainerId, mapLocationDisplay) {
    
    $(mapLocationDisplay).text(locationString); 
    
    
    var nominatimUrl = `https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(locationString)}&limit=1`;

    $.getJSON(nominatimUrl, function(data) {
        if (data && data.length > 0) {
            var lat = data[0].lat;
            var lon = data[0].lon;

            
            var formattedAddress = data[0].display_name;
            $(mapLocationDisplay).text(formattedAddress);
            
            
            if (shipmentMap === null) {
                shipmentMap = L.map(mapContainerId).setView([lat, lon], 13);
                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 {
                shipmentMap.setView([lat, lon], 13);
            }
            
            
            shipmentMap.eachLayer(function(layer) {
                if (layer instanceof L.Marker) {
                    shipmentMap.removeLayer(layer);
                }
            });
            L.marker([lat, lon]).addTo(shipmentMap)
                .bindPopup(locationString)
                .openPopup();

        } else {
            
            $(mapLocationDisplay).text(locationString + " (Map coordinates not found. Showing world 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 {
                shipmentMap.setView([0, 0], 2);
                shipmentMap.eachLayer(function(layer) { // Clear markers if we fall back
                    if (layer instanceof L.Marker) {
                        shipmentMap.removeLayer(layer);
                    }
                });
            }
        }
    }).fail(function(jqXHR, textStatus, errorThrown) {
        
        let errorMsg = locationString;
        if (jqXHR.status === 403) {
             errorMsg += " (Map service temporarily blocked (403: Rate Limit).)";
        } else {
             errorMsg += " (Error connecting to map service for geo-coding. Check console for details.)";
        }
        $(mapLocationDisplay).text(errorMsg);

        
        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);
        }
    });
}

    $(document).ready(function() {
        
        $('#updateStatusModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget);
            var shipmentId = button.data('id');
            var trackingNumber = button.data('track');
            var currentStatus = button.data('current-status');

            var modal = $(this);
            modal.find('#modal_shipment_id').val(shipmentId);
            modal.find('#modal_tracking_number').val(trackingNumber);
            modal.find('#modal_tracking_number_hidden').val(trackingNumber);
            modal.find('#current_shipment_status').val(currentStatus);
            modal.find('#location').val('');
            modal.find('#status_update').val('');
            
            if (modal.find('#current_shipment_status').val() !== currentStatus) {
                modal.find('#current_shipment_status').val('In Transit');
            }
        });

        
        $('#mapModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget);
            var shipmentId = button.data('id');
            var trackingNumber = button.data('track');
            
            var modal = $(this);
            modal.find('#map_tracking_number_display').text(trackingNumber);
            modal.find('#map_location_display').text("Fetching location...");

            
            $.ajax({
                url: '<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>',
                type: 'GET',
                dataType: 'json',
                data: {
                    fetch_location: 1, 
                    shipment_id: shipmentId
                },
                success: function(response) {
                    if (response.success && response.location) {
                        
                        geocodeLocation(response.location, 'mapid', '#map_location_display');
                    } else {
                       
                        modal.find('#map_location_display').text(response.location || "No location data found in history.");
                       
                        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);
                        }
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                   
                    modal.find('#map_location_display').text("Error fetching location data: " + textStatus);
                }
            });

        });

       
        $('#mapModal').on('shown.bs.modal', function() {
            if (shipmentMap !== null) {
                shipmentMap.invalidateSize();
            }
        });
    });
</script>

    <script>
        
        $(document).ready(function() {
            $('#updateStatusModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget); 
                var shipmentId = button.data('id');
                var trackingNumber = button.data('track');
                var currentStatus = button.data('current-status');

                var modal = $(this);
                
                
                modal.find('#modal_shipment_id').val(shipmentId);
                
                
                modal.find('#modal_tracking_number').val(trackingNumber);
                modal.find('#modal_tracking_number_hidden').val(trackingNumber); 
                
               
                modal.find('#current_shipment_status').val(currentStatus);
                
                
                modal.find('#location').val('');
                modal.find('#status_update').val('');
                
                
                if (modal.find('#current_shipment_status').val() !== currentStatus) {
                    modal.find('#current_shipment_status').val('In Transit'); 
                }
            });
        });
    </script>
	
<script>
document.addEventListener("DOMContentLoaded", function() {
    const statusUpdate = document.getElementById("status_update");
    const overallStatus = document.getElementById("current_shipment_status");
    const hiddenStatus = document.getElementById("hidden_status");
    const onHoldReasonBox = document.getElementById("onHoldReasonBox"); // The new box container
    const onHoldReasonField = document.getElementById("on_hold_reason"); // The new text area (name="on_hold_reason_field")
    const validStatuses = ["Pending", "In Transit", "Out for Delivery", "On Hold", "Delivered", "Exception"];

    // 1. Initial setup for overall status dropdown
    overallStatus.innerHTML = '';
    overallStatus.setAttribute("disabled", true);
   
    statusUpdate.addEventListener("change", function() {
        const selected = this.value?.trim() || '';

        // Conditional display for On Hold Reason
        if (selected === 'On Hold') {
            onHoldReasonBox.style.display = 'block';
            onHoldReasonField.setAttribute('required', 'required'); // Require the reason
        } else {
            onHoldReasonBox.style.display = 'none';
            onHoldReasonField.removeAttribute('required'); // Remove required for other statuses
            onHoldReasonField.value = ''; // Clear value for non-On Hold submissions
        }

        // Update Overall Status and hidden field
        if (validStatuses.includes(selected)) {
            overallStatus.innerHTML = `<option value="${selected}">${selected}</option>`;
            hiddenStatus.value = selected;
        } else {
            overallStatus.innerHTML = '';
            hiddenStatus.value = '';
        }
    });

    // 3. Setup on Modal show to ensure correct state and clear state
    $('#updateStatusModal').on('show.bs.modal', function() {
       
        onHoldReasonBox.style.display = 'none';
        onHoldReasonField.value = '';
        onHoldReasonField.removeAttribute('required');
        
        if (statusUpdate.value) {
             $(statusUpdate).trigger('change');
        }
    });
});
</script>

<script>
$(document).on('click', '.delete-shipment-btn', function(e) {
    e.preventDefault();
    const form = $(this).closest('form');
    const trackingNumber = $(this).data('track');
    
    Swal.fire({
        title: 'Are you sure?',
        text: `You are about to permanently delete shipment #${trackingNumber}. This action cannot be undone!`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#B00000',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Yes, delete it!',
        cancelButtonText: 'Cancel',
        reverseButtons: true,
        background: '#fff',
        customClass: {
            confirmButton: 'btn btn-danger px-4',
            cancelButton: 'btn btn-secondary px-4'
        },
        buttonsStyling: false
    }).then((result) => {
        if (result.isConfirmed) {
            // Show loading state
            Swal.fire({
                title: 'Deleting...',
                text: 'Please wait while we process the removal.',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            form.submit();
        }
    });
});
</script>

<script>
$(document).ready(function() {
    $('.tracking-copy').on('click', function() {
        const trackingNumber = $(this).data('tn');
        const tempInput = document.createElement('input');
        tempInput.value = trackingNumber;
        document.body.appendChild(tempInput);
        tempInput.select();
        document.execCommand('copy');
        document.body.removeChild(tempInput);

        const Toast = Swal.mixin({
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 2000,
            timerProgressBar: true
        });
        
        Toast.fire({
            icon: 'success',
            title: 'Tracking number copied!',
            text: trackingNumber
        });
    });
});
</script>

	
	
</body>
</html>