<?php
// admin/add-shipment.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

if (!isAdmin()) {
    header('Location: login.php');
    exit;
}

// Get order_id from URL
$order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
$prefilled_data = [];

if ($order_id > 0) {
    $stmt = $pdo->prepare("SELECT id, invoice_no, name, phone, address, city FROM orders WHERE id = ?");
    $stmt->execute([$order_id]);
    $order = $stmt->fetch();
    if ($order) {
        $prefilled_data = [
            'order_id' => $order['id'],
            'invoice_no' => $order['invoice_no'],
            'customer_name' => $order['name'],
            'customer_phone' => $order['phone'],
            'customer_address' => $order['address'],
            'city' => $order['city']
        ];
    }
}

// Get orders without shipment
$stmt = $pdo->query("SELECT o.id, o.invoice_no, o.name, o.phone, o.address 
                     FROM orders o 
                     LEFT JOIN shipments s ON o.id = s.order_id 
                     WHERE s.id IS NULL AND o.order_status != 'cancelled'
                     ORDER BY o.created_at DESC");
$orders = $stmt->fetchAll();

// Get couriers
$couriers = $pdo->query("SELECT * FROM couriers WHERE status = 1 ORDER BY name")->fetchAll();

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $order_id = isset($_POST['order_id']) && !empty($_POST['order_id']) ? intval($_POST['order_id']) : null;
    $customer_name = sanitize($_POST['customer_name'] ?? '');
    $customer_phone = sanitize($_POST['customer_phone'] ?? '');
    $customer_address = sanitize($_POST['customer_address'] ?? '');
    $city = sanitize($_POST['city'] ?? '');
    $shipping_method = sanitize($_POST['shipping_method'] ?? 'courier');
    $courier_id = isset($_POST['courier_id']) && !empty($_POST['courier_id']) ? intval($_POST['courier_id']) : null;
    $tracking_no = sanitize($_POST['tracking_no'] ?? '');
    $weight = floatval($_POST['weight'] ?? 0);
    $shipping_cost = floatval($_POST['shipping_cost'] ?? 0);
    $delivery_date = $_POST['delivery_date'] ?? null;
    $status = sanitize($_POST['status'] ?? 'pending');
    $note = sanitize($_POST['note'] ?? '');
    
    if (empty($customer_name) || empty($customer_phone) || empty($customer_address)) {
        $error = 'Customer name, phone, and address are required';
    } else {
        // Get courier name if selected
        $courier_name = null;
        if ($courier_id) {
            $stmt = $pdo->prepare("SELECT name FROM couriers WHERE id = ?");
            $stmt->execute([$courier_id]);
            $courier = $stmt->fetch();
            $courier_name = $courier ? $courier['name'] : null;
        }
        
        $shipment_no = 'SHIP-' . date('Ymd') . '-' . rand(1000, 9999);
        
        $stmt = $pdo->prepare("INSERT INTO shipments 
            (shipment_no, order_id, customer_name, customer_phone, customer_address, city,
             shipping_method, courier_name, tracking_no, weight, shipping_cost, delivery_date, status, note, created_by) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        $stmt->execute([
            $shipment_no, $order_id, $customer_name, $customer_phone, $customer_address, $city,
            $shipping_method, $courier_name, $tracking_no, $weight, $shipping_cost, $delivery_date, $status, $note, $_SESSION['admin_id']
        ]);
        
        $shipment_id = $pdo->lastInsertId();
        
        // Add initial tracking
        $stmt = $pdo->prepare("INSERT INTO shipment_tracking 
            (shipment_id, status, description, created_by) 
            VALUES (?, ?, ?, ?)");
        $stmt->execute([$shipment_id, $status, 'Shipment created', $_SESSION['admin_id']]);
        
        $_SESSION['success_msg'] = 'Shipment created successfully!';
        header('Location: shipments.php');
        exit;
    }
}

include 'header.php';
?>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fa-solid fa-truck me-2"></i> Create Shipment</h2>
        <a href="shipments.php" class="btn btn-secondary">
            <i class="fa-solid fa-arrow-left"></i> Back to Shipments
        </a>
    </div>
    
    <?php if ($error): ?>
    <div class="alert alert-danger"><?php echo $error; ?></div>
    <?php endif; ?>
    
    <div class="admin-card">
        <form method="POST">
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">Order (Optional)</label>
                        <select name="order_id" id="orderSelect" class="form-control">
                            <option value="">Select Order</option>
                            <?php foreach ($orders as $order): ?>
                            <option value="<?php echo $order['id']; ?>" 
                                    data-name="<?php echo $order['name']; ?>"
                                    data-phone="<?php echo $order['phone']; ?>"
                                    data-address="<?php echo $order['address']; ?>"
                                    <?php echo ($prefilled_data['order_id'] ?? 0) == $order['id'] ? 'selected' : ''; ?>>
                                <?php echo $order['invoice_no']; ?> - <?php echo $order['name']; ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Customer Name *</label>
                        <input type="text" name="customer_name" id="customerName" class="form-control" 
                               value="<?php echo $prefilled_data['customer_name'] ?? ''; ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Customer Phone *</label>
                        <input type="text" name="customer_phone" id="customerPhone" class="form-control" 
                               value="<?php echo $prefilled_data['customer_phone'] ?? ''; ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Customer Address *</label>
                        <textarea name="customer_address" id="customerAddress" class="form-control" rows="2" required><?php echo $prefilled_data['customer_address'] ?? ''; ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">City</label>
                        <input type="text" name="city" class="form-control" value="<?php echo $prefilled_data['city'] ?? ''; ?>">
                    </div>
                </div>
                
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">Shipping Method</label>
                        <select name="shipping_method" class="form-control">
                            <option value="courier">Courier</option>
                            <option value="self_delivery">Self Delivery</option>
                            <option value="postal">Postal</option>
                            <option value="other">Other</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Courier</label>
                        <select name="courier_id" class="form-control">
                            <option value="">Select Courier</option>
                            <?php foreach ($couriers as $courier): ?>
                            <option value="<?php echo $courier['id']; ?>"><?php echo $courier['name']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Tracking Number</label>
                        <input type="text" name="tracking_no" class="form-control" placeholder="Enter tracking number">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Weight (kg)</label>
                        <input type="number" name="weight" class="form-control" step="0.01" value="0">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Shipping Cost</label>
                        <input type="number" name="shipping_cost" class="form-control" step="0.01" value="0">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Expected Delivery Date</label>
                        <input type="date" name="delivery_date" class="form-control">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-control">
                            <option value="pending">Pending</option>
                            <option value="processing">Processing</option>
                            <option value="picked">Picked</option>
                            <option value="in_transit">In Transit</option>
                            <option value="out_for_delivery">Out for Delivery</option>
                            <option value="delivered">Delivered</option>
                            <option value="returned">Returned</option>
                            <option value="cancelled">Cancelled</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Note</label>
                        <textarea name="note" class="form-control" rows="2"></textarea>
                    </div>
                </div>
            </div>
            
            <div class="mt-3">
                <button type="submit" class="btn btn-primary">
                    <i class="fa-solid fa-save"></i> Create Shipment
                </button>
                <a href="shipments.php" class="btn btn-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>

<script>
document.getElementById('orderSelect').addEventListener('change', function() {
    var selected = this.options[this.selectedIndex];
    if (selected.value) {
        document.getElementById('customerName').value = selected.getAttribute('data-name') || '';
        document.getElementById('customerPhone').value = selected.getAttribute('data-phone') || '';
        document.getElementById('customerAddress').value = selected.getAttribute('data-address') || '';
    }
});
</script>

<?php include 'footer.php'; ?>