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

// Ensure user is logged in
if (!isset($_SESSION['user']['id']) || !isset($_SESSION['user']['shop_id'])) {
    header("Location: ../../auth/login.php");
    exit();
}

$current_shop = $_SESSION['user']['shop_id'];
$current_user_id = $_SESSION['user']['id'];

// Success message handling
$successMessage = '';
if (isset($_GET['added']) && $_GET['added'] == 1) {
    $successMessage = isset($_SESSION['success_message']) ? $_SESSION['success_message'] : 'Purchase added successfully!';
    unset($_SESSION['success_message']);
} elseif (isset($_GET['updated']) && $_GET['updated'] == 1) {
    $successMessage = isset($_SESSION['success_message']) ? $_SESSION['success_message'] : 'Purchase updated successfully!';
    unset($_SESSION['success_message']);
}

// Search functionality
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$dateFrom = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$dateTo = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$supplierId = isset($_GET['supplier_id']) ? intval($_GET['supplier_id']) : 0;

// Build WHERE clause
$whereClause = "WHERE p.shop_id = ?";
$params = [$current_shop];

// Add search conditions
if ($search !== '') {
    $whereClause .= " AND (p.invoice_no LIKE ? OR s.name LIKE ?)";
    $searchTerm = "%{$search}%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

if ($dateFrom !== '') {
    $whereClause .= " AND p.purchase_date >= ?";
    $params[] = $dateFrom;
}

if ($dateTo !== '') {
    $whereClause .= " AND p.purchase_date <= ?";
    $params[] = $dateTo;
}

if ($supplierId > 0) {
    $whereClause .= " AND p.supplier_id = ?";
    $params[] = $supplierId;
}

// Get list of suppliers for filter
$suppliers = $pdo->query("SELECT id, name FROM suppliers ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);

// Pagination settings
$rowsPerPage = 20;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? intval($_GET['page']) : 1;
$page = max(1, $page);
$start = ($page - 1) * $rowsPerPage;

// Count total purchases with filters
$countSql = "SELECT COUNT(*) FROM purchases p LEFT JOIN suppliers s ON p.supplier_id = s.id $whereClause";
$countStmt = $pdo->prepare($countSql);
$countStmt->execute($params);
$totalPurchases = $countStmt->fetchColumn();
$totalPages = ceil($totalPurchases / $rowsPerPage);

// Adjust page if out of bounds
if ($page > $totalPages && $totalPages > 0) {
    $page = $totalPages;
    $start = ($page - 1) * $rowsPerPage;
}

// Fetch purchases with filters and pagination
$sql = "
    SELECT p.*, 
           s.name AS supplier_name, 
           s.contact as supplier_contact,
           u.username AS created_by_name,
           COUNT(pl.id) as item_count,
           COALESCE(SUM(pl.qty), 0) as total_qty
    FROM purchases p
    LEFT JOIN suppliers s ON p.supplier_id = s.id
    LEFT JOIN users u ON p.created_by = u.id
    LEFT JOIN purchase_lines pl ON p.id = pl.purchase_id
    $whereClause
    GROUP BY p.id
    ORDER BY p.purchase_date DESC, p.id DESC
    LIMIT $start, $rowsPerPage
";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$purchases = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate grand totals
$grandTotal = 0;
$grandQty = 0;
foreach ($purchases as $row) {
    $grandTotal += (float)($row['total'] ?? 0);
    $grandQty += (int)($row['total_qty'] ?? 0);
}
?>

<div class="col-md-10 ml-sm-auto px-4 py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="text-primary">
            <i class="fas fa-shopping-cart"></i> Purchases
            <?php if ($totalPurchases > 0): ?>
                <small class="text-muted">(<?= $totalPurchases ?> total)</small>
            <?php endif; ?>
        </h3>
        <div>
            <a href="add_purchase.php" class="btn btn-primary">
                <i class="fas fa-plus"></i> Add Purchase
            </a>
        </div>
    </div>

    <!-- Success Messages -->
    <?php if ($successMessage): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle"></i> <?= htmlspecialchars($successMessage) ?>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    <?php endif; ?>

    <!-- Filter Form -->
    <div class="card mb-4">
        <div class="card-header bg-light">
            <h5 class="mb-0"><i class="fas fa-filter"></i> Filter Purchases</h5>
        </div>
        <div class="card-body">
            <form method="GET" class="row">
                <div class="col-md-3">
                    <div class="form-group">
                        <label>Search</label>
                        <input type="text" name="search" class="form-control" placeholder="Invoice or Supplier" value="<?= htmlspecialchars($search) ?>">
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="form-group">
                        <label>From Date</label>
                        <input type="date" name="date_from" class="form-control" value="<?= htmlspecialchars($dateFrom) ?>">
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="form-group">
                        <label>To Date</label>
                        <input type="date" name="date_to" class="form-control" value="<?= htmlspecialchars($dateTo) ?>">
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label>Supplier</label>
                        <select name="supplier_id" class="form-control">
                            <option value="">All Suppliers</option>
                            <?php foreach ($suppliers as $supplier): ?>
                                <option value="<?= $supplier['id'] ?>" <?= $supplierId == $supplier['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($supplier['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <div class="form-group w-100">
                        <button type="submit" class="btn btn-primary btn-block">
                            <i class="fas fa-search"></i> Filter
                        </button>
                        <?php if ($search || $dateFrom || $dateTo || $supplierId): ?>
                            <a href="list_purchases.php" class="btn btn-secondary btn-block mt-1">
                                <i class="fas fa-times"></i> Clear
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Export & Print Buttons -->
    <div class="mb-3 d-flex justify-content-between align-items-center">
        <div>
            <!--<button class="btn btn-sm btn-outline-info" onclick="exportToCSV()">
                <i class="fas fa-file-csv"></i> Export CSV
            </button> -->
            <button class="btn btn-sm btn-outline-success" onclick="printPurchases()">
                <i class="fas fa-print"></i> Print
            </button>
        </div>
        <div class="text-muted">
            Showing <?= count($purchases) ?> of <?= $totalPurchases ?> purchases
        </div>
    </div>

    <div class="table-responsive">
        <table class="table table-bordered table-hover" id="purchasesTable">
            <thead class="thead-dark">
                <tr>
                    <th class="no-print"><input type="checkbox" id="selectAll"></th>
                    <th>Invoice #</th>
                    <th>Supplier</th>
                    <th>Date</th>
                    <th>Items</th>
                    <th>Qty</th>
                    <th>Amount</th>
                    <th>Created By</th>
                    <th class="no-print">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($purchases)): ?>
                    <tr>
                        <td colspan="9" class="text-center py-4">
                            <i class="fas fa-shopping-cart fa-2x text-muted mb-2 d-block"></i>
                            No purchases found. <?php if ($search || $dateFrom || $dateTo || $supplierId): ?>Try different filters.<?php else: ?>Add your first purchase.<?php endif; ?>
                        </td>
                    </tr>
                <?php else: 
                    foreach ($purchases as $row):
                        $total = (float)($row['total'] ?? 0);
                ?>
                <tr id="row-<?= $row['id'] ?>" class="<?= $row['total'] === null ? 'table-warning' : '' ?>">
                    <td class="no-print"><input type="checkbox" class="selectRow" value="<?= $row['id'] ?>"></td>
                    <td>
                        <strong><?= htmlspecialchars($row['invoice_no']) ?></strong>
                        <br><small class="text-muted">ID: <?= $row['id'] ?></small>
                    </td>
                    <td>
                        <strong><?= htmlspecialchars($row['supplier_name'] ?? 'Unknown') ?></strong>
                        <?php if ($row['supplier_contact']): ?>
                            <br><small class="text-muted"><?= htmlspecialchars($row['supplier_contact']) ?></small>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?= $row['purchase_date'] ? date('d/m/Y', strtotime($row['purchase_date'])) : '-' ?>
                    </td>
                    <td><?= $row['item_count'] ?></td>
                    <td><?= number_format($row['total_qty']) ?></td>
                    <td class="font-weight-bold">
                        TSh <?= number_format($total, 2) ?>
                        <?php if ($row['total'] === null): ?>
                            <br><small class="text-warning"><i class="fas fa-exclamation-triangle"></i> No total</small>
                        <?php endif; ?>
                    </td>
                    <td>
                        <small><?= htmlspecialchars($row['created_by_name'] ?? 'Unknown') ?></small>
                    </td>
                    <td class="no-print">
                     <?php if($_SESSION['user']['role']!='admin')
								{ 
								echo""; // display none for non-admins
								}
								else
								{?>
                        <div class="btn-group btn-group-sm" role="group">
                            <a href="view_purchase.php?id=<?= $row['id'] ?>" 
                               class="btn btn-info" 
                               title="View Details">
                                <i class="fas fa-eye"></i>
                            </a>
                            <a href="edit_purchase.php?id=<?= $row['id'] ?>" 
                               class="btn btn-warning" 
                               title="Edit Purchase">
                                <i class="fas fa-edit"></i>
                            </a>
                            <button class="btn btn-danger" 
                                    onclick="deletePurchase(<?= $row['id'] ?>, '<?= htmlspecialchars(addslashes($row['invoice_no'])) ?>')"
                                    title="Delete Purchase">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                        <?php } ?>
                    </td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
            <tfoot class="table-info">
                <tr>
                    <th colspan="5" class="text-right">Grand Totals:</th>
                    <th><?= number_format($grandQty) ?></th>
                    <th class="font-weight-bold">TSh <?= number_format($grandTotal, 2) ?></th>
                    <th colspan="2"></th>
                </tr>
            </tfoot>
        </table>
    </div>

    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
    <nav aria-label="Purchase pagination">
        <ul class="pagination justify-content-center mt-4">
            <!-- Previous -->
            <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                <a class="page-link" href="?page=<?= $page-1 ?>&search=<?= urlencode($search) ?>&date_from=<?= urlencode($dateFrom) ?>&date_to=<?= urlencode($dateTo) ?>&supplier_id=<?= $supplierId ?>">
                    <i class="fas fa-chevron-left"></i>
                </a>
            </li>
            
            <!-- Page numbers -->
            <?php 
            $startPage = max(1, $page - 2);
            $endPage = min($totalPages, $page + 2);
            
            for($p = $startPage; $p <= $endPage; $p++): ?>
                <li class="page-item <?= $p == $page ? 'active' : '' ?>">
                    <a class="page-link" href="?page=<?= $p ?>&search=<?= urlencode($search) ?>&date_from=<?= urlencode($dateFrom) ?>&date_to=<?= urlencode($dateTo) ?>&supplier_id=<?= $supplierId ?>">
                        <?= $p ?>
                    </a>
                </li>
            <?php endfor; ?>
            
            <!-- Next -->
            <li class="page-item <?= $page >= $totalPages ? 'disabled' : '' ?>">
                <a class="page-link" href="?page=<?= $page+1 ?>&search=<?= urlencode($search) ?>&date_from=<?= urlencode($dateFrom) ?>&date_to=<?= urlencode($dateTo) ?>&supplier_id=<?= $supplierId ?>">
                    <i class="fas fa-chevron-right"></i>
                </a>
            </li>
        </ul>
        <div class="text-center text-muted mt-2">
            Page <?= $page ?> of <?= $totalPages ?>
        </div>
    </nav>
    <?php endif; ?>
</div>

<!-- Toast container -->
<div id="toastContainer" style="position: fixed; top: 20px; right: 20px; z-index: 1050;"></div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// Show toast notification
function showToast(message, type='success', icon='') {
    const icons = {
        'success': 'fa-check-circle',
        'danger': 'fa-exclamation-circle',
        'warning': 'fa-exclamation-triangle',
        'info': 'fa-info-circle'
    };
    
    let toastId = 'toast-' + Date.now();
    let toastHTML = `
        <div id="${toastId}" class="alert alert-${type} alert-dismissible fade show shadow" 
             style="min-width: 300px; margin-bottom: 10px; border-left: 4px solid var(--${type});">
            <div class="d-flex align-items-center">
                <i class="fas ${icon || icons[type] || 'fa-info-circle'} fa-lg mr-2"></i>
                <div class="flex-grow-1">${message}</div>
                <button type="button" class="close ml-2" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        </div>`;
    
    $('#toastContainer').append(toastHTML);
    
    // Auto remove after 4 seconds
    setTimeout(() => {
        $(`#${toastId}`).alert('close');
    }, 4000);
}

// Select all checkbox
document.getElementById('selectAll').addEventListener('change', function() {
    let checked = this.checked;
    document.querySelectorAll('.selectRow').forEach(cb => cb.checked = checked);
});

// Delete purchase via AJAX
function deletePurchase(purchaseId, invoiceNo) {
    if (confirm(`Are you sure you want to delete purchase "${invoiceNo}"? This action cannot be undone.`)) {
        $.ajax({
            url: 'delete_purchase.php',
            type: 'POST',
            data: { 
                id: purchaseId,
                user_id: <?= $current_user_id ?>
            },
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    $(`#row-${purchaseId}`).fadeOut(400, function() { 
                        $(this).remove();
                        // Update totals if needed
                        location.reload();
                    });
                    showToast(response.message, 'success', 'fa-trash');
                } else {
                    showToast(response.message, 'danger');
                }
            },
            error: function(xhr, status, error) {
                console.error("AJAX Error:", error);
                showToast("An error occurred while deleting the purchase.", 'danger');
            }
        });
    }
}

