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

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

$id = intval($_GET['id'] ?? 0);
if (!$id) {
    header('Location: shipments.php');
    exit;
}

// Get shipment
$stmt = $pdo->prepare("SELECT * FROM shipments WHERE id = ?");
$stmt->execute([$id]);
$shipment = $stmt->fetch();

if (!$shipment) {
    header('Location: shipments.php');
    exit;
}

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $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;
        }
        
        $stmt = $pdo->prepare("UPDATE shipments SET 
            customer_name = ?, customer_phone = ?, customer_address = ?, city = ?,
            shipping_method = ?, courier_name = ?, tracking_no = ?, 
            weight = ?, shipping_cost = ?, delivery_date = ?, status = ?, note = ? 
            WHERE id = ?");
        
        $stmt->execute([
            $customer_name, $customer_phone, $customer_address, $city,
            $shipping_method, $courier_name, $tracking_no,
            $weight, $shipping_cost, $delivery_date, $status, $note,
            $id
        ]);
        
        $_SESSION['success_msg'] = 'Shipment updated successfully!';
        header('Location: shipments.php');
        exit;
    }
}

include 'header.php';
?>

<style>
.info-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}

.info-card {
    background: #f8fafc;
    border-radius: 10px;
    padding: 15px 20px;
}

.info-card h6 {
    font-weight: 600;
    color: #64748b;
    font-size: 13px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 8px;
    padding-bottom: 6px;
    border-bottom: 1px solid #e2e8f0;
}

.info-card p {
    margin-bottom: 3px;
    font-size: 14px;
}
</style>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fa-solid fa-edit me-2"></i> Edit Shipment</h2>
        <div>
            <a href="view-shipment.php?id=<?php echo $id; ?>" class="btn btn-primary">
                <i class="fa-solid fa-eye"></i> View
            </a>
            <a href="shipments.php" class="btn btn-secondary">
                <i class="fa-solid fa-arrow-left"></i> Back
            </a>
        </div>
    </div>
    
    <!-- Current Info -->
    <div class="info-grid">
        <div class="info-card">
            <h6><i class="fa-solid fa-box me-2"></i> Shipment Info</h6>
            <p><strong>Shipment #:</strong> <?php echo $shipment['shipment_no']; ?></p>
            <p><strong>Status:</strong> <?php echo ucfirst(str_replace('_', ' ', $shipment['status'])); ?></p>
            <p><strong>Created:</strong> <?php echo date('d M Y, h:i A', strtotime($shipment['created_at'])); ?></p>
        </div>
        <div class="info-card">
            <h6><i class="fa-solid fa-user me-2"></i> Customer</h6>
            <p><strong><?php echo $shipment['customer_name']; ?></strong></p>
            <p><?php echo $shipment['customer_phone']; ?></p>
            <p><?php echo substr($shipment['customer_address'], 0, 50) . '...'; ?></p>
        </div>
    </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">Customer Name *</label>
                        <input type="text" name="customer_name" class="form-control" value="<?php echo htmlspecialchars($shipment['customer_name']); ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Customer Phone *</label>
                        <input type="text" name="customer_phone" class="form-control" value="<?php echo htmlspecialchars($shipment['customer_phone']); ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Customer Address *</label>
                        <textarea name="customer_address" class="form-control" rows="2" required><?php echo htmlspecialchars($shipment['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 htmlspecialchars($shipment['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" <?php echo $shipment['shipping_method'] == 'courier' ? 'selected' : ''; ?>>Courier</option>
                            <option value="self_delivery" <?php echo $shipment['shipping_method'] == 'self_delivery' ? 'selected' : ''; ?>>Self Delivery</option>
                            <option value="postal" <?php echo $shipment['shipping_method'] == 'postal' ? 'selected' : ''; ?>>Postal</option>
                            <option value="other" <?php echo $shipment['shipping_method'] == 'other' ? 'selected' : ''; ?>>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'] == $shipment['courier_name'] ? 'selected' : ''; ?>>
                                <?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" value="<?php echo htmlspecialchars($shipment['tracking_no']); ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Weight (kg)</label>
                        <input type="number" name="weight" class="form-control" step="0.01" value="<?php echo $shipment['weight']; ?>">
                    </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="<?php echo $shipment['shipping_cost']; ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Expected Delivery Date</label>
                        <input type="date" name="delivery_date" class="form-control" value="<?php echo $shipment['delivery_date']; ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-control">
                            <option value="pending" <?php echo $shipment['status'] == 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="processing" <?php echo $shipment['status'] == 'processing' ? 'selected' : ''; ?>>Processing</option>
                            <option value="picked" <?php echo $shipment['status'] == 'picked' ? 'selected' : ''; ?>>Picked</option>
                            <option value="in_transit" <?php echo $shipment['status'] == 'in_transit' ? 'selected' : ''; ?>>In Transit</option>
                            <option value="out_for_delivery" <?php echo $shipment['status'] == 'out_for_delivery' ? 'selected' : ''; ?>>Out for Delivery</option>
                            <option value="delivered" <?php echo $shipment['status'] == 'delivered' ? 'selected' : ''; ?>>Delivered</option>
                            <option value="returned" <?php echo $shipment['status'] == 'returned' ? 'selected' : ''; ?>>Returned</option>
                            <option value="cancelled" <?php echo $shipment['status'] == 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Note</label>
                        <textarea name="note" class="form-control" rows="2"><?php echo htmlspecialchars($shipment['note']); ?></textarea>
                    </div>
                </div>
            </div>
            
            <div class="mt-3">
                <button type="submit" class="btn btn-primary">
                    <i class="fa-solid fa-save"></i> Update Shipment
                </button>
                <a href="view-shipment.php?id=<?php echo $id; ?>" class="btn btn-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>

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