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

// Get companies accessible to this user
$role = $_SESSION['user_role'] ?? '';
$uid  = (int)$_SESSION['user_id'];

if ($role === 'admin') {
    $companiesRes = $conn->query("SELECT id, company_name FROM company_master ORDER BY id ASC");
} else {
    $companiesRes = $conn->query("
        SELECT cm.id, cm.company_name
        FROM company_master cm
        JOIN user_companies uc ON uc.company_id = cm.id
        WHERE uc.user_id = $uid
        ORDER BY cm.id ASC
    ");
}
$allCompanies = [];
while ($c = $companiesRes->fetch_assoc()) {
    $allCompanies[] = $c;
}

// Filters
$from      = $_GET['from']      ?? date('Y-m-01');
$to        = $_GET['to']        ?? date('Y-m-d');
$itemWise  = isset($_GET['itemwise']) ? 1 : 0;
$selCo     = isset($_GET['companies']) ? array_map('intval', (array)$_GET['companies']) : array_column($allCompanies, 'id');

// Validate selected companies against accessible list
$accessibleIds = array_column($allCompanies, 'id');
$selCo = array_values(array_filter($selCo, fn($id) => in_array($id, $accessibleIds)));
if (empty($selCo)) $selCo = $accessibleIds;

$rows        = [];
$totalSales  = 0;
$totalCost   = 0;
$totalProfit = 0;
$byCompany   = []; // company_id => [sales, cost, profit]

if (!empty($selCo)) {
    $placeholders = implode(',', array_fill(0, count($selCo), '?'));
    $types = 'ss' . str_repeat('i', count($selCo));
    $params = array_merge([$from, $to], $selCo);

    if ($itemWise) {
        $sql = "
            SELECT si.company_id,
                   cm.company_name,
                   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
            JOIN company_master cm ON cm.id = si.company_id
            WHERE si.invoice_date BETWEEN ? AND ?
              AND si.company_id IN ($placeholders)
              AND si.status = 'final'
            ORDER BY si.company_id ASC, si.id DESC
        ";
    } else {
        $sql = "
            SELECT si.company_id,
                   cm.company_name,
                   si.id,
                   si.invoice_no,
                   si.invoice_date,
                   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
            JOIN company_master cm ON cm.id = si.company_id
            WHERE si.invoice_date BETWEEN ? AND ?
              AND si.company_id IN ($placeholders)
              AND si.status = 'final'
            GROUP BY si.id
            ORDER BY si.company_id ASC, si.id DESC
        ";
    }

    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $cId = $row['company_id'];
        if (!isset($byCompany[$cId])) {
            $byCompany[$cId] = ['name' => $row['company_name'], 'sales' => 0, 'cost' => 0, 'profit' => 0, 'rows' => []];
        }
        if ($itemWise) {
            $rs = $row['selling_price_excl'] * $row['sold_qty'];
            $rc = $row['purchase_price']     * $row['sold_qty'];
        } else {
            $rs = $row['total_sale_excl'];
            $rc = $row['total_cost'];
        }
        $byCompany[$cId]['sales']  += $rs;
        $byCompany[$cId]['cost']   += $rc;
        $byCompany[$cId]['profit'] += $row['profit'];
        $byCompany[$cId]['rows'][] = $row;
        $totalSales  += $rs;
        $totalCost   += $rc;
        $totalProfit += $row['profit'];
    }
}
?>

<div class="page-header">
    <h2><i class="fas fa-layer-group" style="color:#7c3aed;margin-right:8px;"></i>Consolidated Profit Report</h2>
    <a href="index.php" class="btn btn-outline btn-sm"><i class="fas fa-arrow-left"></i> Reports</a>
</div>

<!-- Filters -->
<div class="panel" style="margin-bottom:16px;">
    <div class="panel-body" style="padding:16px;">
        <form method="GET" id="filterForm">
            <div style="display:flex;flex-wrap:wrap;gap:16px;align-items:flex-end;">
                <div class="form-group" style="margin:0;min-width:140px;">
                    <label>From</label>
                    <input type="date" name="from" value="<?= htmlspecialchars($from) ?>">
                </div>
                <div class="form-group" style="margin:0;min-width:140px;">
                    <label>To</label>
                    <input type="date" name="to" value="<?= htmlspecialchars($to) ?>">
                </div>
                <div class="form-group" style="margin:0;">
                    <label>Companies</label>
                    <div style="display:flex;flex-wrap:wrap;gap:8px;margin-top:4px;">
                        <?php foreach ($allCompanies as $co): ?>
                        <label style="display:flex;align-items:center;gap:5px;font-weight:400;font-size:13px;cursor:pointer;background:#f1f5f9;padding:4px 10px;border-radius:20px;border:1px solid #e2e8f0;">
                            <input type="checkbox" name="companies[]" value="<?= $co['id'] ?>"
                                   <?= in_array($co['id'], $selCo) ? 'checked' : '' ?>
                                   style="width:auto;accent-color:#7c3aed;">
                            <?= htmlspecialchars($co['company_name']) ?>
                        </label>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div class="form-group" style="margin:0;">
                    <label style="display:flex;align-items:center;gap:6px;font-weight:400;cursor:pointer;margin-top:20px;">
                        <input type="checkbox" name="itemwise" value="1" <?= $itemWise ? 'checked' : '' ?> style="width:auto;accent-color:#7c3aed;">
                        Item Wise
                    </label>
                </div>
                <div style="display:flex;gap:8px;align-items:flex-end;">
                    <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Generate</button>
                    <a href="consolidated_profit.php" class="btn btn-secondary">Reset</a>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Grand Summary -->
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:12px;margin-bottom:16px;">
    <div class="stat-card">
        <div class="stat-card-label">Total Sales (Excl GST)</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">Overall Margin</div>
        <div class="stat-card-value" style="color:#7c3aed;"><?= number_format(($totalProfit / $totalSales) * 100, 1) ?>%</div>
    </div>
    <?php endif; ?>
