<?php
session_start();
require_once '../assets/db_connect.php';

/* ==========================
   AUTH
========================== */
if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'admin') {
    exit('Access denied');
}

/* ==========================
   FILTERS
========================== */
$from = $_GET['from'] ?? date('Y-m-01');
$to   = $_GET['to']   ?? date('Y-m-d');

$sqlBase = "
    SELECT p.*, s.name AS supplier_name
    FROM purchases p
    LEFT JOIN suppliers s ON s.id = p.supplier_id
    WHERE DATE(p.purchase_date) BETWEEN ? AND ?
";
$params = [$from, $to];

/* ==========================
   EXPORT CSV
========================== */
if (isset($_GET['action']) && $_GET['action'] === 'csv') {
    $stmt = $pdo->prepare($sqlBase . " ORDER BY p.purchase_date DESC");
    $stmt->execute($params);

    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename=purchases_'.$from.'_'.$to.'.csv');

    $out = fopen('php://output', 'w');
    fputcsv($out, ['ID','Invoice','Date','Supplier','Total']);

    while ($r = $stmt->fetch(PDO::FETCH_ASSOC)) {
        fputcsv($out, [
            $r['id'],
            $r['invoice_no'],
            $r['purchase_date'],
            $r['supplier_name'],
            $r['total'] !== null ? number_format($r['total'], 2) : '0.00'
        ]);
    }
    fclose($out);
    exit;
}

/* ==========================
   PRINT FULL LIST
========================== */
if (isset($_GET['action']) && $_GET['action'] === 'print_full') {
    $stmt = $pdo->prepare($sqlBase . " ORDER BY p.purchase_date DESC");
    $stmt->execute($params);
?>
<!DOCTYPE html>
<html>
<head>
    <title>Print Purchases</title>
    <link rel="stylesheet" href="../libraries/bootstrap.css">
</head>
<body onload="window.print()">
<div class="container mt-3">
    <h4 class="text-center mb-3">
        Purchases from <?= htmlspecialchars($from) ?> to <?= htmlspecialchars($to) ?>
    </h4>
    <table class="table table-bordered table-sm">
        <thead>
        <tr>
            <th>ID</th><th>Invoice</th><th>Date</th><th>Supplier</th><th>Total</th>
        </tr>
        </thead>
        <tbody>
        <?php while ($r = $stmt->fetch(PDO::FETCH_ASSOC)): ?>
            <tr>
                <td><?= $r['id'] ?></td>
                <td><?= htmlspecialchars($r['invoice_no']) ?></td>
                <td><?= $r['purchase_date'] ?></td>
                <td><?= htmlspecialchars($r['supplier_name']) ?></td>
                <td><?= $r['total'] !== null ? number_format($r['total'], 2) : '0.00' ?></td>
            </tr>
        <?php endwhile; ?>
        </tbody>
    </table>
</div>
</body>
</html>
<?php
    exit;
}

/* ==========================
   NORMAL PAGE
========================== */
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

/* PAGINATION */
$limit = 20;
$page = max(1, (int)($_GET['page'] ?? 1));
$offset = ($page - 1) * $limit;

$totalStmt = $pdo->prepare($sqlBase);
$totalStmt->execute($params);
$totalRows  = $totalStmt->rowCount();
$totalPages = ceil($totalRows / $limit);

$stmt = $pdo->prepare(
    $sqlBase . " ORDER BY p.purchase_date DESC LIMIT $limit OFFSET $offset"
);
$stmt->execute($params);
$rows = $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, .btn-group, .pagination {
        display: none !important;
    }
}
</style>

<div class="col-md-10 ml-sm-auto px-4 py-4">

<!-- 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>

<h3 class="text-success">Purchases Between Dates</h3>

<!-- FILTER -->
<form method="get" class="form-inline mb-3 no-print">
    <input type="date" name="from" value="<?= $from ?>" class="form-control mr-2">
    <input type="date" name="to" value="<?= $to ?>" class="form-control mr-2">
    <button class="btn btn-primary mr-2">Filter</button>
</form>