// Export to CSV
function exportToCSV() {
    let csv = [];
    let rows = document.querySelectorAll("#purchasesTable tr");
    
    for (let i = 0; i < rows.length; i++) {
        let row = [], cols = rows[i].querySelectorAll("td, th");
        
        for (let j = 0; j < cols.length - 1; j++) { // Exclude actions column
            // Clean up the content
            let text = cols[j].innerText
                .replace(/(\r\n|\n|\r)/gm, " ")  // Remove line breaks
                .replace(/\s+/g, " ")            // Replace multiple spaces
                .trim();
            
            // Escape quotes and wrap in quotes if contains comma
            if (text.includes(',') || text.includes('"')) {
                text = '"' + text.replace(/"/g, '""') + '"';
            }
            row.push(text);
        }
        
        csv.push(row.join(","));
    }

    // Download CSV file
    let csvContent = "data:text/csv;charset=utf-8," + csv.join("\n");
    let encodedUri = encodeURI(csvContent);
    let link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", `purchases_${new Date().toISOString().split('T')[0]}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    showToast('Purchases exported to CSV file', 'info', 'fa-file-csv');
}

// Print purchases
function printPurchases() {
    let tableClone = document.getElementById('purchasesTable').cloneNode(true);
    
    // Remove actions and checkbox columns
    $(tableClone).find('.no-print').remove();
    
    let newWin = window.open('', '', 'width=1200,height=700');
    newWin.document.write('<html><head><title>Purchases List</title>');
    newWin.document.write('<link rel="stylesheet" href="../libraries/bootstrap.min.css">');
    newWin.document.write('<style>');
    newWin.document.write('body { font-family: Arial, sans-serif; margin: 20px; }');
    newWin.document.write('.header { text-align: center; margin-bottom: 30px; border-bottom: 2px solid #333; padding-bottom: 10px; }');
    newWin.document.write('.header h2 { color: #333; }');
    newWin.document.write('.filter-info { background-color: #f8f9fa; padding: 10px; border-radius: 5px; margin-bottom: 20px; }');
    newWin.document.write('.print-date { text-align: right; color: #666; margin-bottom: 20px; }');
    newWin.document.write('table { width: 100%; border-collapse: collapse; margin-top: 20px; }');
    newWin.document.write('th { background-color: #343a40; color: white; padding: 10px; text-align: left; border: 1px solid #ddd; }');
    newWin.document.write('td { padding: 8px; border: 1px solid #ddd; }');
    newWin.document.write('tr:nth-child(even) { background-color: #f2f2f2; }');
    newWin.document.write('tfoot { background-color: #d1ecf1; font-weight: bold; }');
    newWin.document.write('@media print { .no-print { display: none; } }');
    newWin.document.write('</style>');
    newWin.document.write('</head><body>');
    
    newWin.document.write('<div class="header">');
    newWin.document.write('<h2><i class="fas fa-shopping-cart"></i> Purchases List</h2>');
    newWin.document.write('<p>Shop: <?= $_SESSION['user']['shop_name'] ?? "Current Shop" ?></p>');
    newWin.document.write('</div>');
    
    newWin.document.write('<div class="print-date">');
    newWin.document.write('Printed on: ' + new Date().toLocaleDateString() + ' ' + new Date().toLocaleTimeString());
    newWin.document.write('</div>');
    
    // Filter information
    newWin.document.write('<div class="filter-info">');
    newWin.document.write('<strong>Filters:</strong> ');
    let filterText = [];
    <?php if ($search): ?>filterText.push('Search: <?= htmlspecialchars($search) ?>');<?php endif; ?>
    <?php if ($dateFrom): ?>filterText.push('From: <?= $dateFrom ?>');<?php endif; ?>
    <?php if ($dateTo): ?>filterText.push('To: <?= $dateTo ?>');<?php endif; ?>
    <?php if ($supplierId && $suppliers): 
        foreach ($suppliers as $s):
            if ($s['id'] == $supplierId): ?>
                filterText.push('Supplier: <?= htmlspecialchars($s['name']) ?>');
            <?php endif;
        endforeach;
    endif; ?>
    newWin.document.write(filterText.length > 0 ? filterText.join(' | ') : 'No filters applied');
    newWin.document.write('</div>');
    
    newWin.document.write(tableClone.outerHTML);
    newWin.document.write('</body></html>');
    newWin.document.close();
    
    // Wait for content to load then print
    setTimeout(() => {
        newWin.print();
        newWin.close();
    }, 500);
}

// Real-time search (client-side) for quick filter
$('input[name="search"]').on('keyup', function(e) {
    if (e.key === 'Enter') {
        $(this).closest('form').submit();
    }
});

// Auto-dismiss success alert after 5 seconds
$(document).ready(function() {
    setTimeout(function() {
        $('.alert-success').alert('close');
    }, 5000);
});
</script>

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