<?php
$page_title = 'Create 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);
$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    if (!Utils::verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $error = 'Security token invalid. Please try again.';
    } else {
        $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',
            'status' => 'pending',
            'current_location' => $_POST['sender_city'] ?? '', // Default to sender city
            'current_latitude' => !empty($_POST['latitude']) ? $_POST['latitude'] : null,
            'current_longitude' => !empty($_POST['longitude']) ? $_POST['longitude'] : null,
            'estimated_delivery' => $_POST['estimated_delivery'] ?? null,
            'notes' => $_POST['notes'] ?? ''
        ];

        $result = $parcel_model->create($data);

        if ($result['success']) {
            // Send notification email
            if ($data['receiver_email']) {
                $new_parcel = $parcel_model->getById($result['parcel_id']);
                $email_service->sendParcelNotification($new_parcel, $data['receiver_email']);
            }
            
            Utils::redirect('/routex/admin/parcel-edit?id=' . $result['parcel_id']);
        } else {
            $error = 'Failed to create 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">
            <h1 class="text-4xl font-bold text-gray-900">Create New Parcel</h1>
            <a href="/routex/admin/parcels" class="btn-secondary">
                <i class="fas fa-arrow-left mr-2"></i>Back
            </a>
        </div>

        <div class="bg-white rounded-xl shadow-md p-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; ?>

            <form method="POST" class="space-y-8">
                <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 font-semibold mb-2">Name</label><input type="text" name="sender_name" class="w-full px-4 py-3 border rounded-lg" required></div>
                        <div><label class="block font-semibold mb-2">Email</label><input type="email" name="sender_email" class="w-full px-4 py-3 border rounded-lg"></div>
                        <div><label class="block font-semibold mb-2">Phone</label><input type="tel" name="sender_phone" class="w-full px-4 py-3 border rounded-lg"></div>
                        <div><label class="block font-semibold mb-2">Country</label><input type="text" name="sender_country" class="w-full px-4 py-3 border rounded-lg"></div>
                        <div><label class="block font-semibold mb-2">City</label><input type="text" name="sender_city" class="w-full px-4 py-3 border rounded-lg" required></div>
                        <div><label class="block font-semibold mb-2">Address</label><input type="text" name="sender_address" class="w-full px-4 py-3 border rounded-lg"></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 font-semibold mb-2">Name</label><input type="text" name="receiver_name" class="w-full px-4 py-3 border rounded-lg" required></div>
                        <div><label class="block font-semibold mb-2">Email</label><input type="email" name="receiver_email" class="w-full px-4 py-3 border rounded-lg" required></div>
                        <div><label class="block font-semibold mb-2">Phone</label><input type="tel" name="receiver_phone" class="w-full px-4 py-3 border rounded-lg"></div>
                        <div><label class="block font-semibold mb-2">Country</label><input type="text" name="receiver_country" class="w-full px-4 py-3 border rounded-lg"></div>
                        <div><label class="block font-semibold mb-2">City</label><input type="text" name="receiver_city" class="w-full px-4 py-3 border rounded-lg" required></div>
                        <div><label class="block font-semibold mb-2">Address</label><input type="text" name="receiver_address" class="w-full px-4 py-3 border rounded-lg"></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 font-semibold mb-2">Description</label><input type="text" name="package_description" class="w-full px-4 py-3 border rounded-lg" required></div>
                        <div><label class="block font-semibold mb-2">Weight (kg)</label><input type="number" step="0.01" name="package_weight" class="w-full px-4 py-3 border rounded-lg"></div>
                        <div><label class="block font-semibold mb-2">Dimensions</label><input type="text" name="package_dimensions" class="w-full px-4 py-3 border rounded-lg" placeholder="L x W x H"></div>
                        <div>
                            <label class="block font-semibold mb-2">Service Type</label>
                            <select name="service_type" class="w-full px-4 py-3 border rounded-lg">
                                <option value="air_freight">Air Freight</option>
                                <option value="sea_freight">Sea Freight</option>
                                <option value="road_transport">Road Transport</option>
                                <option value="warehousing">Warehousing</option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- Initial Location -->
                <div>
                    <h3 class="text-xl font-bold text-gray-900 mb-4">Initial Location (Optional)</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div><label class="block font-semibold mb-2">Latitude</label><input type="text" name="latitude" class="w-full px-4 py-3 border rounded-lg" placeholder="e.g. 51.5074"></div>
                        <div><label class="block font-semibold mb-2">Longitude</label><input type="text" name="longitude" class="w-full px-4 py-3 border rounded-lg" placeholder="e.g. -0.1278"></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 font-semibold mb-2">Estimated Delivery</label><input type="date" name="estimated_delivery" class="w-full px-4 py-3 border rounded-lg"></div>
                        <div><label class="block font-semibold mb-2">Notes</label><input type="text" name="notes" class="w-full px-4 py-3 border rounded-lg"></div>
                    </div>
                </div>

                <div class="flex gap-4 pt-4">
                    <button type="submit" class="btn-primary"><i class="fas fa-plus mr-2"></i>Create Parcel</button>
                    <a href="/routex/admin/parcels" class="btn-secondary">Cancel</a>
                </div>
            </form>
        </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>
</html>