<?php
$page_title = 'Edit Parcel - Admin';

if (!Admin::isLoggedIn()) {
    Utils::redirect('/routex/admin/login');
}

require_once __DIR__ . '/../../app/Services/EmailService.php';
$parcel_model = new Parcel($pdo);
$email_service = new EmailService($pdo);
$parcel_id = $_GET['id'] ?? null;
$error = '';
$success = '';

if (!$parcel_id) {
    Utils::redirect('/routex/admin/parcels');
}

$parcel = $parcel_model->getById($parcel_id);
if (!$parcel) {
    Utils::redirect('/routex/admin/parcels');
}

$updates = $parcel_model->getUpdates($parcel_id);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'update_parcel') {
        $data = [
            'sender_name' => $_POST['sender_name'] ?? '',
            'sender_email' => $_POST['sender_email'] ?? '',
            'sender_phone' => $_POST['sender_phone'] ?? '',
            'sender_address' => $_POST['sender_address'] ?? '',
            'sender_city' => $_POST['sender_city'] ?? '',
            'sender_country' => $_POST['sender_country'] ?? '',
            'receiver_name' => $_POST['receiver_name'] ?? '',
            'receiver_email' => $_POST['receiver_email'] ?? '',
            'receiver_phone' => $_POST['receiver_phone'] ?? '',
            'receiver_address' => $_POST['receiver_address'] ?? '',
            'receiver_city' => $_POST['receiver_city'] ?? '',
            'receiver_country' => $_POST['receiver_country'] ?? '',
            'package_description' => $_POST['package_description'] ?? '',
            'package_weight' => $_POST['package_weight'] ?? 0,
            'package_dimensions' => $_POST['package_dimensions'] ?? '',
            'service_type' => $_POST['service_type'] ?? 'air_freight',
            'estimated_delivery' => $_POST['estimated_delivery'] ?? null,
            'notes' => $_POST['notes'] ?? ''
        ];

        if ($parcel_model->update($parcel_id, $data)) {
            $success = 'Parcel updated successfully!';
            $parcel = $parcel_model->getById($parcel_id);
        } else {
            $error = 'Failed to update parcel.';
        }
    } elseif ($action === 'add_update') {
        $status = $_POST['status'] ?? '';
        $location = $_POST['location'] ?? '';
        $description = $_POST['description'] ?? '';
        $latitude = !empty($_POST['latitude']) ? $_POST['latitude'] : null;
        $longitude = !empty($_POST['longitude']) ? $_POST['longitude'] : null;

        if (empty($status) || empty($location)) {
            $error = 'Status and location are required.';
        } else {
            if ($parcel_model->addUpdate($parcel_id, $status, $location, $description, $latitude, $longitude)) {
                // Send notification email
                $updated_parcel = $parcel_model->getById($parcel_id);
                if ($updated_parcel['receiver_email']) {
                    $email_service->sendParcelNotification($updated_parcel, $updated_parcel['receiver_email']);
                }
                
                $success = 'Parcel update added and notification sent!';
                $parcel = $parcel_model->getById($parcel_id);
                $updates = $parcel_model->getUpdates($parcel_id);
            } else {
                $error = 'Failed to add update.';
            }
        }
    } elseif ($action === 'delete_parcel') {
        if ($parcel_model->delete($parcel_id)) {
            Utils::redirect('/routex/admin/parcels');
        } else {
            $error = 'Failed to delete parcel.';
        }
    }
}

$csrf_token = Utils::generateCSRFToken();
require_once __DIR__ . '/../../includes/trackheader.php';
?>

<section class="min-h-screen bg-gray-50">
    <div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        <!-- Header -->
        <div class="flex justify-between items-center mb-8">
            <div>
                <h1 class="text-4xl font-bold text-gray-900">Edit Parcel</h1>
                <p class="text-gray-600 mt-2">Tracking: <input value="<?= htmlspecialchars($parcel->tracking_code ?? '') ?>">
