<?php
// External API Profit Tracking Page
require_once '../config.php';
require_once '../app/classes/ExternalAPIOrderService.php';

$page_title = 'External API Profit Tracking';
$page_description = 'View profit made on each order sent through external API';

use App\classes\ExternalAPIOrderService;

$orderService = new ExternalAPIOrderService($conn);

// Get filters - default to last 30 days if no dates are set
$filterStatus = $_GET['status'] ?? '';
$filterDateFrom = $_GET['date_from'] ?? '';
$filterDateTo = $_GET['date_to'] ?? '';

// Set default to last 30 days if no date filters are provided (shows recent orders)
if (empty($filterDateFrom) && empty($filterDateTo)) {
    $filterDateTo = date('Y-m-d');
    $filterDateFrom = date('Y-m-d', strtotime('-30 days'));
}

$filters = [];
if ($filterStatus) $filters['status'] = $filterStatus;
// SECURITY: Always apply date filters to prevent showing all orders
if (!empty($filterDateFrom)) {
    $filters['date_from'] = $filterDateFrom;
}
if (!empty($filterDateTo)) {
    $filters['date_to'] = $filterDateTo;
}

// Get orders
try {
    $orders = $orderService->getAllOrders($filters);
} catch (Exception $e) {
    error_log("External API Profit Error: " . $e->getMessage());
    $orders = [];
}

// Debug: Check table and log info
if (empty($orders)) {
    $tableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'external_api_orders'");
    if (mysqli_num_rows($tableCheck) == 0) {
        error_log("External API Profit: Table 'external_api_orders' does not exist!");
    } else {
        $countResult = mysqli_query($conn, "SELECT COUNT(*) as count FROM external_api_orders");
        $countRow = mysqli_fetch_assoc($countResult);
        error_log("External API Profit: Table exists with " . $countRow['count'] . " total orders. Filters: " . json_encode($filters));
    }
}

// Get statistics
try {
    $stats = $orderService->getProfitStatistics($filterDateFrom, $filterDateTo);
} catch (Exception $e) {
    error_log("External API Profit Statistics Error: " . $e->getMessage());
    $stats = [
        'total_orders' => 0,
        'total_revenue' => 0,
        'total_cost' => 0,
        'total_profit' => 0
    ];
}
?>

