<?php session_start();
include('../includes/header.php'); 
include('../includes/sidebar.php'); 
include('../assets/db_connect.php');

// Allow only admins
if (!isset($_SESSION['user']) || $_SESSION['user']['role'] != 'admin') {
    die("Access denied. Admin only.");
}

// Default date range: last 30 days
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d', strtotime('-30 days'));
$end_date   = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');

// Fetch supplier ID if provided
$supplier_id = isset($_GET['supplier_id']) ? (int)$_GET['supplier_id'] : 0;

// Prepare SQL
$sql = "
    SELECT 
        s.name AS supplier_name,
        p.name AS product_name,
        pb.batch_no,
        pl.qty,
        pl.cost_price,
        pl.qty * pl.cost_price AS line_total,
        pu.invoice_no,
        pu.purchase_date
    FROM purchase_lines pl
    JOIN product_batches pb ON pb.id = pl.batch_id
    JOIN products p ON p.id = pb.product_id
    JOIN purchases pu ON pu.id = pl.purchase_id
    JOIN suppliers s ON s.id = pu.supplier_id
    WHERE pu.purchase_date BETWEEN :start_date AND :end_date
";

if ($supplier_id > 0) {
    $sql .= " AND s.id = :supplier_id";
}

$sql .= " ORDER BY pu.purchase_date ASC";

