<?php
session_start();
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 4) {
    header("Location: ../../index.php");
    exit();
}
include('../../includes/config.php');

$export = $_GET['export'] ?? '';
$date_from = $_GET['from_date'] ?? date('Y-m-01');
$date_to = $_GET['to_date'] ?? date('Y-m-d');
$store_id = $_GET['store_id'] ?? '';

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

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

$total_income = getSingleValue($conn, "SELECT SUM(total_amount - vat_total) FROM sales_transactions WHERE status = 'completed' AND created_at BETWEEN ? AND ? $store_filter_sql", $params, $types);
$cogs = getSingleValue($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_filter_sql", $params, $types);
$operating_expenses = getSingleValue($conn, "SELECT SUM(amount) FROM expenses WHERE status = 'approved' AND deleted_at IS NULL AND expense_date BETWEEN ? AND ? $store_filter_sql", $params, $types);
$gross_profit = $total_income - $cogs;
$net_profit = $gross_profit - $operating_expenses;

if ($export === 'excel') {
    // Export as simple CSV
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="income_statement.csv"');
    $output = fopen('php://output', 'w');
    fputcsv($output, ['Section', 'Amount']);
    fputcsv($output, ['Total Income (Net of VAT)', number_format($total_income, 2)]);
    fputcsv($output, ['Cost of Goods Sold (COGS)', number_format($cogs, 2)]);
    fputcsv($output, ['Gross Profit', number_format($gross_profit, 2)]);
    fputcsv($output, ['Operating Expenses', number_format($operating_expenses, 2)]);
    fputcsv($output, ['Net Profit', number_format($net_profit, 2)]);
    fclose($output);
    exit;
}

if ($export === 'pdf') {
    // Basic PDF export using TCPDF or similar library recommended.
    // Below example uses a very simple HTML and browser print (you can replace with TCPDF or FPDF)

    echo "<html><head><title>Income Statement PDF</title></head><body>";
    echo "<h2>Income Statement (Profit & Loss)</h2>";
    echo "<p>From: " . htmlspecialchars($date_from) . " To: " . htmlspecialchars($date_to) . "</p>";
    if ($store_id !== '') {
        $store_name = $conn->query("SELECT store_name FROM stores WHERE id = " . intval($store_id))->fetch_assoc()['store_name'] ?? 'N/A';
        echo "<p>Store: " . htmlspecialchars($store_name) . "</p>";
    }
    echo "<table border='1' cellpadding='5' cellspacing='0'>";
    echo "<tr><th>Section</th><th>Amount</th></tr>";
    echo "<tr><td>Total Income (Net of VAT)</td><td>" . number_format($total_income, 2) . "</td></tr>";
    echo "<tr><td>Cost of Goods Sold (COGS)</td><td>" . number_format($cogs, 2) . "</td></tr>";
    echo "<tr><td>Gross Profit</td><td>" . number_format($gross_profit, 2) . "</td></tr>";
    echo "<tr><td>Operating Expenses</td><td>" . number_format($operating_expenses, 2) . "</td></tr>";
    echo "<tr><td><b>Net Profit</b></td><td><b>" . number_format($net_profit, 2) . "</b></td></tr>";
    echo "</table>";
    echo "<script>window.print();</script>";
    echo "</body></html>";
    exit;
}

header('Location: income_statement.php'); // fallback redirect

?>