<div class="container mx-auto px-4 py-8">
    <!-- Header -->
    <div class="mb-8">
        <h1 class="text-3xl font-bold text-white mb-2">
            <i class="fas fa-chart-line mr-2"></i>External API Profit Tracking
        </h1>
        <p class="text-gray-400">View profit made on each order sent through external API (MTN only)</p>
        <?php 
        // Check total orders in table
        $totalCheck = mysqli_query($conn, "SELECT COUNT(*) as count FROM external_api_orders");
        $totalRow = mysqli_fetch_assoc($totalCheck);
        $totalInTable = $totalRow['count'] ?? 0;
        ?>
        <?php if (empty($orders) && $totalInTable == 0): ?>
        <div class="mt-4 bg-yellow-900 border border-yellow-700 rounded-lg p-4">
            <p class="text-yellow-200 text-sm mb-2">
                <i class="fas fa-info-circle mr-2"></i>
                <strong>No external API orders found.</strong>
            </p>
            <p class="text-yellow-300 text-xs">
                Orders must be created through the <code class="bg-yellow-800 px-2 py-1 rounded text-xs">api/create_external_api_order.php</code> endpoint to appear here.
                This is a separate system from regular orders (which go to <code class="bg-yellow-800 px-2 py-1 rounded text-xs">orders</code> or <code class="bg-yellow-800 px-2 py-1 rounded text-xs">agent_orders</code> tables).
            </p>
        </div>
        <?php elseif (empty($orders) && $totalInTable > 0): ?>
        <div class="mt-4 bg-blue-900 border border-blue-700 rounded-lg p-4">
            <p class="text-blue-200 text-sm">
                <i class="fas fa-filter mr-2"></i>
                <strong>No orders match the current filters.</strong> There are <?= $totalInTable ?> total orders in the system. 
                Try adjusting your filters or clearing them to see all orders.
            </p>
        </div>
        <?php endif; ?>
    </div>

    <!-- Statistics Cards -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div class="bg-gray-800 border border-gray-700 rounded-lg p-6">
            <p class="text-gray-400 text-sm mb-1">Total Orders</p>
            <p class="text-3xl font-bold text-white"><?= number_format($stats['total_orders'] ?? 0) ?></p>
        </div>
        <div class="bg-gray-800 border border-gray-700 rounded-lg p-6">
            <p class="text-gray-400 text-sm mb-1">Total Revenue</p>
            <p class="text-3xl font-bold text-green-400">GHS <?= number_format($stats['total_revenue'] ?? 0, 2) ?></p>
        </div>
        <div class="bg-gray-800 border border-gray-700 rounded-lg p-6">
            <p class="text-gray-400 text-sm mb-1">Total Cost</p>
            <p class="text-3xl font-bold text-red-400">GHS <?= number_format($stats['total_cost'] ?? 0, 2) ?></p>
        </div>
        <div class="bg-gray-800 border border-gray-700 rounded-lg p-6">
            <p class="text-gray-400 text-sm mb-1">Total Profit</p>
            <p class="text-3xl font-bold <?= ($stats['total_profit'] ?? 0) >= 0 ? 'text-green-400' : 'text-red-400' ?>">
                GHS <?= number_format($stats['total_profit'] ?? 0, 2) ?>
            </p>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-gray-800 border border-gray-700 rounded-lg p-6 mb-6">
        <form method="GET" action="index.php" class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <input type="hidden" name="page" value="external_api_profit">
            <div>
                <label class="block text-sm font-medium text-gray-300 mb-2">Status</label>
                <select name="status" class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg px-4 py-2">
                    <option value="">All Statuses</option>
                    <option value="pending" <?= $filterStatus === 'pending' ? 'selected' : '' ?>>Pending</option>
                    <option value="processing" <?= $filterStatus === 'processing' ? 'selected' : '' ?>>Processing</option>
                    <option value="delivered" <?= $filterStatus === 'delivered' ? 'selected' : '' ?>>Delivered</option>
                    <option value="failed" <?= $filterStatus === 'failed' ? 'selected' : '' ?>>Failed</option>
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-300 mb-2">Date From</label>
                <input type="date" name="date_from" value="<?= htmlspecialchars($filterDateFrom) ?>"
                       class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg px-4 py-2">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-300 mb-2">Date To</label>
                <input type="date" name="date_to" value="<?= htmlspecialchars($filterDateTo) ?>"
                       class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg px-4 py-2">
            </div>
            <div class="flex items-end gap-2">
                <button type="submit" class="flex-1 bg-blue-600 hover:bg-blue-700 text-white py-2 rounded-lg font-medium">
                    <i class="fas fa-filter mr-2"></i>Filter
                </button>
                <a href="index.php?page=external_api_profit" class="px-4 bg-gray-600 hover:bg-gray-700 text-white py-2 rounded-lg font-medium">
                    <i class="fas fa-redo mr-2"></i>Reset
                </a>
            </div>
        </form>
    </div>

    <!-- Orders Table -->
    <div class="bg-gray-800 border border-gray-700 rounded-lg overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full" id="profitTable">
                <thead>
                    <tr class="bg-gray-700 border-b border-gray-600">
                        <th class="text-left py-3 px-4 text-gray-300">Order ID</th>
                        <th class="text-left py-3 px-4 text-gray-300">Date</th>
                        <th class="text-left py-3 px-4 text-gray-300">Package</th>
                        <th class="text-left py-3 px-4 text-gray-300">Beneficiary</th>
                        <th class="text-right py-3 px-4 text-gray-300">Admin Price</th>
                        <th class="text-right py-3 px-4 text-gray-300">External Price</th>
                        <th class="text-right py-3 px-4 text-gray-300">Profit</th>
                        <th class="text-left py-3 px-4 text-gray-300">Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($orders)): ?>
                    <tr>
                        <td colspan="8" class="text-center py-8 text-gray-400">No orders found</td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($orders as $order): ?>
                    <tr class="border-b border-gray-700/50 hover:bg-gray-700/30">
                        <td class="py-3 px-4 text-white">#<?= $order['id'] ?></td>
                        <td class="py-3 px-4 text-gray-300 text-sm"><?= date('M j, Y H:i', strtotime($order['created_at'])) ?></td>
                        <td class="py-3 px-4 text-white"><?= htmlspecialchars($order['package_size']) ?></td>
                        <td class="py-3 px-4 text-gray-300"><?= htmlspecialchars($order['beneficiary_number']) ?></td>
                        <td class="py-3 px-4 text-right text-green-400 font-semibold">GHS <?= number_format($order['admin_price'], 2) ?></td>
                        <td class="py-3 px-4 text-right text-red-400">GHS <?= number_format($order['external_api_price'], 2) ?></td>
                        <td class="py-3 px-4 text-right font-bold <?= $order['profit'] >= 0 ? 'text-green-400' : 'text-red-400' ?>">
                            GHS <?= number_format($order['profit'], 2) ?>
                        </td>
                        <td class="py-3 px-4">
                            <?php
                            $statusColors = [
                                'pending' => 'bg-yellow-900 text-yellow-300',
                                'processing' => 'bg-blue-900 text-blue-300',
                                'delivered' => 'bg-green-900 text-green-300',
                                'failed' => 'bg-red-900 text-red-300',
                                'cancelled' => 'bg-gray-700 text-gray-300'
                            ];
                            $statusColor = $statusColors[$order['status']] ?? 'bg-gray-700 text-gray-300';
                            ?>
                            <span class="px-2 py-1 rounded text-xs font-medium <?= $statusColor ?>">
                                <?= ucfirst($order['status']) ?>
                            </span>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
// Initialize DataTables if available
if (typeof $ !== 'undefined' && $.fn.DataTable) {
    $(document).ready(function() {
        // Check if table exists
        const table = $('#profitTable');
        if (table.length === 0) {
            console.error('profitTable not found');
            return;
        }
        
        // Destroy existing DataTable instance if it exists
        if ($.fn.DataTable.isDataTable('#profitTable')) {
            $('#profitTable').DataTable().destroy();
        }
        
        // Count columns in header to verify structure
        const headerCols = table.find('thead tr th').length;
        const firstRowCols = table.find('tbody tr:first td').length;
        
        // Only initialize if structure is correct
        if (headerCols === 8 && (firstRowCols === 8 || table.find('tbody tr').length === 0)) {
            $('#profitTable').DataTable({
                order: [[0, 'desc']],
                pageLength: 25,
                language: {
                    search: "Search:",
                    lengthMenu: "Show _MENU_ entries"
                },
                responsive: true,
                autoWidth: false
            });
        } else {
            console.error('Column count mismatch: Header has ' + headerCols + ' columns, first row has ' + firstRowCols + ' columns');
        }
    });
} else {
    console.warn('jQuery or DataTables not loaded');
}
</script>