<!-- EXPORT / PRINT BUTTONS - NO DROPDOWN -->
<div class="mb-3 no-print">
    <div class="btn-group">
        <a href="?from=<?= $from ?>&to=<?= $to ?>&action=csv" 
           class="btn btn-outline-primary">
           Export CSV
        </a>
        <a href="?from=<?= $from ?>&to=<?= $to ?>&action=print_full" 
           target="_blank"
           class="btn btn-outline-primary">
           Print Full List
        </a>
        <button type="button" class="btn btn-outline-primary" onclick="printCurrentPage()">
           Print Current Page
        </button>
        <button type="button" class="btn btn-outline-primary" onclick="printSelectedRows()">
           Print Selected Rows
        </button>
    </div>
</div>

<div class="table-responsive">
<table class="table table-bordered table-sm" id="purchaseTable">
<thead>
<tr>
    <th class="no-print"><input type="checkbox" id="checkAll"></th>
    <th>ID</th><th>Invoice</th><th>Date</th><th>Supplier</th><th>Total</th>
</tr>
</thead>
<tbody>
<?php 
$total_amount = 0;
foreach ($rows as $r): 
    $total_amount += $r['total'] ?? 0;
?>
<tr>
    <td class="no-print"><input type="checkbox" class="rowCheck" value="<?= $r['id'] ?>"></td>
    <td><?= $r['id'] ?></td>
    <td><?= htmlspecialchars($r['invoice_no']) ?></td>
    <td><?= date('d-M-Y', strtotime($r['purchase_date'])) ?></td>
    <td><?= htmlspecialchars($r['supplier_name']) ?></td>
    <td><?= $r['total'] !== null ? number_format($r['total'], 2) : '0.00' ?></td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
    <tr class="table-secondary">
        <td class="no-print"></td>
        <td colspan="4" class="text-right"><strong>Page Total:</strong></td>
        <td><strong><?= number_format($total_amount, 2) ?></strong></td>
    </tr>
</tfoot>
</table>
</div>

<!-- PAGINATION -->
<nav class="no-print">
<ul class="pagination">
<?php for ($i=1; $i<=$totalPages; $i++): ?>
<li class="page-item <?= $i==$page?'active':'' ?>">
    <a class="page-link"
       href="?from=<?= $from ?>&to=<?= $to ?>&page=<?= $i ?>">
       <?= $i ?>
    </a>
</li>
<?php endfor; ?>
</ul>
</nav>

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

</div>

<script>
// Check/Uncheck all functionality
document.getElementById('checkAll').addEventListener('click', function() {
    var checkboxes = document.querySelectorAll('.rowCheck');
    for(var i=0; i<checkboxes.length; i++) {
        checkboxes[i].checked = this.checked;
    }
});

function printCurrentPage() {
    // Get the current page table HTML
    var table = document.getElementById('purchaseTable');
    
    // Remove checkboxes and no-print elements from the table clone
    var tempDiv = document.createElement('div');
    tempDiv.innerHTML = table.outerHTML;
    var tempTable = tempDiv.firstChild;
    
    // Remove all no-print elements from the cloned table
    var noPrintElements = tempTable.querySelectorAll('.no-print');
    for(var i=0; i<noPrintElements.length; i++) {
        noPrintElements[i].parentNode.removeChild(noPrintElements[i]);
    }
    
    // Create a new window for printing
    var printWindow = window.open('', '_blank', 'width=900,height=650');
    
    var htmlContent = `
        <!DOCTYPE html>
        <html>
        <head>
            <title>Purchases Report - Page <?= $page ?></title>
            <link rel="stylesheet" href="../libraries/bootstrap.css">
            <style>
                body { padding: 20px; font-family: Arial, sans-serif; }
                h3 { text-align: center; margin-bottom: 20px; }
                .report-info { 
                    text-align: center; 
                    margin-bottom: 20px;
                    color: #666;
                }
                .btn-container { 
                    text-align: center; 
                    margin-top: 20px;
                }
                @media print {
                    .btn-container { display: none; }
                }
            </style>
        </head>
        <body>
            <h3>Purchases Report</h3>
            <div class="report-info">
                <p>Date Range: <?= htmlspecialchars($from) ?> to <?= htmlspecialchars($to) ?></p>
                <p>Page: <?= $page ?> of <?= $totalPages ?></p>
                <p>Generated on: <?= date('Y-m-d H:i:s') ?></p>
            </div>
            ${tempTable.outerHTML}
            <div class="btn-container">
                <button onclick="window.print()" class="btn btn-primary">Print</button>
                <button onclick="window.close()" class="btn btn-secondary">Close</button>
            </div>
            <script>
                window.onload = function() {
                    window.focus();
                };
            <\/script>
        </body>
        </html>
    `;
    
    printWindow.document.open();
    printWindow.document.write(htmlContent);
    printWindow.document.close();
}

