<?php
/**
 * ADMIN ORDERS MANAGEMENT PAGE - COMPLETE
 * File: admin/orders.php
 */

require_once '../app/Core/init.php';
require_once '../app/Models/OrderRating.php';

Auth::requireAdmin();

$order = new Order();
$db = Database::getInstance();

// Get filters
$status_filter = $_GET['status'] ?? 'all';
$payment_status = $_GET['payment'] ?? 'all';
$search = $_GET['search'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 20;

// ============================================================
// DASHBOARD FILTER SUPPORT
// ============================================================
$dashboard_filter = $_GET['filter'] ?? '';
$today = date('Y-m-d');

// Build WHERE clause
$where_conditions = [];
$params = [];

// Apply dashboard filter first
if (!empty($dashboard_filter)) {
    switch ($dashboard_filter) {
        case 'all':
            // Show all orders
            break;
        case 'ongoing':
            // Orders active right now
            $where_conditions[] = "o.start_date <= ?";
            $where_conditions[] = "o.end_date >= ?";
            $where_conditions[] = "o.status NOT IN ('cancelled', 'completed')";
            $params[] = $today;
            $params[] = $today;
            break;
        case 'future':
            // Orders starting in the future
            $where_conditions[] = "o.start_date > ?";
            $where_conditions[] = "o.status NOT IN ('cancelled', 'completed')";
            $params[] = $today;
            break;
        case 'completed':
            $where_conditions[] = "o.status = 'completed'";
            break;
        case 'cancelled':
            $where_conditions[] = "o.status = 'cancelled'";
            break;
    }
}

if ($status_filter !== 'all') {
    $where_conditions[] = "o.status = ?";
    $params[] = $status_filter;
}

if ($payment_status !== 'all') {
    $where_conditions[] = "o.payment_status = ?";
    $params[] = $payment_status;
}

if (!empty($search)) {
    $where_conditions[] = "(o.order_number LIKE ? OR i.title LIKE ? OR CONCAT(c.first_name, ' ', c.last_name) LIKE ? OR v.business_name LIKE ?)";
    $search_term = "%{$search}%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get total count
$count_sql = "SELECT COUNT(*) as total FROM orders o 
              JOIN items i ON o.item_id = i.id
              JOIN customers c ON o.customer_id = c.id
              JOIN vendors v ON o.vendor_id = v.id
              {$where_clause}";
$total_count = $db->fetch($count_sql, $params);
$total_orders = $total_count['total'];
$total_pages = ceil($total_orders / $per_page);

// Get orders
$offset = ($page - 1) * $per_page;
$orders_sql = "SELECT o.*, 
               i.title as item_title, i.main_image as item_image,
               CONCAT(c.first_name, ' ', c.last_name) as customer_name,
               v.business_name as vendor_name
               FROM orders o
               JOIN items i ON o.item_id = i.id
               JOIN customers c ON o.customer_id = c.id
               JOIN vendors v ON o.vendor_id = v.id
               {$where_clause}
               ORDER BY o.created_at DESC
               LIMIT ? OFFSET ?";
$params[] = $per_page;
$params[] = $offset;
$orders = $db->fetchAll($orders_sql, $params);

// Get statistics
$stats_sql = "SELECT 
              COUNT(*) as total,
              SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
              SUM(CASE WHEN status = 'confirmed' THEN 1 ELSE 0 END) as confirmed,
              SUM(CASE WHEN status = 'ongoing' THEN 1 ELSE 0 END) as ongoing,
              SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed,
              SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled,
              SUM(total_amount) as total_revenue
              FROM orders";
$stats = $db->fetch($stats_sql);

$page_title = 'Manage Orders - ' . APP_NAME;
include '../templates/layouts/admin/head.php';
?>

<div class="main-content">
    <?php include '../templates/layouts/admin/header.php'; ?>

    <div class="page-header">
        <h1><i class="fas fa-shopping-bag"></i> Manage Orders</h1>
        <p class="text-muted">View and manage all platform orders</p>
    </div>

    <?php if (!empty($dashboard_filter)): ?>
    <!-- Dashboard Filter Active -->
    <div class="alert alert-info alert-dismissible fade show" role="alert">
        <strong><i class="fas fa-filter"></i> Dashboard Filter Active:</strong>
        <?php
        $filter_labels = [
            'all' => '📦 All Orders',
            'ongoing' => '🔄 Ongoing Orders',
            'future' => '🔮 Future Orders',
            'completed' => '✅ Completed Orders',
            'cancelled' => '❌ Cancelled Orders'
        ];
        echo $filter_labels[$dashboard_filter] ?? 'Custom Filter';
        ?>
        <a href="orders.php" class="btn btn-sm btn-outline-primary ms-3">Clear Filter</a>
    </div>
    <?php endif; ?>

    
    <!-- Content -->
    <div class="content">

    <!-- Stats -->
    <div class="row mb-4">
        <div class="col-md-2">
            <div class="stat-card">
                <div class="stat-icon bg-primary"><i class="fas fa-shopping-bag"></i></div>
                <div class="stat-details">
                    <h3><?= number_format($stats['total'] ?? 0) ?></h3>
                    <p>Total Orders</p>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="stat-card">
                <div class="stat-icon bg-warning"><i class="fas fa-clock"></i></div>
                <div class="stat-details">
                    <h3><?= number_format($stats['pending'] ?? 0) ?></h3>
                    <p>Pending</p>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="stat-card">
                <div class="stat-icon bg-info"><i class="fas fa-check"></i></div>
                <div class="stat-details">
                    <h3><?= number_format($stats['confirmed'] ?? 0) ?></h3>
                    <p>Confirmed</p>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="stat-card">
                <div class="stat-icon bg-primary"><i class="fas fa-play"></i></div>
                <div class="stat-details">
                    <h3><?= number_format($stats['ongoing'] ?? 0) ?></h3>
                    <p>Ongoing</p>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="stat-card">
                <div class="stat-icon bg-success"><i class="fas fa-check-double"></i></div>
                <div class="stat-details">
                    <h3><?= number_format($stats['completed'] ?? 0) ?></h3>
                    <p>Completed</p>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="stat-card">
                <div class="stat-icon bg-danger"><i class="fas fa-ban"></i></div>
                <div class="stat-details">
                    <h3><?= number_format($stats['cancelled'] ?? 0) ?></h3>
                    <p>Cancelled</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-2">
                    <label class="form-label">Status</label>
                    <select name="status" class="form-select" onchange="this.form.submit()">
                        <option value="all" <?= $status_filter === 'all' ? 'selected' : '' ?>>All Status</option>
                        <option value="pending" <?= $status_filter === 'pending' ? 'selected' : '' ?>>Pending</option>
                        <option value="confirmed" <?= $status_filter === 'confirmed' ? 'selected' : '' ?>>Confirmed</option>
                        <option value="ongoing" <?= $status_filter === 'ongoing' ? 'selected' : '' ?>>Ongoing</option>
                        <option value="completed" <?= $status_filter === 'completed' ? 'selected' : '' ?>>Completed</option>
                        <option value="cancelled" <?= $status_filter === 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Payment</label>
                    <select name="payment" class="form-select" onchange="this.form.submit()">
                        <option value="all" <?= $payment_status === 'all' ? 'selected' : '' ?>>All Payment</option>
                        <option value="pending" <?= $payment_status === 'pending' ? 'selected' : '' ?>>Pending</option>
                        <option value="paid" <?= $payment_status === 'paid' ? 'selected' : '' ?>>Paid</option>
                        <option value="refunded" <?= $payment_status === 'refunded' ? 'selected' : '' ?>>Refunded</option>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Search</label>
                    <input type="text" name="search" class="form-control" placeholder="Order #, customer, vendor, item..." value="<?= esc($search) ?>">
                </div>
                <div class="col-md-2">
                    <label class="form-label">&nbsp;</label>
                    <button type="submit" class="btn btn-primary w-100"><i class="fas fa-search"></i> Search</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Orders Table -->
    <div class="card">
        <div class="card-header">
            <h5 class="mb-0">Orders List <span class="badge bg-secondary"><?= number_format($total_orders) ?></span></h5>
        </div>
        <div class="card-body p-0">
            <?php if (empty($orders)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-shopping-bag fa-3x text-muted mb-3"></i>
                    <p class="text-muted">No orders found</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover table-striped mb-0">
                        <thead>
                            <tr>
                                <th>Order #</th>
                                <th>Customer<br>Vendor</th>
                                <th>Amount<br>Rent/Security</th>
                                <th>Status</th>
                                <th>Completion</th>
                                <th>Date</th>
                                <th class="text-end">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($orders as $order_data): ?>
                                <tr>
                                    <td>
                                        <strong><?= esc($order_data['order_number']) ?></strong><br>
                                        <?php if (!empty($order_data['item_image'])): ?>
                                            <img src="<?= upload('items/' . $order_data['item_image']) ?>" 
                                                    alt="" class="rounded me-2" style="width: 80px; height: 80px; object-fit: cover;"><br>
                                        <?php endif; ?>
                                        <span><?= esc($order_data['item_title']) ?></span>
                                        <?php if ($order_data['has_active_dispute'] == 1): ?>
                                            <br><span class="badge bg-danger"><i class="fas fa-exclamation-triangle"></i> Issue</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        C: <strong><?= esc($order_data['customer_name']) ?></strong><br>
                                        V: <strong><?= esc($order_data['vendor_name']) ?></strong>
                                    </td>
                                    <td>
                                        <strong>₦<?= number_format($order_data['total_amount'], 2) ?></strong><br><br>
                                        R: <strong>₦<?= number_format($order_data['subtotal'], 2) ?></strong><br>
                                        S: <strong>₦<?= number_format($order_data['security_deposit'], 2) ?></strong><br>
                                    </td>
                                    <td>
                                        <?php
                                        $status_badges = [
                                            'pending' => 'warning',
                                            'confirmed' => 'info',
                                            'ongoing' => 'primary',
                                            'completed' => 'success',
                                            'cancelled' => 'danger'
                                        ];
                                        $badge_class = $status_badges[$order_data['status']] ?? 'secondary';
                                        ?>
                                        <span class="badge bg-<?= $badge_class ?>"><?= ucfirst($order_data['status']) ?></span>
                                    </td>
                                    <td>
                                        <?php
                                        $customer_requested = $order_data['customer_completion_request'] ?? 0;
                                        $vendor_requested = $order_data['vendor_completion_request'] ?? 0;
                                        $completed_by = $order_data['completed_by'] ?? '';
                                        
                                        if ($order_data['status'] === 'completed'):
                                            if ($completed_by === 'admin'):
                                                echo '<span class="badge bg-info" title="Completed by admin">Admin</span>';
                                            elseif ($completed_by === 'customer_confirmed'):
                                                echo '<span class="badge bg-primary" title="Vendor requested, Customer confirmed">Cust. Confirm</span>';
                                            elseif ($completed_by === 'vendor_confirmed'):
                                                echo '<span class="badge bg-warning" title="Customer requested, Vendor confirmed">Vend. Confirm</span>';
                                            else:
                                                echo '<span class="badge bg-success">Completed</span>';
                                            endif;
                                        elseif ($customer_requested && $vendor_requested):
                                            echo '<span class="badge bg-warning">Both Requested</span>';
                                        elseif ($customer_requested):
                                            $time = $order_data['customer_completion_time'] ? date('M d, h:i A', strtotime($order_data['customer_completion_time'])) : '';
                                            echo '<span class="badge bg-info" title="' . $time . '">Cust. Requested</span>';
                                        elseif ($vendor_requested):
                                            $time = $order_data['vendor_completion_time'] ? date('M d, h:i A', strtotime($order_data['vendor_completion_time'])) : '';
                                            echo '<span class="badge bg-info" title="' . $time . '">Vend. Requested</span>';
                                        else:
                                            echo '<span class="badge bg-secondary">No Request</span>';
                                        endif;
                                        ?>
                                    </td>
                                    <td>
                                        <small><b><?= date('j M, Y', strtotime($order_data['created_at'])) ?></b></small><br>
                                        <small><?= date('j M', strtotime($order_data['start_date'])) ?> - 
                                        <small><?= date('j M, Y', strtotime($order_data['end_date'])) ?></small><br>
                                        <span class="badge bg-secondary"><?= $order_data['rental_days'] ?> days</span>
                                    </td>
                                    <td class="text-end">
                                        <div class="btn-group-vertical btn-group-sm">
                                            <a href="order-details.php?id=<?= $order_data['id'] ?>" class="btn btn-sm btn-info mb-1">
                                                <i class="fas fa-eye"></i> View
                                            </a>
                                            
                                            <?php
                                            // Admin can complete any ongoing/confirmed order
                                            $can_complete = in_array($order_data['status'], ['ongoing', 'confirmed']) 
                                                         && $order_data['rental_completed'] == 0;
                                            ?>
                                            <?php if ($can_complete): ?>
                                                <button class="btn btn-sm btn-success mb-1" 
                                                        onclick="completeRental(<?= $order_data['id'] ?>, '<?= esc($order_data['order_number']) ?>')">
                                                    <i class="fas fa-check-circle"></i> Complete
                                                    <?php if ($customer_requested || $vendor_requested): ?>
                                                        <span class="badge bg-light text-dark" title="Request pending">!</span>
                                                    <?php endif; ?>
                                                </button>
                                            <?php endif; ?>
                                            
                                            <?php
                                            $can_cancel = !in_array($order_data['status'], ['cancelled', 'completed']);
                                            ?>
                                            <?php if ($can_cancel): ?>
                                                <button class="btn btn-sm btn-danger mb-1" 
                                                        onclick="openCancelModal(<?= $order_data['id'] ?>, '<?= htmlspecialchars($order_data['order_number']) ?>')">
                                                    <i class="fas fa-ban"></i> Cancel
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                    <?php
                    // Build pagination URL with all filters
                    $params = [];
                    if (!empty($dashboard_filter)) $params['filter'] = $dashboard_filter;
                    if ($status_filter !== 'all') $params['status'] = $status_filter;
                    if ($payment_status !== 'all') $params['payment'] = $payment_status;
                    if (!empty($search)) $params['search'] = $search;
                    $base_url = 'orders.php?' . http_build_query($params);
                    ?>
                    <div class="card-footer">
                        <nav>
                            <ul class="pagination justify-content-center mb-0">
                                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                    <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                                        <a class="page-link" href="<?= $base_url ?>&page=<?= $i ?>"><?= $i ?></a>
                                    </li>
                                <?php endfor; ?>
                            </ul>
                        </nav>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Cancel Order Modal -->
<div class="modal fade" id="cancelOrderModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">
                    <i class="fas fa-exclamation-triangle"></i> Cancel Order
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form id="cancelOrderForm">
                <input type="hidden" id="cancel_order_id">
                <input type="hidden" id="cancel_cancelled_by" value="admin">
                
                <div class="modal-body">
                    <div class="alert alert-warning">
                        <i class="fas fa-info-circle"></i> 
                        <strong>Order #<span id="cancel_order_number"></span></strong> will be cancelled.
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label"><strong>Cancellation Reason</strong> <span class="text-danger">*</span></label>
                        <select class="form-select" id="cancel_reason" name="reason" required>
                            <option value="">-- Select Reason --</option>
                            <option value="Vendor request">Vendor request</option>
                            <option value="Customer request">Customer request</option>
                            <option value="Payment issue/Fraud detected">Payment issue/Fraud</option>
                            <option value="Item not available">Item not available</option>
                            <option value="Policy violation">Policy violation</option>
                            <option value="Dispute resolution">Dispute resolution</option>
                            <option value="Date conflict">Date conflict</option>
                            <option value="Other">Other (specify below)</option>
                        </select>
                    </div>
                    
                    <div class="mb-3" id="cancel_other_reason_div" style="display:none;">
                        <label class="form-label">Please specify:</label>
                        <textarea class="form-control" id="cancel_other_reason" rows="2"></textarea>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-danger" id="cancel_submit_btn">
                        <i class="fas fa-ban"></i> Cancel Order
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include '../templates/layouts/admin/footer.php'; ?>

<script>
// Cancel modal
document.getElementById('cancel_reason').addEventListener('change', function() {
    const otherDiv = document.getElementById('cancel_other_reason_div');
    if (this.value === 'Other') {
        otherDiv.style.display = 'block';
        document.getElementById('cancel_other_reason').required = true;
    } else {
        otherDiv.style.display = 'none';
        document.getElementById('cancel_other_reason').required = false;
    }
});

function openCancelModal(orderId, orderNumber) {
    document.getElementById('cancel_order_id').value = orderId;
    document.getElementById('cancel_order_number').textContent = orderNumber;
    document.getElementById('cancelOrderForm').reset();
    document.getElementById('cancel_other_reason_div').style.display = 'none';
    var cancelModal = new bootstrap.Modal(document.getElementById('cancelOrderModal'));
    cancelModal.show();
}

document.getElementById('cancelOrderForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const orderId = document.getElementById('cancel_order_id').value;
    const reason = document.getElementById('cancel_reason').value;
    const otherReason = document.getElementById('cancel_other_reason').value;
    const submitBtn = document.getElementById('cancel_submit_btn');
    
    if (!reason) {
        alert('Please select a cancellation reason');
        return;
    }
    
    if (reason === 'Other' && !otherReason.trim()) {
        alert('Please specify the cancellation reason');
        return;
    }
    
    if (!confirm('Cancel this order? Customer will receive full refund.')) {
        return;
    }
    
    const finalReason = reason === 'Other' ? otherReason : reason;
    
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Cancelling...';
    
    fetch('../api/cancel-order.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: new URLSearchParams({
            'order_id': orderId,
            'cancelled_by': 'admin',
            'reason': finalReason
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('✓ Order cancelled!\n\n' + data.message);
            bootstrap.Modal.getInstance(document.getElementById('cancelOrderModal')).hide();
            location.reload();
        } else {
            alert('✗ Error: ' + data.error);
            submitBtn.disabled = false;
            submitBtn.innerHTML = '<i class="fas fa-ban"></i> Cancel Order';
        }
    })
    .catch(error => {
        alert('✗ Failed: ' + error.message);
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fas fa-ban"></i> Cancel Order';
    });
});

// Complete rental function
function completeRental(orderId, orderNumber) {
    if (confirm('Complete order ' + orderNumber + '?\n\nThis will:\n• Release funds to vendor\n• Refund security deposit to customer\n• Send emails to both parties')) {
        fetch('../api/complete-rental.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'order_id=' + orderId + '&action=complete'
        })
        .then(r => r.json())
        .then(data => {
            alert(data.success ? '✓ ' + data.message : '✗ Error: ' + data.error);
            if (data.success) location.reload();
        });
    }
}
</script>