<?php
// admin/delivery-reports.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

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

// Sync delivered orders to delivery reports
if (isset($_GET['sync'])) {
    // Get delivered orders that are not yet in delivery reports
    $stmt = $pdo->query("SELECT o.id, o.invoice_no, o.name, o.phone, o.address, o.city, o.total, o.created_at
                         FROM orders o 
                         LEFT JOIN delivery_reports dr ON o.id = dr.order_id 
                         WHERE dr.id IS NULL AND o.order_status = 'delivered'
                         ORDER BY o.created_at DESC");
    $delivered_orders = $stmt->fetchAll();
    
    $synced_count = 0;
    foreach ($delivered_orders as $order) {
        $report_no = 'DLV-' . date('Ymd') . '-' . rand(1000, 9999);
        
        $stmt = $pdo->prepare("INSERT INTO delivery_reports 
            (report_no, order_id, invoice_no, customer_name, customer_phone, customer_address, area,
             delivery_status, cod_amount, delivery_date, created_by) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $report_no,
            $order['id'],
            $order['invoice_no'],
            $order['name'],
            $order['phone'],
            $order['address'],
            $order['city'],
            'delivered',
            $order['total'],
            date('Y-m-d', strtotime($order['created_at'])),
            $_SESSION['admin_id']
        ]);
        $synced_count++;
    }
    
    $_SESSION['success_msg'] = $synced_count . ' delivered orders synced to delivery reports!';
    header('Location: delivery-reports.php');
    exit;
}

