<?php
// admin/shipments.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

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

// Get all shipments
$stmt = $pdo->query("SELECT s.*, o.invoice_no as order_invoice 
                     FROM shipments s 
                     LEFT JOIN orders o ON s.order_id = o.id 
                     ORDER BY s.created_at DESC");
$shipments = $stmt->fetchAll();

// Get counts
$stmt = $pdo->query("SELECT COUNT(*) as total FROM shipments");
$total = $stmt->fetch()['total'];

$stmt = $pdo->query("SELECT COUNT(*) as total FROM shipments WHERE status = 'pending'");
$pending = $stmt->fetch()['total'];

$stmt = $pdo->query("SELECT COUNT(*) as total FROM shipments WHERE status = 'delivered'");
$delivered = $stmt->fetch()['total'];

$stmt = $pdo->query("SELECT COUNT(*) as total FROM shipments WHERE status IN ('in_transit', 'out_for_delivery')");
$in_transit = $stmt->fetch()['total'];

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

include 'header.php';
?>

<style>
.shipment-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
    margin-bottom: 25px;
}

.stat-box {
    background: #fff;
    border-radius: 12px;
    padding: 18px 20px;
    text-align: center;
    box-shadow: 0 1px 3px rgba(0,0,0,0.08);
    transition: all 0.3s ease;
}

.stat-box:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.stat-box .stat-number {
    font-size: 28px;
    font-weight: 700;
}

.stat-box .stat-label {
    font-size: 13px;
    color: #64748b;
    margin-top: 2px;
}

.stat-box .stat-icon {
    font-size: 24px;
    margin-bottom: 5px;
}

.status-badge {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}

.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; }

.shipment-table td {
    vertical-align: middle;
}

.btn-sm {
    padding: 4px 10px;
    font-size: 12px;
}

.action-btns {
    display: flex;
    gap: 4px;
    flex-wrap: wrap;
}
</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> Shipments</h2>
        <a href="add-shipment.php" class="btn btn-primary">
            <i class="fa-solid fa-plus"></i> Add Shipment
        </a>
    </div>
    
    <!-- Stats -->
    <div class="shipment-stats">
        <div class="stat-box">
            <div class="stat-icon text-primary"><i class="fa-solid fa-box"></i></div>
            <div class="stat-number text-primary"><?php echo $total; ?></div>
            <div class="stat-label">Total Shipments</div>
        </div>
        <div class="stat-box">
            <div class="stat-icon text-warning"><i class="fa-solid fa-clock"></i></div>
            <div class="stat-number text-warning"><?php echo $pending; ?></div>
            <div class="stat-label">Pending</div>
        </div>
        <div class="stat-box">
            <div class="stat-icon text-info"><i class="fa-solid fa-truck"></i></div>
            <div class="stat-number text-info"><?php echo $in_transit; ?></div>
            <div class="stat-label">In Transit</div>
        </div>
        <div class="stat-box">
            <div class="stat-icon text-success"><i class="fa-solid fa-check-circle"></i></div>
            <div class="stat-number text-success"><?php echo $delivered; ?></div>
            <div class="stat-label">Delivered</div>
        </div>
    </div>
    
    <?php if ($success_msg): ?>
    <div class="alert alert-success"><?php echo $success_msg; ?></div>
    <?php endif; ?>
    
    <!-- Shipments Table -->
    <div class="admin-card">
        <div class="table-responsive">
            <table class="table table-hover shipment-table">
                <thead>
                    <tr>
                        <th>Shipment No</th>
                        <th>Customer</th>
                        <th>Order</th>
                        <th>Courier</th>
                        <th>Tracking</th>
                        <th>Status</th>
                        <th>Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($shipments)): ?>
                    <tr>
                        <td colspan="8" class="text-center py-4">
                            <i class="fa-regular fa-truck fa-2x text-muted d-block mb-2"></i>
                            No shipments found
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($shipments as $shipment): ?>
                    <tr id="shipmentRow_<?php echo $shipment['id']; ?>">
                        <td><code><?php echo $shipment['shipment_no']; ?></code></td>
                        <td>
                            <strong><?php echo $shipment['customer_name']; ?></strong><br>
                            <small><?php echo $shipment['customer_phone']; ?></small>
                        </td>
                        <td>
                            <?php if ($shipment['order_invoice']): ?>
                            <a href="order-details.php?id=<?php echo $shipment['order_id']; ?>">
                                <?php echo $shipment['order_invoice']; ?>
                            </a>
                            <?php else: ?>
                            <span class="text-muted">N/A</span>
                            <?php endif; ?>
                        </td>
                        <td><?php echo $shipment['courier_name'] ?? '-'; ?></td>
                        <td>
                            <?php if ($shipment['tracking_no']): ?>
                            <code><?php echo $shipment['tracking_no']; ?></code>
                            <?php else: ?>
                            <span class="text-muted">-</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="status-badge <?php echo $shipment['status']; ?>">
                                <?php echo ucfirst(str_replace('_', ' ', $shipment['status'])); ?>
                            </span>
                        </td>
                        <td><?php echo date('d M Y', strtotime($shipment['created_at'])); ?></td>
                       <td>
    <div class="action-btns">
        <a href="view-shipment.php?id=<?php echo $shipment['id']; ?>" class="btn btn-sm btn-primary" title="View">
            <i class="fa-solid fa-eye"></i>
        </a>
        <a href="edit-shipment.php?id=<?php echo $shipment['id']; ?>" class="btn btn-sm btn-warning" title="Edit">
            <i class="fa-solid fa-edit"></i>
        </a>
        <a href="javascript:void(0)" onclick="updateStatus(<?php echo $shipment['id']; ?>)" class="btn btn-sm btn-info" title="Update Status">
            <i class="fa-solid fa-arrow-right"></i>
        </a>
        <a href="javascript:void(0)" onclick="deleteShipment(<?php echo $shipment['id']; ?>)" class="btn btn-sm btn-danger" title="Delete">
            <i class="fa-solid fa-trash"></i>
        </a>
    </div>
</td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Update Status Modal -->
<div class="modal fade" id="statusModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Update Shipment Status</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="update-shipment-status.php">
                <input type="hidden" name="shipment_id" id="status_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">Update Status</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) {
                var row = document.getElementById('shipmentRow_' + id);
                if (row) {
                    row.style.transition = 'all 0.5s ease';
                    row.style.opacity = '0';
                    setTimeout(function() { row.remove(); }, 500);
                }
                showToast('Shipment deleted successfully!', 'success');
            } 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'; ?>