<?php
// admin/view-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 details
$stmt = $pdo->prepare("SELECT s.*, o.invoice_no as order_invoice 
                       FROM shipments s 
                       LEFT JOIN orders o ON s.order_id = o.id 
                       WHERE s.id = ?");
$stmt->execute([$id]);
$shipment = $stmt->fetch();

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

// Get tracking history
$stmt = $pdo->prepare("SELECT * FROM shipment_tracking WHERE shipment_id = ? ORDER BY created_at DESC");
$stmt->execute([$id]);
$tracking_history = $stmt->fetchAll();

$success_msg = $_SESSION['success_msg'] ?? '';
unset($_SESSION['success_msg']);

include 'header.php';
?>

<style>
.status-badge {
    padding: 6px 16px;
    border-radius: 20px;
    font-size: 14px;
    font-weight: 500;
    display: inline-block;
}

.status-badge.pending { background: #fcd34d; color: #92400e; }
.status-badge.processing { background: #93c5fd; color: #1e40af; }
.status-badge.picked { background: #86efac; color: #166534; }
.status-badge.in_transit { background: #f59e0b; color: #92400e; }
.status-badge.out_for_delivery { background: #f59e0b; color: #92400e; }
.status-badge.delivered { background: #22c55e; color: #fff; }
.status-badge.returned { background: #fca5a5; color: #991b1b; }
.status-badge.cancelled { background: #e2e8f0; color: #475569; }

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

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

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

.info-card p {
    margin-bottom: 4px;
    font-size: 14px;
}

.info-card .label {
    color: #64748b;
    font-weight: 500;
}

.timeline {
    position: relative;
    padding-left: 30px;
}

.timeline::before {
    content: '';
    position: absolute;
    left: 8px;
    top: 0;
    bottom: 0;
    width: 2px;
    background: #e2e8f0;
}

.timeline-item {
    position: relative;
    margin-bottom: 20px;
    padding-left: 20px;
}

.timeline-item::before {
    content: '';
    position: absolute;
    left: -22px;
    top: 5px;
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background: #e2e8f0;
    border: 2px solid #fff;
    box-shadow: 0 0 0 2px #e2e8f0;
}

.timeline-item.active::before {
    background: #047dc3;
    box-shadow: 0 0 0 2px #047dc3;
}

.timeline-item .time {
    font-size: 12px;
    color: #94a3b8;
}

.timeline-item .status-text {
    font-weight: 600;
    font-size: 14px;
}

.timeline-item .desc {
    font-size: 13px;
    color: #64748b;
}

.action-buttons {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    margin-top: 20px;
}
</style>

<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> Shipment Details</h2>
        <div>
            <a href="shipments.php" class="btn btn-secondary">
                <i class="fa-solid fa-arrow-left"></i> Back
            </a>
            <a href="edit-shipment.php?id=<?php echo $shipment['id']; ?>" class="btn btn-warning">
                <i class="fa-solid fa-edit"></i> Edit
            </a>
            <button onclick="window.print()" class="btn btn-primary">
                <i class="fa-solid fa-print"></i> Print
            </button>
        </div>
    </div>
    
    <?php if ($success_msg): ?>
    <div class="alert alert-success"><?php echo $success_msg; ?></div>
    <?php endif; ?>
    
    <!-- Status -->
    <div class="mb-4">
        <span class="status-badge <?php echo $shipment['status']; ?>">
            <?php echo ucfirst(str_replace('_', ' ', $shipment['status'])); ?>
        </span>
        <span class="ms-3 text-muted">Shipment #<?php echo $shipment['shipment_no']; ?></span>
    </div>
    
    <!-- Info Grid -->
    <div class="info-grid">
        <div class="info-card">
            <h6><i class="fa-solid fa-user me-2"></i> Customer Information</h6>
            <p><strong><?php echo $shipment['customer_name']; ?></strong></p>
            <p><span class="label">Phone:</span> <?php echo $shipment['customer_phone']; ?></p>
            <p><span class="label">Address:</span> <?php echo $shipment['customer_address']; ?></p>
            <?php if ($shipment['city']): ?>
            <p><span class="label">City:</span> <?php echo $shipment['city']; ?></p>
            <?php endif; ?>
        </div>
        
        <div class="info-card">
            <h6><i class="fa-solid fa-box me-2"></i> Order Information</h6>
            <?php if ($shipment['order_invoice']): ?>
            <p><span class="label">Order:</span> 
                <a href="order-details.php?id=<?php echo $shipment['order_id']; ?>">
                    <?php echo $shipment['order_invoice']; ?>
                </a>
            </p>
            <?php else: ?>
            <p><span class="label">Order:</span> N/A</p>
            <?php endif; ?>
            <p><span class="label">Created:</span> <?php echo date('d M Y, h:i A', strtotime($shipment['created_at'])); ?></p>
            <?php if ($shipment['delivery_date']): ?>
            <p><span class="label">Expected Delivery:</span> <?php echo date('d M Y', strtotime($shipment['delivery_date'])); ?></p>
            <?php endif; ?>
        </div>
        
        <div class="info-card">
            <h6><i class="fa-solid fa-truck-fast me-2"></i> Shipping Details</h6>
            <p><span class="label">Method:</span> <?php echo ucfirst(str_replace('_', ' ', $shipment['shipping_method'])); ?></p>
            <?php if ($shipment['courier_name']): ?>
            <p><span class="label">Courier:</span> <?php echo $shipment['courier_name']; ?></p>
            <?php endif; ?>
            <?php if ($shipment['tracking_no']): ?>
            <p><span class="label">Tracking:</span> <code><?php echo $shipment['tracking_no']; ?></code></p>
            <?php endif; ?>
            <p><span class="label">Weight:</span> <?php echo $shipment['weight']; ?> kg</p>
            <p><span class="label">Shipping Cost:</span> <?php echo number_format($shipment['shipping_cost']); ?> TK</p>
        </div>
    </div>
    
    <?php if ($shipment['note']): ?>
    <div class="alert alert-info mb-3">
        <strong>Note:</strong> <?php echo $shipment['note']; ?>
    </div>
    <?php endif; ?>
    
    <!-- Tracking Timeline -->
    <div class="admin-card">
        <h5 class="card-title"><i class="fa-solid fa-clock-rotate-left me-2"></i> Tracking History</h5>
        
        <?php if (empty($tracking_history)): ?>
        <p class="text-muted">No tracking history available</p>
        <?php else: ?>
        <div class="timeline">
            <?php foreach ($tracking_history as $track): ?>
            <div class="timeline-item active">
                <div class="time"><?php echo date('d M Y, h:i A', strtotime($track['created_at'])); ?></div>
                <div class="status-text"><?php echo ucfirst(str_replace('_', ' ', $track['status'])); ?></div>
                <?php if ($track['location']): ?>
                <div class="desc"><i class="fa-solid fa-location-dot me-1"></i> <?php echo $track['location']; ?></div>
                <?php endif; ?>
                <?php if ($track['description']): ?>
                <div class="desc"><?php echo $track['description']; ?></div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
        
        <!-- Add Tracking -->
        <div class="mt-3">
            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#trackingModal">
                <i class="fa-solid fa-plus"></i> Add Tracking Update
            </button>
        </div>
    </div>
    
    <!-- Action Buttons -->
    <div class="action-buttons">
        <a href="edit-shipment.php?id=<?php echo $shipment['id']; ?>" class="btn btn-warning">
            <i class="fa-solid fa-edit"></i> Edit Shipment
        </a>
        <a href="javascript:void(0)" onclick="updateStatus(<?php echo $shipment['id']; ?>)" class="btn btn-info">
            <i class="fa-solid fa-arrow-right"></i> Update Status
        </a>
        <a href="javascript:void(0)" onclick="deleteShipment(<?php echo $shipment['id']; ?>)" class="btn btn-danger">
            <i class="fa-solid fa-trash"></i> Delete
        </a>
    </div>
</div>

<!-- Add Tracking Modal -->
<div class="modal fade" id="trackingModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Tracking Update</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="add-tracking.php">
                <input type="hidden" name="shipment_id" value="<?php echo $shipment['id']; ?>">
                <div class="modal-body">
                    <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">Location</label>
                        <input type="text" name="location" class="form-control" placeholder="Current location">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea name="description" class="form-control" rows="2" placeholder="Update description"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add Update</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function updateStatus(id) {
    document.getElementById('status_shipment_id').value = id;
    var modal = new bootstrap.Modal(document.getElementById('statusModal'));
    modal.show();
}

function deleteShipment(id) {
    if (confirm('Are you sure you want to delete this shipment?')) {
        var formData = new FormData();
        formData.append('delete_id', id);
        
        fetch('delete-shipment.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                window.location.href = 'shipments.php';
            } else {
                showToast(data.message || 'Failed to delete', 'error');
            }
        })
        .catch(error => {
            showToast('Something went wrong', 'error');
        });
    }
}

function showToast(message, type) {
    var colors = { success: '#22c55e', error: '#ef4444', warning: '#f59e0b', info: '#3b82f6' };
    var toast = document.createElement('div');
    toast.style.cssText = `
        position: fixed; top: 20px; right: 20px; padding: 12px 24px;
        background: ${colors[type] || colors.info}; color: #fff;
        border-radius: 8px; z-index: 9999;
        animation: slideIn 0.3s ease; max-width: 400px; font-size: 14px;
        box-shadow: 0 5px 20px rgba(0,0,0,0.15);
    `;
    toast.textContent = message;
    document.body.appendChild(toast);
    setTimeout(function() { toast.remove(); }, 3000);
}
</script>

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