function printSelectedRows() {
    // Get selected rows
    var checkboxes = document.querySelectorAll('.rowCheck:checked');
    
    if(checkboxes.length === 0) {
        alert('Please select at least one row to print.');
        return;
    }
    
    // Get the table header
    var table = document.getElementById('purchaseTable');
    var thead = table.querySelector('thead');
    
    // Create new table HTML
    var tableHtml = '<table class="table table-bordered table-sm"><thead><tr>';
    
    // Add table headers (skip checkbox column)
    var headerCells = thead.querySelectorAll('th');
    var selectedTotal = 0;
    
    // Start from index 1 to skip checkbox column
    for(var i=1; i<headerCells.length; i++) {
        tableHtml += '<th>' + headerCells[i].textContent + '</th>';
    }
    
    tableHtml += '</tr></thead><tbody>';
    
    // Add selected rows (without checkboxes)
    for(var i=0; i<checkboxes.length; i++) {
        var row = checkboxes[i].closest('tr');
        var cells = row.querySelectorAll('td');
        tableHtml += '<tr>';
        
        // Calculate total for selected rows
        var rowTotal = parseFloat(cells[5].textContent.replace(/,/g, '')) || 0;
        selectedTotal += rowTotal;
        
        // Start from index 1 to skip checkbox cell
        for(var j=1; j<cells.length; j++) {
            tableHtml += '<td>' + cells[j].innerHTML + '</td>';
        }
        tableHtml += '</tr>';
    }
    
    tableHtml += '</tbody>';
    
    // Add totals row
    tableHtml += '<tfoot><tr class="table-secondary">';
    tableHtml += '<td colspan="4" class="text-right"><strong>Selected Total:</strong></td>';
    tableHtml += '<td><strong>' + selectedTotal.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,') + '</strong></td>';
    tableHtml += '</tr></tfoot>';
    tableHtml += '</table>';
    
    // Create a new window for printing
    var printWindow = window.open('', '_blank', 'width=900,height=650');
    
    var htmlContent = `
        <!DOCTYPE html>
        <html>
        <head>
            <title>Selected Purchases Report</title>
            <link rel="stylesheet" href="../libraries/bootstrap.css">
            <style>
                body { padding: 20px; font-family: Arial, sans-serif; }
                h3 { text-align: center; margin-bottom: 20px; }
                .report-info { 
                    text-align: center; 
                    margin-bottom: 20px;
                    color: #666;
                }
                .btn-container { 
                    text-align: center; 
                    margin-top: 20px;
                }
                @media print {
                    .btn-container { display: none; }
                }
            </style>
        </head>
        <body>
            <h3>Selected Purchases Report</h3>
            <div class="report-info">
                <p>Date Range: <?= htmlspecialchars($from) ?> to <?= htmlspecialchars($to) ?></p>
                <p>Total Selected: ${checkboxes.length} items</p>
                <p>Generated on: <?= date('Y-m-d H:i:s') ?></p>
            </div>
            ${tableHtml}
            <div class="btn-container">
                <button onclick="window.print()" class="btn btn-primary">Print</button>
                <button onclick="window.close()" class="btn btn-secondary">Close</button>
            </div>
            <script>
                window.onload = function() {
                    window.focus();
                };
            <\/script>
        </body>
        </html>
    `;
    
    printWindow.document.open();
    printWindow.document.write(htmlContent);
    printWindow.document.close();
}
</script>

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