<?php
require_once '../includes/auth.php';
requirePermission('reports', 'view');
require_once '../db.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

$from = $_GET['from'] ?? date('Y-m-01');
$to   = $_GET['to'] ?? date('Y-m-d');
$customer_id = $_GET['customer_id'] ?? '';
$itemWise = isset($_GET['itemwise']) ? 1 : 0;

$customers = $conn->query("SELECT id, name FROM clients ORDER BY name ASC");

$where = " WHERE si.invoice_date BETWEEN ? AND ? AND si.company_id = ? AND si.status = 'final' ";
$params = [$from, $to, $cid];
$types = "ssi";

if (!empty($customer_id)) {
    $where .= " AND si.client_id = ? ";
    $params[] = $customer_id;
    $types .= "i";
}

$totalSales = 0;
$totalCost = 0;
$totalProfit = 0;

$rows = [];

if ($itemWise) {
    $sql = "
        SELECT si.id, si.invoice_no, si.invoice_date, c.name AS customer_name,
               p.name AS product_name, s.batch_no, s.sold_qty,
               s.purchase_price, s.selling_price_excl,
               ((s.selling_price_excl - s.purchase_price) * s.sold_qty) AS profit
        FROM sales_items s
        JOIN sales_invoices si ON si.id = s.sales_invoice_id
        JOIN clients c ON c.id = si.client_id
        JOIN products p ON p.id = s.product_id
        $where
        ORDER BY si.id DESC
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
    while($row = $result->fetch_assoc()) {
        $totalSales += $row['selling_price_excl'] * $row['sold_qty'];
        $totalCost  += $row['purchase_price'] * $row['sold_qty'];
        $totalProfit += $row['profit'];
        $rows[] = $row;
    }
} else {
    $sql = "
        SELECT si.id, si.invoice_no, si.invoice_date, si.net_total, c.name AS customer_name,
               SUM(s.purchase_price * s.sold_qty) AS total_cost,
               SUM(s.selling_price_excl * s.sold_qty) AS total_sale_excl,
               SUM((s.selling_price_excl - s.purchase_price) * s.sold_qty) AS profit
        FROM sales_invoices si
        JOIN clients c ON c.id = si.client_id
        JOIN sales_items s ON s.sales_invoice_id = si.id
        $where
        GROUP BY si.id
        ORDER BY si.id DESC
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
    while($row = $result->fetch_assoc()) {
        $totalSales  += $row['total_sale_excl'];
        $totalCost   += $row['total_cost'];
        $totalProfit += $row['profit'];
        $rows[] = $row;
    }
}
?>

<div class="page-header">
    <h2><i class="fas fa-chart-pie" style="color:var(--primary);margin-right:8px;"></i>Profit Report</h2>
    <div style="display:flex;gap:8px;">
        <a href="profit_export_excel.php?from=<?= urlencode($from) ?>&to=<?= urlencode($to) ?>&customer_id=<?= urlencode($customer_id) ?>&itemwise=<?= $itemWise ?>"
           target="_blank" class="btn btn-success btn-sm"><i class="fas fa-file-excel"></i> Excel</a>
        <a href="profit_export_pdf.php?from=<?= urlencode($from) ?>&to=<?= urlencode($to) ?>&customer_id=<?= urlencode($customer_id) ?>&itemwise=<?= $itemWise ?>"
           target="_blank" class="btn btn-danger btn-sm"><i class="fas fa-file-pdf"></i> PDF</a>
    </div>
</div>

<!-- Filters -->
<div class="filter-panel">
    <form method="GET" class="filter-form">
        <div class="filter-group">
            <label>From</label>
            <input type="date" name="from" value="<?= htmlspecialchars($from) ?>">
        </div>
        <div class="filter-group">
            <label>To</label>
            <input type="date" name="to" value="<?= htmlspecialchars($to) ?>">
        </div>
        <div class="filter-group">
            <label>Customer</label>
            <select name="customer_id">
                <option value="">All Customers</option>
                <?php while($c = $customers->fetch_assoc()): ?>
                    <option value="<?= $c['id'] ?>" <?= ($customer_id==$c['id'])?'selected':'' ?>>
                        <?= htmlspecialchars($c['name']) ?>
                    </option>
                <?php endwhile; ?>
            </select>
        </div>
        <div class="filter-group" style="justify-content:flex-end;">
            <label style="font-weight:400;text-transform:none;letter-spacing:0;display:flex;align-items:center;gap:6px;margin-top:20px;cursor:pointer;">
                <input type="checkbox" name="itemwise" value="1" <?= $itemWise?'checked':'' ?> style="width:auto;accent-color:var(--primary);">
                Item Wise
            </label>
        </div>
        <div class="filter-actions">
            <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Generate</button>
            <a href="profit_report.php" class="btn btn-secondary">Reset</a>
        </div>
    </form>