$stmt = $pdo->prepare($sql);
$stmt->bindParam(':start_date', $start_date);
$stmt->bindParam(':end_date', $end_date);
if ($supplier_id > 0) {
    $stmt->bindParam(':supplier_id', $supplier_id, PDO::PARAM_INT);
}
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
/* Back button styling - consistent with other pages */
.back-btn {
    display: inline-block;
    padding: 8px 16px;
    background-color: #6c757d;
    color: white;
    text-decoration: none;
    border-radius: 4px;
    border: none;
    cursor: pointer;
    font-size: 14px;
    margin-bottom: 15px;
    transition: background-color 0.2s;
}
.back-btn:hover {
    background-color: #5a6268;
    color: white;
    text-decoration: none;
}
.back-btn i {
    margin-right: 5px;
}
/* Print-only styling */
@media print {
    .no-print, .back-btn {
        display: none !important;
    }
    body { padding: 20px !important; }
    .card { border: none !important; box-shadow: none !important; }
    .card-header { background-color: #f8f9fa !important; color: #000 !important; }
}
</style>

<div class="content-wrapper main-content-wrapper">
    <div class="container-fluid mt-3">
        
        <!-- BACK BUTTON at the top -->
        <div class="mb-3 no-print">
            <a href="daily_sales.php" class="back-btn">
                <i>←</i> Back to Reports
            </a>
        </div>
        
        <div class="card">
            <div class="card-header bg-info text-white d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Supplier Statement</h5>
                <div class="btn-group">
                    <button class="btn btn-light btn-sm mr-2 no-print" onclick="window.print()">Print</button>
                    <button class="btn btn-warning btn-sm no-print" onclick="exportToExcel()">Export Excel</button>
                </div>
            </div>
            <div class="card-body">
                
                <form class="form-inline mb-3 no-print">
                    <label class="mr-2">Start Date:</label>
                    <input type="date" name="start_date" class="form-control mr-3" value="<?= $start_date ?>">
                    <label class="mr-2">End Date:</label>
                    <input type="date" name="end_date" class="form-control mr-3" value="<?= $end_date ?>">
                    <label class="mr-2">Supplier:</label>
                    <select name="supplier_id" class="form-control mr-2">
                        <option value="0">All Suppliers</option>
                        <?php
                        $suppliers = $pdo->query("SELECT * FROM suppliers ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);
                        foreach ($suppliers as $s) {
                            $selected = ($s['id'] == $supplier_id) ? "selected" : "";
                            echo "<option value='{$s['id']}' $selected>{$s['name']}</option>";
                        }
                        ?>
                    </select>
                    <button type="submit" class="btn btn-primary btn-sm">Filter</button>
                </form>

                <!-- Summary cards -->
                <?php if ($data): 
                    $total_qty = 0;
                    $total_amount = 0;
                    $supplier_total = [];
                    
                    foreach ($data as $row) {
                        $total_qty += $row['qty'];
                        $total_amount += $row['line_total'];
                        
                        // Track supplier totals
                        $supplier_name = $row['supplier_name'];
                        if (!isset($supplier_total[$supplier_name])) {
                            $supplier_total[$supplier_name] = 0;
                        }
                        $supplier_total[$supplier_name] += $row['line_total'];
                    }
                ?>
                <div class="row mb-4 no-print">
                    <div class="col-md-3">
                        <div class="card text-white bg-primary">
                            <div class="card-body p-2">
                                <h6 class="card-title mb-1">Total Items</h6>
                                <p class="card-text h4 mb-0"><?= count($data) ?></p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card text-white bg-info">
                            <div class="card-body p-2">
                                <h6 class="card-title mb-1">Total Quantity</h6>
                                <p class="card-text h4 mb-0"><?= number_format($total_qty) ?></p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card text-white bg-success">
                            <div class="card-body p-2">
                                <h6 class="card-title mb-1">Total Amount</h6>
                                <p class="card-text h4 mb-0"><?= number_format($total_amount, 2) ?></p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card text-white bg-secondary">
                            <div class="card-body p-2">
                                <h6 class="card-title mb-1">Suppliers</h6>
                                <p class="card-text h4 mb-0"><?= count($supplier_total) ?></p>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Report header for print -->
                <div class="text-center mb-3 d-none d-print-block">
                    <h4>Supplier Statement</h4>
                    <p><strong>Date Range:</strong> <?= date('d-M-Y', strtotime($start_date)) ?> to <?= date('d-M-Y', strtotime($end_date)) ?></p>
                    <?php if ($supplier_id > 0): 
                        $supplier_name = $pdo->prepare("SELECT name FROM suppliers WHERE id = ?");
                        $supplier_name->execute([$supplier_id]);
                        $supplier = $supplier_name->fetch();
                    ?>
                    <p><strong>Supplier:</strong> <?= htmlspecialchars($supplier['name'] ?? '') ?></p>
                    <?php else: ?>
                    <p><strong>All Suppliers</strong></p>
                    <?php endif; ?>
                    <p><strong>Generated on:</strong> <?= date('d-M-Y H:i:s') ?></p>
                </div>

                <div class="table-responsive">
                    <table class="table table-bordered table-hover table-sm" id="supplierTable">
                        <thead class="thead-dark">
                            <tr>
                                <th>#</th>
                                <th>Supplier</th>
                                <th>Product</th>
                                <th>Batch No</th>
                                <th>Qty</th>
                                <th>Cost Price</th>
                                <th>Line Total</th>
                                <th>Invoice No</th>
                                <th>Purchase Date</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$data): ?>
                                <tr>
                                    <td colspan="9" class="text-center text-muted">No purchases found for this range.</td>
                                </tr>
                            <?php else: ?>
                                <?php 
                                $i = 0;
                                $current_supplier = '';
                                foreach ($data as $row): 
                                    $i++;
                                    // Check if supplier changed
                                    if ($current_supplier != $row['supplier_name']) {
                                        $current_supplier = $row['supplier_name'];
                                        // Calculate supplier total
                                        $supplier_sum = 0;
                                        foreach ($data as $d) {
                                            if ($d['supplier_name'] == $current_supplier) {
                                                $supplier_sum += $d['line_total'];
                                            }
                                        }
                                ?>
                                <tr class="table-info">
                                    <td colspan="8" class="font-weight-bold">
                                        <?= htmlspecialchars($current_supplier) ?> - Total: <?= number_format($supplier_sum, 2) ?>
                                    </td>
                                    <td></td>
                                </tr>
                                <?php } ?>
                                <tr>
                                    <td><?= $i ?></td>
                                    <td><?= htmlspecialchars($row['supplier_name']) ?></td>
                                    <td><?= htmlspecialchars($row['product_name']) ?></td>
                                    <td><?= htmlspecialchars($row['batch_no']) ?></td>
                                    <td><?= $row['qty'] ?></td>
                                    <td><?= number_format($row['cost_price'],2) ?></td>
                                    <td><?= number_format($row['line_total'],2) ?></td>
                                    <td><?= htmlspecialchars($row['invoice_no']) ?></td>
                                    <td><?= date('Y-m-d', strtotime($row['purchase_date'])) ?></td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                        <?php if ($data): ?>
                        <tfoot class="table-secondary">
                            <tr>
                                <td colspan="4" class="text-right"><strong>Totals:</strong></td>
                                <td><strong><?= number_format($total_qty) ?></strong></td>
                                <td></td>
                                <td><strong><?= number_format($total_amount, 2) ?></strong></td>
                                <td colspan="2"></td>
                            </tr>
                        </tfoot>
                        <?php endif; ?>
                    </table>
                </div>

            </div>
        </div>
        
        <!-- BACK BUTTON at the bottom -->
        <div class="mt-4 mb-4 no-print">
            <a href="daily_sales.php" class="back-btn">
                <i>←</i> Back to Reports
            </a>
        </div>

    </div>
</div>

<script>
function exportToExcel() {
    // Create a table clone
    var table = document.getElementById('supplierTable');
    var tableHTML = table.outerHTML;
    
    // Create a Blob with the table data
    var blob = new Blob([tableHTML], {
        type: 'application/vnd.ms-excel'
    });
    
    // Create a temporary anchor element
    var a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = 'supplier_statement_<?= $start_date ?>_<?= $end_date ?>.xls';
    a.click();
    
    // Clean up
    URL.revokeObjectURL(a.href);
}

// Enhanced print function
function printReport() {
    window.print();
}
</script>

<?php include('../includes/footer.php'); ?>