<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('report_view');

$pdo = getDB();
$from = $_GET['from'] ?? date('Y-m-01');
$to = $_GET['to'] ?? date('Y-m-d');

// Sales Revenue
$stmt = $pdo->prepare("SELECT COALESCE(SUM(total_amount),0) FROM sales_invoices WHERE DATE(invoice_date) BETWEEN ? AND ? AND invoice_status != 'Cancelled'");
$stmt->execute([$from, $to]);
$revenue = $stmt->fetchColumn();

// Cost of Goods Sold (simplified: based on cost price of items sold)
$stmt = $pdo->prepare("
    SELECT COALESCE(SUM(p.cost_price * sii.quantity),0)
    FROM sales_invoice_items sii
    JOIN products p ON sii.product_id = p.id
    JOIN sales_invoices si ON sii.sales_invoice_id = si.id
    WHERE DATE(si.invoice_date) BETWEEN ? AND ? AND si.invoice_status != 'Cancelled'
");
$stmt->execute([$from, $to]);
$cogs = $stmt->fetchColumn();

// Repair Income
$stmt = $pdo->prepare("SELECT COALESCE(SUM(paid_amount),0) FROM repair_jobs WHERE DATE(updated_at) BETWEEN ? AND ? AND repair_status = 'Delivered'");
$stmt->execute([$from, $to]);
$repair_income = $stmt->fetchColumn();

// Expenses
$stmt = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM expenses WHERE DATE(expense_date) BETWEEN ? AND ?");
$stmt->execute([$from, $to]);
$expenses = $stmt->fetchColumn();

$gross_profit = $revenue - $cogs;
$net_profit = $gross_profit + $repair_income - $expenses;

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <h4 class="page-title"><i class="fas fa-chart-pie me-2"></i>Profit & Loss Report</h4>
        <div class="card">
            <div class="card-body">
                <form method="GET" class="row g-3 mb-3">
                    <div class="col-md-4"><input type="date" name="from" class="form-control" value="<?= $from ?>"></div>
                    <div class="col-md-4"><input type="date" name="to" class="form-control" value="<?= $to ?>"></div>
                    <div class="col-md-4"><button type="submit" class="btn btn-primary"><i class="fas fa-filter me-1"></i>Filter</button></div>
                </form>
                <div class="table-responsive">
                    <table class="table table-bordered no-datatable">
                        <tr><td colspan="2"><strong>Income</strong></td></tr>
                        <tr><td>Sales Revenue</td><td class="text-end"><?= formatCurrency($revenue) ?></td></tr>
                        <tr><td>Repair Income</td><td class="text-end"><?= formatCurrency($repair_income) ?></td></tr>
                        <tr class="fw-bold"><td>Total Income</td><td class="text-end"><?= formatCurrency($revenue + $repair_income) ?></td></tr>
                        <tr><td colspan="2"><strong>Cost of Goods Sold</strong></td></tr>
                        <tr><td>COGS (Products)</td><td class="text-end"><?= formatCurrency($cogs) ?></td></tr>
                        <tr class="fw-bold"><td>Gross Profit</td><td class="text-end"><?= formatCurrency($gross_profit) ?></td></tr>
                        <tr><td colspan="2"><strong>Expenses</strong></td></tr>
                        <tr><td>Total Expenses</td><td class="text-end"><?= formatCurrency($expenses) ?></td></tr>
                        <tr class="fw-bold <?= $net_profit < 0 ? 'text-danger' : 'text-success' ?>"><td>Net Profit / Loss</td><td class="text-end"><?= formatCurrency($net_profit) ?></td></tr>
                    </table>
                </div>
                <button class="btn btn-success" onclick="window.print()"><i class="fas fa-print me-1"></i>Print</button>
            </div>
        </div>
    </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
