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

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

// Handle Add Courier
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_courier'])) {
    $name = sanitize($_POST['name'] ?? '');
    $code = sanitize($_POST['code'] ?? '');
    $phone = sanitize($_POST['phone'] ?? '');
    $email = sanitize($_POST['email'] ?? '');
    $website = sanitize($_POST['website'] ?? '');
    $tracking_url = sanitize($_POST['tracking_url'] ?? '');
    $status = isset($_POST['status']) ? 1 : 0;
    
    if (empty($name) || empty($code)) {
        $error_msg = 'Name and code are required';
    } else {
        try {
            $stmt = $pdo->prepare("INSERT INTO couriers (name, code, phone, email, website, tracking_url, status) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$name, $code, $phone, $email, $website, $tracking_url, $status]);
            $_SESSION['success_msg'] = 'Courier "' . $name . '" added successfully!';
            header('Location: couriers.php');
            exit;
        } catch (Exception $e) {
            $error_msg = 'Error: ' . $e->getMessage();
        }
    }
}

// Handle Edit Courier
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_courier'])) {
    $id = intval($_POST['courier_id'] ?? 0);
    $name = sanitize($_POST['name'] ?? '');
    $code = sanitize($_POST['code'] ?? '');
    $phone = sanitize($_POST['phone'] ?? '');
    $email = sanitize($_POST['email'] ?? '');
    $website = sanitize($_POST['website'] ?? '');
    $tracking_url = sanitize($_POST['tracking_url'] ?? '');
    $status = isset($_POST['status']) ? 1 : 0;
    
    if ($id > 0 && !empty($name) && !empty($code)) {
        try {
            $stmt = $pdo->prepare("UPDATE couriers SET 
                name = ?, code = ?, phone = ?, email = ?, website = ?, 
                tracking_url = ?, status = ? 
                WHERE id = ?");
            $stmt->execute([$name, $code, $phone, $email, $website, $tracking_url, $status, $id]);
            $_SESSION['success_msg'] = 'Courier updated successfully!';
            header('Location: couriers.php');
            exit;
        } catch (Exception $e) {
            $error_msg = 'Error: ' . $e->getMessage();
        }
    }
}

