<?php
session_start();
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 4) {
    http_response_code(403);
    exit('Unauthorized');
}
include('../../includes/config.php');

$from_date = $_POST['from_date'] ?? date('Y-m-01');
$to_date = $_POST['to_date'] ?? date('Y-m-d');
$store_id = $_POST['store_id'] ?? '';
$detail_type = $_POST['detail_type'] ?? '';

$store_filter_sql = "";
$params = [$from_date, $to_date];
$types = "ss";

if ($store_id !== '' && is_numeric($store_id)) {
    $store_filter_sql = " AND store_id = ? ";
    $params[] = (int)$store_id;
    $types .= "i";
}

function formatMoney($num) {
    return number_format((float)$num, 2);
}

switch ($detail_type) {
    case 'income':
        // Show list of completed sales
        $sql = "SELECT id, receipt_number, customer_name, total_amount, vat_total, created_at 
                FROM sales_transactions 
                WHERE status = 'completed' 
                AND created_at BETWEEN ? AND ? 
                $store_filter_sql
                ORDER BY created_at DESC
                LIMIT 100";
        break;
    case 'cogs':
        // Show sales items with cost_price
        $sql = "SELECT st.id AS sale_id, st.receipt_number, p.product_name, si.quantity, p.cost_price, (si.quantity * p.cost_price) AS total_cost, st.created_at
                FROM sales_items si
                INNER JOIN products p ON si.product_id = p.id
                INNER JOIN sales_transactions st ON si.transaction_id = st.id
                WHERE st.status = 'completed'
                AND st.created_at BETWEEN ? AND ? 
                $store_filter_sql
                ORDER BY st.created_at DESC
                LIMIT 100";
        break;
    case 'expenses':
        // Show approved expenses
        $sql = "SELECT id, reference, description, amount, expense_date
                FROM expenses 
                WHERE status = 'approved' 
                AND deleted_at IS NULL
                AND expense_date BETWEEN ? AND ?
                $store_filter_sql
                ORDER BY expense_date DESC
                LIMIT 100";
        break;
    case 'netprofit':
        // Show summary breakdown (just reuse income, cogs, expenses)
        echo "<p><strong>Net Profit Breakdown:</strong></p>";
        echo "<ul>";
        echo "<li>Total Income (Net of VAT): " . formatMoney(getValue($conn, "SELECT SUM(total_amount - vat_total) FROM sales_transactions WHERE status = 'completed' AND created_at BETWEEN ? AND ? " . ($store_id ? "AND store_id = ?" : ""), $params, $types)) . "</li>";
        echo "<li>COGS (from sales items): " . formatMoney(getValue($conn, "SELECT SUM(si.quantity * p.cost_price) FROM sales_items si INNER JOIN products p ON si.product_id = p.id INNER JOIN sales_transactions st ON si.transaction_id = st.id WHERE st.status = 'completed' AND st.created_at BETWEEN ? AND ? " . ($store_id ? "AND st.store_id = ?" : ""), $params, $types)) . "</li>";
        echo "<li>Operating Expenses: " . formatMoney(getValue($conn, "SELECT SUM(amount) FROM expenses WHERE status = 'approved' AND deleted_at IS NULL AND expense_date BETWEEN ? AND ? " . ($store_id ? "AND store_id = ?" : ""), $params, $types)) . "</li>";
        echo "</ul>";
        exit;
    default:
        echo "Invalid detail type.";
        exit;
}

$stmt = $conn->prepare($sql);
if ($store_id !== '' && is_numeric($store_id)) {
    $stmt->bind_param($types, ...$params);
} else {
    $stmt->bind_param("ss", $from_date, $to_date);
}
$stmt->execute();
$res = $stmt->get_result();

echo "<table class='table table-striped table-dark table-bordered'>";
if ($detail_type == 'income') {
    echo "<thead><tr><th>ID</th><th>Receipt No.</th><th>Customer</th><th>Total Amount</th><th>VAT</th><th>Date</th></tr></thead><tbody>";
    while ($r = $res->fetch_assoc()) {
        echo "<tr>";
        echo "<td>" . htmlspecialchars($r['id']) . "</td>";
        echo "<td>" . htmlspecialchars($r['receipt_number']) . "</td>";
        echo "<td>" . htmlspecialchars($r['customer_name']) . "</td>";
        echo "<td>" . formatMoney($r['total_amount']) . "</td>";
        echo "<td>" . formatMoney($r['vat_total']) . "</td>";
        echo "<td>" . htmlspecialchars($r['created_at']) . "</td>";
        echo "</tr>";
    }
    echo "</tbody>";
} elseif ($detail_type == 'cogs') {
    echo "<thead><tr><th>Sale ID</th><th>Receipt No.</th><th>Product</th><th>Qty</th><th>Cost Price</th><th>Total Cost</th><th>Date</th></tr></thead><tbody>";
    while ($r = $res->fetch_assoc()) {
        echo "<tr>";
        echo "<td>" . htmlspecialchars($r['sale_id']) . "</td>";
        echo "<td>" . htmlspecialchars($r['receipt_number']) . "</td>";
        echo "<td>" . htmlspecialchars($r['product_name']) . "</td>";
        echo "<td>" . htmlspecialchars($r['quantity']) . "</td>";
        echo "<td>" . formatMoney($r['cost_price']) . "</td>";
        echo "<td>" . formatMoney($r['total_cost']) . "</td>";
        echo "<td>" . htmlspecialchars($r['created_at']) . "</td>";
        echo "</tr>";
    }
    echo "</tbody>";
} elseif ($detail_type == 'expenses') {
    echo "<thead><tr><th>ID</th><th>Reference</th><th>Description</th><th>Amount</th><th>Date</th></tr></thead><tbody>";
    while ($r = $res->fetch_assoc()) {
        echo "<tr>";
        echo "<td>" . htmlspecialchars($r['id']) . "</td>";
        echo "<td>" . htmlspecialchars($r['reference']) . "</td>";
        echo "<td>" . htmlspecialchars($r['description']) . "</td>";
        echo "<td>" . formatMoney($r['amount']) . "</td>";
        echo "<td>" . htmlspecialchars($r['expense_date']) . "</td>";
        echo "</tr>";
    }
    echo "</tbody>";
}
echo "</table>";

function getValue($conn, $query, $params, $types) {
    $stmt = $conn->prepare($query);
    if (count($params) == 3) {
        $stmt->bind_param($types, ...$params);
    } else {
        $stmt->bind_param("ss", $params[0], $params[1]);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_row();
    $stmt->close();
    return $row[0] ?? 0;
}
?>