</div>

<?php if (count($allCompanies) > 1 && !empty($byCompany)): ?>
<!-- Company-wise summary bar -->
<div class="panel" style="margin-bottom:16px;">
    <div class="panel-header"><span class="panel-title">Company-wise Summary</span></div>
    <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>Company</th>
                    <th style="text-align:right;">Sales (Excl GST)</th>
                    <th style="text-align:right;">Cost</th>
                    <th style="text-align:right;">Profit</th>
                    <th style="text-align:right;">Margin %</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($byCompany as $cId => $cd): ?>
            <tr>
                <td style="font-weight:600;"><?= htmlspecialchars($cd['name']) ?></td>
                <td style="text-align:right;">&#8377; <?= number_format($cd['sales'], 2) ?></td>
                <td style="text-align:right;">&#8377; <?= number_format($cd['cost'], 2) ?></td>
                <td style="text-align:right;color:<?= $cd['profit'] >= 0 ? 'var(--success)' : 'var(--danger)' ?>;">
                    <strong>&#8377; <?= number_format($cd['profit'], 2) ?></strong>
                </td>
                <td style="text-align:right;color:#7c3aed;">
                    <?= $cd['sales'] > 0 ? number_format(($cd['profit'] / $cd['sales']) * 100, 1) . '%' : '—' ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr style="font-weight:700;background:#f8fafc;border-top:2px solid #e2e8f0;">
                    <td>Grand Total</td>
                    <td style="text-align:right;">&#8377; <?= number_format($totalSales, 2) ?></td>
                    <td style="text-align:right;">&#8377; <?= number_format($totalCost, 2) ?></td>
                    <td style="text-align:right;color:<?= $totalProfit >= 0 ? 'var(--success)' : 'var(--danger)' ?>;">&#8377; <?= number_format($totalProfit, 2) ?></td>
                    <td style="text-align:right;color:#7c3aed;"><?= $totalSales > 0 ? number_format(($totalProfit / $totalSales) * 100, 1) . '%' : '—' ?></td>
                </tr>
            </tfoot>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- Detailed data per company -->
<?php if (empty($byCompany)): ?>
<div class="panel">
    <div style="text-align:center;padding:48px;color:var(--text-muted);">
        <i class="fas fa-chart-bar" style="font-size:36px;margin-bottom:12px;display:block;opacity:.3;"></i>
        No data found for the selected filters.
    </div>
</div>
<?php else: ?>
<?php foreach ($byCompany as $cId => $cd): ?>
<div class="panel" style="margin-bottom:16px;">
    <div class="panel-header" style="background:linear-gradient(90deg,#eff6ff,#f8fafc);">
        <span class="panel-title" style="color:#2563eb;">
            <i class="fas fa-building" style="margin-right:6px;"></i><?= htmlspecialchars($cd['name']) ?>
        </span>
        <span style="font-size:12px;color:var(--text-muted);margin-left:12px;">
            Sales: <strong style="color:var(--primary);">&#8377; <?= number_format($cd['sales'], 2) ?></strong>
            &nbsp;|&nbsp; Cost: <strong style="color:var(--danger);">&#8377; <?= number_format($cd['cost'], 2) ?></strong>
            &nbsp;|&nbsp; Profit: <strong style="color:<?= $cd['profit'] >= 0 ? 'var(--success)' : 'var(--danger)' ?>;">&#8377; <?= number_format($cd['profit'], 2) ?></strong>
        </span>
    </div>
    <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;">Sales (Excl GST)</th>
                    <th style="text-align:right;">Cost</th>
                    <th style="text-align:right;">Profit</th>
                </tr>
                <?php endif; ?>
            </thead>
            <tbody>
            <?php foreach ($cd['rows'] as $row): ?>
            <tr>
                <td style="font-weight:600;color:var(--primary);"><?= htmlspecialchars($row['invoice_no']) ?></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; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endforeach; ?>
<?php endif; ?>

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