<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/order.php';
require_once __DIR__ . '/../vendor/autoload.php';

use Dompdf\Dompdf;

// Check if user is admin
if (!isAdmin()) {
    header('Location: ../login.php?redirect=admin/');
    exit;
}

$orderModel = new Order();
$revenueDetails = $orderModel->getRevenueDetails();
$revenueChart = $orderModel->getRevenueByDate();

// Export as PDF
if (isset($_POST['export_pdf'])) {

    $chart = $_POST['chart_image'] ?? '';

    ob_start();
    ?>
    <h1>Total Revenue Report</h1>
	<img src="<?= $chart ?>" width="100%">	
	
	<br><br><br>
    <table border="1" width="100%" cellpadding="5">
        <thead>
            <tr>
                <th>Order #</th>
                <th>Customer</th>
                <th>Amount</th>
                <th>Status</th>
                <th>Date</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($revenueDetails as $row): ?>
                <tr>
                    <td><?= $row['order_number'] ?></td>
                    <td><?= $row['full_name'] ?? 'Guest' ?></td>
                    <td><?= $row['total_amount'] ?></td>
                    <td><?= $row['status'] ?></td>
                    <td><?= $row['created_at'] ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    
    <?php

    $html = ob_get_clean();

    $dompdf = new Dompdf();
    $dompdf->loadHtml($html);
    $dompdf->render();
    $dompdf->stream("total_revenue.pdf");

    exit;
}

// Export as Excel
if (isset($_POST['export_excel'])) {

    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=revenue.xls");

    echo "Order #\tCustomer\tAmount\tStatus\tDate\n";

    foreach ($revenueDetails as $row) {
        echo "{$row['order_number']}\t{$row['full_name']}\t{$row['total_amount']}\t{$row['status']}\t{$row['created_at']}\n";
    }

    exit;
}

$pageTitle = 'Total Revenue';
require_once __DIR__ . '/admin_header.php';
?>

<div class="admin-header">
    <h1>Total Revenue</h1>
</div>

<div class="admin-card">
    <div class="admin-card-header">
        <h2>Revenue Overview</h2>
    </div>
    <canvas id="revenueChart" height="100"></canvas>
</div>

<div class="admin-card">
    <div class="admin-card-header">
        <h2>Revenue Details</h2>
    </div>

    <table class="admin-table">
        <thead>
            <tr>
                <th>Order #</th>
                <th>Customer</th>
                <th>Amount</th>
                <th>Status</th>
                <th>Date</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($revenueDetails as $row): ?>
                <tr>
                    <td><?= htmlspecialchars($row['order_number']) ?></td>
                    <td><?= htmlspecialchars($row['full_name'] ?? 'Guest') ?></td>
                    <td><?= htmlspecialchars($row['total_amount']) ?></td>
                    <td><?= htmlspecialchars($row['status']) ?></td>
                    <td><?= date('M j, Y', strtotime($row['created_at'])) ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<div style="margin-bottom: 15px; text-align: right">
    <form method="POST" id="pdfForm" style="display:inline;">
        <input type="hidden" name="chart_image" id="chart_image">
        <input type="hidden" name="export_pdf" value="1">
        <button type="button" class="btn btn-success" onclick="exportPDF()">Export as PDF</button>
    </form>

    <form method="POST" style="display:inline;">
        <input type="hidden" name="export_excel" value="1">
        <button type="submit" class="btn btn-success">Export as Excel</button>
    </form>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const chartData = <?php echo json_encode($revenueChart); ?>;

const labels = chartData.map(item => item.date);
const data = chartData.map(item => item.total);

const ctx = document.getElementById('revenueChart').getContext('2d');

const revenueChartInstance = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: labels,
        datasets: [{
            label: 'Revenue',
            data: data,
			backgroundColor: '#333',
			hoverBackgroundColor: 'black'
        }]
    }
});

function exportPDF() {
    const image = revenueChartInstance.toBase64Image();
    document.getElementById('chart_image').value = image;
    document.getElementById('pdfForm').submit();
}
</script>

<?php require_once __DIR__ . '/admin_footer.php'; ?>