</div>

<!-- Summary -->
<div class="stat-cards">
    <div class="stat-card">
        <div class="stat-card-label">Total Sales</div>
        <div class="stat-card-value" style="color:var(--primary);">&#8377; <?= number_format($totalSales, 2) ?></div>
    </div>
    <div class="stat-card">
        <div class="stat-card-label">Total Cost</div>
        <div class="stat-card-value" style="color:var(--danger);">&#8377; <?= number_format($totalCost, 2) ?></div>
    </div>
    <div class="stat-card">
        <div class="stat-card-label">Total Profit</div>
        <div class="stat-card-value" style="color:var(--success);">&#8377; <?= number_format($totalProfit, 2) ?></div>
    </div>
    <?php if($totalSales > 0): ?>
    <div class="stat-card">
        <div class="stat-card-label">Profit Margin</div>
        <div class="stat-card-value" style="color:var(--info);"><?= number_format(($totalProfit/$totalSales)*100, 1) ?>%</div>
    </div>
    <?php endif; ?>
</div>

<!-- Table -->
<div class="panel">
    <div style="overflow-x:auto;">
        <table>
            <thead>
                <?php if($itemWise): ?>
                <tr>
                    <th>Invoice No</th><th>Date</th><th>Customer</th><th>Product</th>
                    <th>Batch</th><th style="text-align:center;">Qty</th>
                    <th style="text-align:right;">Purchase</th>
                    <th style="text-align:right;">Sell (Excl GST)</th>
                    <th style="text-align:right;">Profit</th>
                </tr>
                <?php else: ?>
                <tr>
                    <th>Invoice No</th><th>Date</th><th>Customer</th>
                    <th style="text-align:right;">Total Sales</th>
                    <th style="text-align:right;">Total Cost</th>
                    <th style="text-align:right;">Profit</th>
                </tr>
                <?php endif; ?>
            </thead>
            <tbody>
            <?php if(count($rows) > 0): ?>
                <?php foreach($rows as $row): ?>
                <tr>
                    <td><a href="#" onclick="openDocPopup('sale',<?= $row['id'] ?>,'<?= htmlspecialchars($row['invoice_no'],ENT_QUOTES) ?>');return false;" style="font-weight:700;color:var(--primary);text-decoration:none;"><?= htmlspecialchars($row['invoice_no']) ?></a></td>
                    <td><?= date('d-m-Y', strtotime($row['invoice_date'])) ?></td>
                    <td><?= htmlspecialchars($row['customer_name']) ?></td>
                    <?php if($itemWise): ?>
                    <td><?= htmlspecialchars($row['product_name']) ?></td>
                    <td style="color:var(--text-secondary);font-size:12px;"><?= htmlspecialchars($row['batch_no']) ?></td>
                    <td style="text-align:center;"><?= number_format($row['sold_qty'], 0) ?></td>
                    <td style="text-align:right;">&#8377; <?= number_format($row['purchase_price'], 2) ?></td>
                    <td style="text-align:right;">&#8377; <?= number_format($row['selling_price_excl'], 2) ?></td>
                    <?php else: ?>
                    <td style="text-align:right;">&#8377; <?= number_format($row['total_sale_excl'], 2) ?></td>
                    <td style="text-align:right;">&#8377; <?= number_format($row['total_cost'], 2) ?></td>
                    <?php endif; ?>
                    <td style="text-align:right;color:<?= $row['profit'] >= 0 ? 'var(--success)' : 'var(--danger)' ?>;">
                        <strong>&#8377; <?= number_format($row['profit'], 2) ?></strong>
                    </td>
                </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr><td colspan="<?= $itemWise ? 9 : 6 ?>" style="text-align:center;padding:40px;color:var(--text-muted);">No data found.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php require_once '../includes/doc_popup_modal.php'; ?>
<?php require_once '../includes/footer.php'; ?>
