<?php
session_start();
require_once 'config.php';

echo "<h2>Sales Commission Debug Report</h2>";

echo "<h3>1. Sales Officers in Database</h3>";
$officers = $conn->query("SELECT * FROM sales_officers ORDER BY id DESC LIMIT 10");
if ($officers && $officers->num_rows > 0) {
    echo "<table border='1' cellpadding='10'><tr><th>ID</th><th>Name</th><th>Active</th><th>Created</th></tr>";
    while ($row = $officers->fetch_assoc()) {
        echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td><td>{$row['is_active']}</td><td>{$row['created_at']}</td></tr>";
    }
    echo "</table>";
} else {
    echo "No sales officers found!";
}

echo "<h3>2. Recent Sales (Last 10)</h3>";
$sales = $conn->query("SELECT id, customer_phone, total_amount, payment_method, sale_date FROM sales ORDER BY id DESC LIMIT 10");
if ($sales && $sales->num_rows > 0) {
    echo "<table border='1' cellpadding='10'><tr><th>Sale ID</th><th>Phone</th><th>Amount</th><th>Method</th><th>Date</th></tr>";
    while ($row = $sales->fetch_assoc()) {
        echo "<tr><td>{$row['id']}</td><td>{$row['customer_phone']}</td><td>{$row['total_amount']}</td><td>{$row['payment_method']}</td><td>{$row['sale_date']}</td></tr>";
    }
    echo "</table>";
} else {
    echo "No sales found!";
}

echo "<h3>3. Sales Commissions (Last 10)</h3>";
$commissions = $conn->query("SELECT sc.id, sc.sale_id, sc.sales_officer_id, so.name, sc.commission_amount, sc.created_at FROM sales_commissions sc LEFT JOIN sales_officers so ON sc.sales_officer_id = so.id ORDER BY sc.id DESC LIMIT 10");
if ($commissions && $commissions->num_rows > 0) {
    echo "<table border='1' cellpadding='10'><tr><th>Comm ID</th><th>Sale ID</th><th>Officer ID</th><th>Officer Name</th><th>Commission</th><th>Created</th></tr>";
    while ($row = $commissions->fetch_assoc()) {
        echo "<tr><td>{$row['id']}</td><td>{$row['sale_id']}</td><td>{$row['sales_officer_id']}</td><td>{$row['name']}</td><td>Rs. {$row['commission_amount']}</td><td>{$row['created_at']}</td></tr>";
    }
    echo "</table>";
} else {
    echo "No commissions found!";
}

echo "<h3>4. December 2025 Sales with Officers</h3>";
$dec_sales = $conn->query("SELECT s.id, s.total_amount, s.sale_date, sc.commission_amount, so.name FROM sales s LEFT JOIN sales_commissions sc ON s.id = sc.sale_id LEFT JOIN sales_officers so ON sc.sales_officer_id = so.id WHERE YEAR(s.sale_date) = 2025 AND MONTH(s.sale_date) = 12");
if ($dec_sales && $dec_sales->num_rows > 0) {
    echo "<table border='1' cellpadding='10'><tr><th>Sale ID</th><th>Amount</th><th>Date</th><th>Commission</th><th>Officer</th></tr>";
    while ($row = $dec_sales->fetch_assoc()) {
        echo "<tr><td>{$row['id']}</td><td>{$row['total_amount']}</td><td>{$row['sale_date']}</td><td>{$row['commission_amount']}</td><td>{$row['name']}</td></tr>";
    }
    echo "</table>";
} else {
    echo "No December 2025 sales found!";
}

echo "<hr><p><a href='dashboard.php'>Back to Dashboard</a></p>";
?>