// Handle Delete via AJAX
if (isset($_POST['delete_id'])) {
    $delete_id = intval($_POST['delete_id']);
    try {
        $stmt = $pdo->prepare("DELETE FROM couriers WHERE id = ?");
        $stmt->execute([$delete_id]);
        echo json_encode(['success' => true, 'message' => 'Courier deleted']);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

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

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

include 'header.php';
?>

<style>
.courier-card {
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.courier-card .card-title {
    font-weight: 600;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f1f5f9;
}

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

.status-badge.active {
    background: #86efac;
    color: #166534;
}

.status-badge.inactive {
    background: #fca5a5;
    color: #991b1b;
}

.alert-container {
    margin-bottom: 20px;
}

.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-people-carry-box me-2"></i> Couriers</h2>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#courierModal">
            <i class="fa-solid fa-plus"></i> Add Courier
        </button>
    </div>
    
    <!-- Alert Container -->
    <div id="alertContainer" class="alert-container"></div>
    
    <?php if ($success_msg): ?>
    <div class="alert alert-success alert-dismissible fade show">
        <i class="fa-solid fa-check-circle me-2"></i> <?php echo htmlspecialchars($success_msg); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>
    
    <?php if ($error_msg): ?>
    <div class="alert alert-danger alert-dismissible fade show">
        <i class="fa-solid fa-exclamation-circle me-2"></i> <?php echo htmlspecialchars($error_msg); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>
    
    <!-- Courier List -->
    <div class="courier-card">
        <h5 class="card-title">All Couriers (<?php echo count($couriers); ?>)</h5>
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Code</th>
                        <th>Phone</th>
                        <th>Email</th>
                        <th>Website</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="couriersTableBody">
                    <?php if (empty($couriers)): ?>
                    <tr>
                        <td colspan="8" class="text-center py-4">
                            <i class="fa-regular fa-building fa-2x text-muted d-block mb-2"></i>
                            No couriers found. Click "Add Courier" to create one.
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($couriers as $courier): ?>
                    <tr id="courierRow_<?php echo $courier['id']; ?>">
                        <td><?php echo $courier['id']; ?></td>
                        <td><strong><?php echo htmlspecialchars($courier['name']); ?></strong></td>
                        <td><code><?php echo htmlspecialchars($courier['code']); ?></code></td>
                        <td><?php echo htmlspecialchars($courier['phone'] ?? '-'); ?></td>
                        <td><?php echo htmlspecialchars($courier['email'] ?? '-'); ?></td>
                        <td>
                            <?php if ($courier['website']): ?>
                            <a href="<?php echo $courier['website']; ?>" target="_blank">
                                <?php echo substr($courier['website'], 0, 20) . (strlen($courier['website']) > 20 ? '...' : ''); ?>
                            </a>
                            <?php else: ?>
                            -
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="status-badge <?php echo $courier['status'] ? 'active' : 'inactive'; ?>">
                                <?php echo $courier['status'] ? 'Active' : 'Inactive'; ?>
                            </span>
                        </td>
                        <td>
                            <div class="action-btns">
                                <button onclick="editCourier(<?php echo $courier['id']; ?>)" class="btn btn-sm btn-warning">
                                    <i class="fa-solid fa-edit"></i>
                                </button>
                                <button onclick="deleteCourier(<?php echo $courier['id']; ?>, '<?php echo addslashes($courier['name']); ?>')" class="btn btn-sm btn-danger">
                                    <i class="fa-solid fa-trash"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add Courier Modal -->
<div class="modal fade" id="courierModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa-solid fa-plus-circle me-2"></i> Add Courier</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" id="courierForm">
                <input type="hidden" name="add_courier" value="1">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Courier Name <span class="text-danger">*</span></label>
                                <input type="text" name="name" class="form-control" required placeholder="Enter courier name">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Code <span class="text-danger">*</span></label>
                                <input type="text" name="code" class="form-control" required placeholder="Unique code (e.g., SUNDARBAN)">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Phone</label>
                                <input type="text" name="phone" class="form-control" placeholder="Phone number">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Email</label>
                                <input type="email" name="email" class="form-control" placeholder="Email address">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Website</label>
                                <input type="text" name="website" class="form-control" placeholder="https://example.com">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Tracking URL</label>
                                <input type="text" name="tracking_url" class="form-control" placeholder="https://example.com/track">
                            </div>
                            <div class="mb-3">
                                <div class="form-check">
                                    <input type="checkbox" name="status" class="form-check-input" id="courierStatus" checked>
                                    <label class="form-check-label" for="courierStatus">Active</label>
                                </div>
                            </div>
                        </div>
                    </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">
                        <i class="fa-solid fa-save"></i> Save Courier
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Courier Modal -->
<div class="modal fade" id="editCourierModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa-solid fa-edit me-2"></i> Edit Courier</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" id="editCourierForm">
                <input type="hidden" name="edit_courier" value="1">
                <input type="hidden" name="courier_id" id="edit_courier_id">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Courier Name <span class="text-danger">*</span></label>
                                <input type="text" name="name" id="edit_name" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Code <span class="text-danger">*</span></label>
                                <input type="text" name="code" id="edit_code" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Phone</label>
                                <input type="text" name="phone" id="edit_phone" class="form-control">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Email</label>
                                <input type="email" name="email" id="edit_email" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Website</label>
                                <input type="text" name="website" id="edit_website" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Tracking URL</label>
                                <input type="text" name="tracking_url" id="edit_tracking_url" class="form-control">
                            </div>
                            <div class="mb-3">
                                <div class="form-check">
                                    <input type="checkbox" name="status" id="edit_status" class="form-check-input">
                                    <label class="form-check-label" for="edit_status">Active</label>
                                </div>
                            </div>
                        </div>
                    </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">
                        <i class="fa-solid fa-save"></i> Update Courier
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// ========================================
// EDIT COURIER
// ========================================
function editCourier(id) {
    // Fetch courier data
    fetch('get-courier.php?id=' + id)
        .then(response => response.json())
        .then(data => {
            if (data && data.id) {
                document.getElementById('edit_courier_id').value = data.id;
                document.getElementById('edit_name').value = data.name;
                document.getElementById('edit_code').value = data.code;
                document.getElementById('edit_phone').value = data.phone || '';
                document.getElementById('edit_email').value = data.email || '';
                document.getElementById('edit_website').value = data.website || '';
                document.getElementById('edit_tracking_url').value = data.tracking_url || '';
                document.getElementById('edit_status').checked = data.status == 1;
                
                var modal = new bootstrap.Modal(document.getElementById('editCourierModal'));
                modal.show();
            } else {
                showAlert('danger', 'Failed to load courier data');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('danger', 'Failed to load courier data');
        });
}

// ========================================
// DELETE COURIER
// ========================================
function deleteCourier(id, name) {
    if (!confirm('Are you sure you want to delete courier "' + name + '"?')) return;
    
    var formData = new FormData();
    formData.append('delete_id', id);
    
    fetch('couriers.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            var row = document.getElementById('courierRow_' + id);
            if (row) {
                row.style.transition = 'all 0.5s ease';
                row.style.opacity = '0';
                setTimeout(function() {
                    row.remove();
                    // Update count
                    var tbody = document.getElementById('couriersTableBody');
                    var rows = tbody.querySelectorAll('tr');
                    var count = rows.length - 1;
                    if (count === 0) {
                        tbody.innerHTML = `
                            <tr><td colspan="8" class="text-center py-4">
                                <i class="fa-regular fa-building fa-2x text-muted d-block mb-2"></i>
                                No couriers found. Click "Add Courier" to create one.
                            </td></tr>
                        `;
                    }
                    // Update card title count
                    document.querySelector('.card-title').textContent = 'All Couriers (' + count + ')';
                }, 500);
            }
            showAlert('success', 'Courier deleted successfully!');
        } else {
            showAlert('danger', data.message || 'Failed to delete courier');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('danger', 'Something went wrong');
    });
}

// ========================================
// SHOW ALERT
// ========================================
function showAlert(type, message) {
    var alertContainer = document.getElementById('alertContainer');
    var alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    var icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';
    
    alertContainer.innerHTML = `
        <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
            <i class="fa-solid ${icon} me-2"></i> ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    setTimeout(function() {
        var alert = alertContainer.querySelector('.alert');
        if (alert) {
            alert.style.transition = 'opacity 0.5s ease';
            alert.style.opacity = '0';
            setTimeout(function() { alert.remove(); }, 500);
        }
    }, 5000);
}

// ========================================
// AUTO HIDE ALERTS
// ========================================
document.addEventListener('DOMContentLoaded', function() {
    var alerts = document.querySelectorAll('.alert');
    alerts.forEach(function(alert) {
        setTimeout(function() {
            if (alert) {
                alert.style.transition = 'opacity 0.5s ease';
                alert.style.opacity = '0';
                setTimeout(function() { alert.remove(); }, 500);
            }
        }, 5000);
    });
});
</script>

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