// Get delivery reports with order info
$stmt = $pdo->query("SELECT dr.*, o.invoice_no as order_invoice,
                     da.name as agent_name
                     FROM delivery_reports dr
                     LEFT JOIN orders o ON dr.order_id = o.id
                     LEFT JOIN delivery_agents da ON dr.delivery_agent = da.name
                     ORDER BY dr.created_at DESC");
$deliveries = $stmt->fetchAll();

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

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

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

$stmt = $pdo->query("SELECT COALESCE(SUM(cod_amount), 0) as total FROM delivery_reports WHERE delivery_status = 'delivered'");
$collected = $stmt->fetch()['total'];

// Count pending delivered orders that are not synced
$stmt = $pdo->query("SELECT COUNT(*) as total 
                     FROM orders o 
                     LEFT JOIN delivery_reports dr ON o.id = dr.order_id 
                     WHERE dr.id IS NULL AND o.order_status = 'delivered'");
$pending_sync = $stmt->fetch()['total'];

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

include 'header.php';
?>

<style>
.delivery-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 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;
}

.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.assigned { background: #93c5fd; color: #1e40af; }
.status-badge.picked { background: #86efac; color: #166534; }
.status-badge.in_transit { 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; }

.delivery-card {
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

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

.sync-btn {
    background: #047dc3;
    color: #fff;
    border: none;
    padding: 8px 20px;
    border-radius: 8px;
    transition: all 0.3s ease;
}

.sync-btn:hover {
    background: #0369a1;
    color: #fff;
}

.sync-btn i {
    margin-right: 8px;
}

.action-btns {
    display: flex;
    gap: 4px;
    flex-wrap: wrap;
}

.table td {
    vertical-align: middle;
}
</style>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fa-solid fa-clipboard-list me-2"></i> Delivery Reports</h2>
        <div>
            <?php if ($pending_sync > 0): ?>
            <a href="?sync=1" class="sync-btn">
                <i class="fa-solid fa-sync"></i> Sync Delivered Orders (<?php echo $pending_sync; ?>)
            </a>
            <?php endif; ?>
            <a href="add-delivery-report.php" class="btn btn-primary ms-2">
                <i class="fa-solid fa-plus"></i> Add Delivery Report
            </a>
        </div>
    </div>
    
    <!-- Stats -->
    <div class="delivery-stats">
        <div class="stat-box">
            <div class="stat-icon text-primary"><i class="fa-solid fa-clipboard-list"></i></div>
            <div class="stat-number text-primary"><?php echo $total; ?></div>
            <div class="stat-label">Total Deliveries</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 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-dollar-sign"></i></div>
            <div class="stat-number text-info"><?php echo number_format($collected); ?> TK</div>
            <div class="stat-label">Collected Amount</div>
        </div>
    </div>
    
    <!-- Pending Sync Alert -->
    <?php if ($pending_sync > 0): ?>
    <div class="alert alert-info alert-dismissible fade show">
        <i class="fa-solid fa-info-circle me-2"></i>
        <strong><?php echo $pending_sync; ?></strong> delivered order(s) are waiting to be synced to delivery reports.
        <a href="?sync=1" class="alert-link">Sync now</a>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>
    
    <?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 $success_msg; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>
    
    <!-- Delivery Reports Table -->
    <div class="delivery-card">
        <div class="d-flex justify-content-between align-items-center">
            <h5 class="card-title">Delivery Reports (<?php echo $total; ?>)</h5>
            <div>
                <button onclick="window.print()" class="btn btn-secondary btn-sm">
                    <i class="fa-solid fa-print"></i> Print
                </button>
            </div>
        </div>
        
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Report No</th>
                        <th>Order</th>
                        <th>Customer</th>
                        <th>Agent</th>
                        <th>Status</th>
                        <th>COD</th>
                        <th>Collected</th>
                        <th>Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($deliveries)): ?>
                    <tr>
                        <td colspan="9" class="text-center py-4">
                            <i class="fa-regular fa-clipboard fa-2x text-muted d-block mb-2"></i>
                            No delivery reports found
                            <?php if ($pending_sync > 0): ?>
                            <br><a href="?sync=1" class="btn btn-primary btn-sm mt-2">Sync delivered orders</a>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($deliveries as $delivery): ?>
                    <tr id="deliveryRow_<?php echo $delivery['id']; ?>">
                        <td><code><?php echo $delivery['report_no']; ?></code></td>
                        <td>
                            <?php if ($delivery['order_invoice']): ?>
                            <a href="order-details.php?id=<?php echo $delivery['order_id']; ?>">
                                <?php echo $delivery['order_invoice']; ?>
                            </a>
                            <?php else: ?>
                            <span class="text-muted">N/A</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <strong><?php echo htmlspecialchars($delivery['customer_name']); ?></strong>
                            <br><small><?php echo htmlspecialchars($delivery['customer_phone']); ?></small>
                        </td>
                        <td><?php echo htmlspecialchars($delivery['agent_name'] ?? '-'); ?></td>
                        <td>
                            <span class="status-badge <?php echo $delivery['delivery_status']; ?>">
                                <?php echo ucfirst(str_replace('_', ' ', $delivery['delivery_status'])); ?>
                            </span>
                        </td>
                        <td><?php echo number_format($delivery['cod_amount']); ?> TK</td>
                        <td class="text-success">
                            <?php echo number_format($delivery['collected_amount']); ?> TK
                        </td>
                        <td><?php echo date('d M Y', strtotime($delivery['delivery_date'])); ?></td>
                        <td>
                            <div class="action-btns">
                                <a href="view-delivery-report.php?id=<?php echo $delivery['id']; ?>" class="btn btn-sm btn-primary">
                                    <i class="fa-solid fa-eye"></i>
                                </a>
                                
                                <!-- 
                                <a href="edit-delivery-report.php?id=<?php echo $delivery['id']; ?>" class="btn btn-sm btn-warning">
                                    <i class="fa-solid fa-edit"></i>
                                </a>
                                -->

                                <button onclick="deleteDelivery(<?php echo $delivery['id']; ?>)" 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>

<script>
function deleteDelivery(id) {
    if (!confirm('Delete this delivery report?')) return;
    
    var formData = new FormData();
    formData.append('delete_id', id);
    
    fetch('delete-delivery-report.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            var row = document.getElementById('deliveryRow_' + id);
            if (row) {
                row.style.transition = 'all 0.5s ease';
                row.style.opacity = '0';
                setTimeout(function() { row.remove(); }, 500);
            }
            showToast('Delivery report deleted!', 'success');
        }
    })
    .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'; ?>