</p>
            </div>
            <a href="/routex/admin/parcels" class="btn-secondary">
                <i class="fas fa-arrow-left mr-2"></i>Back
            </a>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- Main Form -->
            <div class="lg:col-span-2">
                <div class="bg-white rounded-xl shadow-md p-8 mb-8">
                    <?php if ($error): ?>
                    <div class="bg-red-50 border-l-4 border-red-500 p-4 rounded-lg mb-6">
                        <p class="text-red-700"><?php echo htmlspecialchars($error); ?></p>
                    </div>
                    <?php endif; ?>

                    <?php if ($success): ?>
                    <div class="bg-green-50 border-l-4 border-green-500 p-4 rounded-lg mb-6">
                        <p class="text-green-700"><?php echo htmlspecialchars($success); ?></p>
                    </div>
                    <?php endif; ?>

                    <form method="POST" class="space-y-8">
                        <input type="hidden" name="action" value="update_parcel">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">

                        <!-- Sender Section -->
                        <div>
                            <h3 class="text-xl font-bold text-gray-900 mb-4">Sender Information</h3>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-gray-900 font-semibold mb-2">Name</label>
                                    <input type="text" name="sender_name" value="<?php echo htmlspecialchars($parcel['sender_name']); ?>" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600">
                                </div>
                                <div>
                                    <label class="block text-gray-900 font-semibold mb-2">Email</label>
                                    <input type="email" name="sender_email" value="<?php echo htmlspecialchars($parcel['sender_email'] ?? ''); ?>" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600">
                                </div>
                                <div>
                                    <label class="block text-gray-900 font-semibold mb-2">Phone</label>
                                    <input type="tel" name="sender_phone" value="<?php echo htmlspecialchars($parcel['sender_phone'] ?? ''); ?>" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600">
                                </div>
                                <div>
                                    <label class="block text-gray-900 font-semibold mb-2">Country</label>
                                    <input type="text" name="sender_country" value="<?php echo htmlspecialchars($parcel['sender_country'] ?? ''); ?>" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600">
                                </div>
                                <div>
                                    <label class="block text-gray-900 font-semibold mb-2">City</label>
                                    <input type="text" name="sender_city" value="<?php echo htmlspecialchars($parcel['sender_city'] ?? ''); ?>" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600">
                                </div>
                                <div>
                                    <label class="block text-gray-900 font-semibold mb-2">Address</label>
                                    <input type="text" name="sender_address" value="<?php echo htmlspecialchars($parcel['sender_address'] ?? ''); ?>" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600">
                                </div>
                            </div>
                        </div>

                        <!-- Receiver Section -->
                        <div>
                            <h3 class="text-xl font-bold text-gray-900 mb-4">Receiver Information</h3>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-gray-900 font-semibold mb-2">Name</label>
                                    <input type="text" name="receiver_name" value="<?php echo htmlspecialchars($parcel['receiver_name']); ?>" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600">
                                </div>
                                <div>
                                    <label class="block text-gray-900 font-semibold mb-2">Email</label>
                                    <input type="email" name="receiver_email" value="<?php echo htmlspecialchars($parcel['receiver_email'] ?? ''); ?>" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600">
                                </div>
                                <div>
                                    <label class="block text-gray-900 font-semibold mb-2">Phone</label>
                                    <input type="tel" name="receiver_phone" value="<?php echo htmlspecialchars($parcel['receiver_phone'] ?? ''); ?>" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600">
                                </div>
                                <div>
                                    <label class="block text-gray-900 font-semibold mb-2">Country</label>
                                    <input type="text" name="receiver_country" value="<?php echo htmlspecialchars($parcel['receiver_country'] ?? ''); ?>" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600">
                                </div>
                                <div>
                                    <label class="block text-gray-900 font-semibold mb-2">City</label>
                                    <input type="text" name="receiver_city" value="<?php echo htmlspecialchars($parcel['receiver_city'] ?? ''); ?>" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600">
                                </div>
                                <div>
                                    <label class="block text-gray-900 font-semibold mb-2">Address</label>
                                    <input type="text" name="receiver_address" value="<?php echo htmlspecialchars($parcel['receiver_address'] ?? ''); ?>" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600">
                                </div>
                            </div>
                        </div>

                        <!-- Package Section -->
                        <div>
                            <h3 class="text-xl font-bold text-gray-900 mb-4">Package Information</h3>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-gray-900 font-semibold mb-2">Description</label>
                                    <input type="text" name="package_description" value="<?php echo htmlspecialchars($parcel['package_description'] ?? ''); ?>" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600">
                                </div>
                                <div>
                                    <label class="block text-gray-900 font-semibold mb-2">Weight (kg)</label>
                                    <input type="number" name="package_weight" step="0.01" value="<?php echo htmlspecialchars($parcel['package_weight'] ?? 0); ?>" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600">
                                </div>
                                <div>
                                    <label class="block text-gray-900 font-semibold mb-2">Dimensions</label>
                                    <input type="text" name="package_dimensions" value="<?php echo htmlspecialchars($parcel['package_dimensions'] ?? ''); ?>" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600">
                                </div>
                                <div>
                                    <label class="block text-gray-900 font-semibold mb-2">Service Type</label>
                                    <select name="service_type" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600">
                                        <option value="air_freight" <?php echo $parcel['service_type'] === 'air_freight' ? 'selected' : ''; ?>>Air Freight</option>
                                        <option value="sea_freight" <?php echo $parcel['service_type'] === 'sea_freight' ? 'selected' : ''; ?>>Sea Freight</option>
                                        <option value="road_transport" <?php echo $parcel['service_type'] === 'road_transport' ? 'selected' : ''; ?>>Road Transport</option>
                                        <option value="warehousing" <?php echo $parcel['service_type'] === 'warehousing' ? 'selected' : ''; ?>>Warehousing</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <!-- Additional Info -->
                        <div>
                            <h3 class="text-xl font-bold text-gray-900 mb-4">Additional Information</h3>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-gray-900 font-semibold mb-2">Estimated Delivery</label>
                                    <input type="date" name="estimated_delivery" value="<?php echo htmlspecialchars($parcel['estimated_delivery'] ?? ''); ?>" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600">
                                </div>
                                <div>
                                    <label class="block text-gray-900 font-semibold mb-2">Notes</label>
                                    <input type="text" name="notes" value="<?php echo htmlspecialchars($parcel['notes'] ?? ''); ?>" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600">
                                </div>
                            </div>
                        </div>

                        <!-- Buttons -->
                        <div class="flex gap-4">
                            <button type="submit" class="btn-primary">
                                <i class="fas fa-save mr-2"></i>Save Changes
                            </button>
                            <a href="/routex/admin/parcels" class="btn-secondary">
                                <i class="fas fa-times mr-2"></i>Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Sidebar -->
            <div class="lg:col-span-1">
                <!-- Status Card -->
                <div class="bg-white rounded-xl shadow-md p-6 mb-6">
                    <h3 class="text-lg font-bold text-gray-900 mb-4">Current Status</h3>
                    <div class="mb-4">
                        <span class="<?php echo Utils::getStatusColor($parcel['status']); ?> status-badge text-lg">
                            <?php echo Utils::getStatusLabel($parcel['status']); ?>
                        </span>
                    </div>
                    <p class="text-gray-600 text-sm mb-2">
                        <strong>Location:</strong> <?php echo htmlspecialchars($parcel['current_location'] ?? 'N/A'); ?>
                    </p>
                    <p class="text-gray-600 text-sm">
                        <strong>Created:</strong> <?php echo Utils::formatDateTime($parcel['created_at']); ?>
                    </p>
                </div>

                <!-- Add Update Form -->
                <div class="bg-white rounded-xl shadow-md p-6 mb-6">
                    <h3 class="text-lg font-bold text-gray-900 mb-4">Add Update</h3>
                    <form method="POST" class="space-y-4">
                        <input type="hidden" name="action" value="add_update">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">

                        <div>
                            <label class="block text-gray-900 font-semibold mb-2 text-sm">Status</label>
                            <select name="status" class="w-full px-3 py-2 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600 text-sm">
                                <option value="pending">Pending</option>
                                <option value="picked_up">Picked Up</option>
                                <option value="in_transit">In Transit</option>
                                <option value="out_for_delivery">Out for Delivery</option>
                                <option value="delivered">Delivered</option>
                                <option value="cancelled">Cancelled</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-gray-900 font-semibold mb-2 text-sm">Location</label>
                            <input type="text" name="location" class="w-full px-3 py-2 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600 text-sm" required>
                        </div>

                        <div class="grid grid-cols-2 gap-2">
                            <div>
                                <label class="block text-gray-900 font-semibold mb-2 text-sm">Latitude</label>
                                <input type="text" name="latitude" class="w-full px-3 py-2 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600 text-sm" placeholder="e.g. 51.5074">
                            </div>
                            <div>
                                <label class="block text-gray-900 font-semibold mb-2 text-sm">Longitude</label>
                                <input type="text" name="longitude" class="w-full px-3 py-2 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600 text-sm" placeholder="e.g. -0.1278">
                            </div>
                        </div>

                        <div>
                            <label class="block text-gray-900 font-semibold mb-2 text-sm">Description</label>
                            <input type="text" name="description" class="w-full px-3 py-2 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600 text-sm">
                        </div>

                        <button type="submit" class="w-full btn-primary text-sm">
                            <i class="fas fa-plus mr-2"></i>Add Update
                        </button>
                    </form>
                </div>

                <!-- Delete Button -->
                <form method="POST" onsubmit="return confirm('Are you sure you want to delete this parcel?');">
                    <input type="hidden" name="action" value="delete_parcel">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                    <button type="submit" class="w-full px-4 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 transition font-semibold">
                        <i class="fas fa-trash mr-2"></i>Delete Parcel
                    </button>
                </form>
            </div>
        </div>

        <!-- Updates Timeline -->
        <div class="bg-white rounded-xl shadow-md p-8 mt-8">
            <h3 class="text-2xl font-bold text-gray-900 mb-6">Update History</h3>
            
            <div class="relative">
                <?php if (!empty($updates)): ?>
                    <?php foreach ($updates as $update): ?>
                    <div class="timeline-item">
                        <div class="bg-gray-50 p-4 rounded-lg">
                            <div class="flex justify-between items-start mb-2">
                                <h4 class="font-semibold text-gray-900"><?php echo Utils::getStatusLabel($update['status']); ?></h4>
                                <span class="text-sm text-gray-600"><?php echo Utils::formatDateTime($update['created_at']); ?></span>
                            </div>
                            <p class="text-gray-700 mb-2"><?php echo htmlspecialchars($update['description'] ?? ''); ?></p>
                            <p class="text-gray-600 text-sm">
                                <i class="fas fa-map-marker-alt mr-2 text-purple-600"></i>
                                <?php echo htmlspecialchars($update['location'] ?? ''); ?>
                            </p>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p class="text-gray-600 text-center py-8">No updates yet</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

<footer class="bg-white border-t mt-20 no-print">
  <div class="max-w-7xl mx-auto px-4 py-6 text-center text-sm text-slate-500">
    © 2026 RoutexShipping. All rights reserved.
  </div>
</footer>

