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

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

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

// Search functionality
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$whereClause = '';
$params = [];

if ($search !== '') {
    $whereClause = "WHERE name LIKE ? OR email LIKE ? OR contact LIKE ? OR address LIKE ?";
    $searchTerm = "%{$search}%";
    $params = array_fill(0, 4, $searchTerm);
}

// Pagination settings
$limit = 20;
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $limit;

// Fetch total suppliers for pagination with search
$sqlTotal = "SELECT COUNT(*) FROM suppliers " . $whereClause;
$stmtTotal = $pdo->prepare($sqlTotal);
$stmtTotal->execute($params);
$totalSuppliers = (int)$stmtTotal->fetchColumn();
$totalPages = ceil($totalSuppliers / $limit);

// Fetch suppliers with search and pagination
$sql = "SELECT * FROM suppliers " . $whereClause . " ORDER BY id DESC LIMIT ? OFFSET ?";
$stmt = $pdo->prepare($sql);

// Bind parameters dynamically
$paramIndex = 0;
foreach ($params as $param) {
    $stmt->bindValue(++$paramIndex, $param, PDO::PARAM_STR);
}
$stmt->bindValue(++$paramIndex, $limit, PDO::PARAM_INT);
$stmt->bindValue(++$paramIndex, $offset, PDO::PARAM_INT);

$stmt->execute();
$suppliers = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="col-md-10 ml-sm-auto px-4 py-4 main-content-wrapper">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="text-primary">
            <i class="fas fa-truck"></i> Suppliers
            <?php if ($totalSuppliers > 0): ?>
                <small class="text-muted">(<?= $totalSuppliers ?> total)</small>
            <?php endif; ?>
        </h3>
        <div>
            <a href="add_supplier.php" class="btn btn-primary">
                <i class="fas fa-plus"></i> Add Supplier
            </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; ?>

    <!-- Search Form -->
    <form method="GET" class="mb-4" id="searchForm">
        <div class="input-group">
            <input type="text" 
                   name="search" 
                   class="form-control" 
                   placeholder="Search by name, email, phone, or address..."
                   value="<?= htmlspecialchars($search) ?>">
            <div class="input-group-append">
                <button class="btn btn-outline-primary" type="submit">
                    <i class="fas fa-search"></i> Search
                </button>
                <?php if ($search): ?>
                    <a href="supplier_list.php" class="btn btn-outline-secondary">
                        <i class="fas fa-times"></i> Clear
                    </a>
                <?php endif; ?>
            </div>
        </div>
    </form>

    <!-- Export Buttons -->
    <div class="mb-3 d-flex justify-content-between">
        <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="printSuppliers()">
                <i class="fas fa-print"></i> Print
            </button>
        </div>
        <div class="text-muted">
            Showing <?= count($suppliers) ?> of <?= $totalSuppliers ?> suppliers
        </div>
    </div>

    <div class="table-responsive">
        <table class="table table-bordered table-hover" id="supplierTable">
            <thead class="thead-dark">
                <tr>
                    <th>#</th>
                    <th>Name</th>
                    <th>Contact</th>
                    <th>Email</th>
                    <th>Address</th>
                    <th>Created</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($suppliers)): ?>
                    <tr>
                        <td colspan="7" class="text-center py-4">
                            <i class="fas fa-info-circle fa-2x text-muted mb-2 d-block"></i>
                            No suppliers found. <?php if ($search): ?>Try a different search term.<?php else: ?>Add your first supplier.<?php endif; ?>
                        </td>
                    </tr>
                <?php else: 
                    $counter = $offset + 1;
                    foreach ($suppliers as $supplier): 
                        // Check if supplier has purchases
                        $hasPurchases = false;
                        $purchaseCount = 0;
                        $purchaseAmount = 0;
                        
                        $checkStmt = $pdo->prepare("
                            SELECT COUNT(*) as purchase_count, 
                                   COALESCE(SUM(total), 0) as total_amount 
                            FROM purchases 
                            WHERE supplier_id = ?
                        ");
                        $checkStmt->execute([$supplier['id']]);
                        $purchaseData = $checkStmt->fetch(PDO::FETCH_ASSOC);
                        
                        if ($purchaseData) {
                            $purchaseCount = $purchaseData['purchase_count'];
                            $purchaseAmount = $purchaseData['total_amount'];
                            $hasPurchases = $purchaseCount > 0;
                        }
                ?>
                    <tr id="row-<?= $supplier['id'] ?>">
                        <td><?= $counter++ ?></td>
                        <td class="font-weight-bold">
                            <i class="fas fa-truck mr-2 text-primary"></i>
                            <?= htmlspecialchars($supplier['name']) ?>
                            <?php if ($hasPurchases): ?>
                                <span class="badge badge-info" title="<?= $purchaseCount ?> purchase(s)">
                                    <i class="fas fa-shopping-cart"></i> <?= $purchaseCount ?>
                                </span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($supplier['contact']): ?>
                                <i class="fas fa-phone mr-1 text-success"></i>
                                <?= htmlspecialchars($supplier['contact']) ?>
                            <?php else: ?>
                                <span class="text-muted">-</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($supplier['email']): ?>
                                <a href="mailto:<?= htmlspecialchars($supplier['email']) ?>" class="text-info">
                                    <i class="fas fa-envelope mr-1"></i>
                                    <?= htmlspecialchars($supplier['email']) ?>
                                </a>
                            <?php else: ?>
                                <span class="text-muted">-</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($supplier['address']): ?>
                                <small><?= nl2br(htmlspecialchars($supplier['address'])) ?></small>
                            <?php else: ?>
                                <span class="text-muted">-</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <small class="text-muted">
                                <?= date('d/m/Y', strtotime($supplier['created_at'])) ?>
                            </small>
                        </td>
                        <td>
                            <div class="btn-group btn-group-sm" role="group">
                                <a href="edit_supplier.php?id=<?= $supplier['id'] ?>" 
                                   class="btn btn-warning" 
                                   title="Edit Supplier">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <button class="btn btn-danger" 
                                        onclick="deleteSupplier(<?= $supplier['id'] ?>, '<?= htmlspecialchars(addslashes($supplier['name'])) ?>', <?= $hasPurchases ? 'true' : 'false' ?>)"
                                        title="Delete Supplier">
                                    <i class="fas fa-trash"></i>
                                </button>
                                <?php if ($hasPurchases): ?>
                                    <a href="../purchases/supplier_purchases.php?supplier_id=<?= $supplier['id'] ?>" 
                                       class="btn btn-info" 
                                       title="View Purchase History (<?= $purchaseCount ?> purchases, TSh <?= number_format($purchaseAmount, 2) ?>)">
                                        <i class="fas fa-shopping-cart"></i>
                                    </a>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
    <nav aria-label="Supplier 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) ?>">
                    <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) ?>">
                        <?= $p ?>
                    </a>
                </li>
            <?php endfor; ?>
            
            <!-- Next -->
            <li class="page-item <?= $page >= $totalPages ? 'disabled' : '' ?>">
                <a class="page-link" href="?page=<?= $page+1 ?>&search=<?= urlencode($search) ?>">
                    <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);
}

// Delete supplier via AJAX
function deleteSupplier(id, name, hasPurchases) {
    if (hasPurchases) {
        showToast(
            `Cannot delete "${name}" because they have purchase records. <a href="../purchases/supplier_purchases.php?supplier_id=${id}" class="alert-link">View purchases</a>`,
            'danger',
            'fa-shopping-cart'
        );
        return;
    }
    
    if (confirm(`Are you sure you want to delete "${name}"? This action cannot be undone.`)) {
        $.ajax({
            url: 'delete_supplier.php',
            type: 'POST',
            data: {id: id},
            dataType: 'json',
            success: function(res) {
                if (res.status === 'success') {
                    $(`#row-${id}`).fadeOut(400, function() { 
                        $(this).remove();
                        // Update counter
                        updateRowNumbers();
                    });
                    showToast(res.message, 'success', 'fa-trash');
                } else {
                    showToast(res.message, 'danger');
                }
            },
            error: function(xhr, status, error) {
                showToast("An error occurred: " + error, 'danger');
            }
        });
    }
}

// Update row numbers after deletion
function updateRowNumbers() {
    $('table tbody tr').each(function(index) {
        $(this).find('td:first').text(index + 1);
    });
}

// Export to CSV
function exportToCSV() {
    let csv = [];
    let rows = document.querySelectorAll("#supplierTable 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", `suppliers_${new Date().toISOString().split('T')[0]}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    showToast('Suppliers exported to CSV file', 'info', 'fa-file-csv');
}

// Print suppliers
function printSuppliers() {
    let tableClone = document.getElementById('supplierTable').cloneNode(true);
    
    // Remove actions column
    $(tableClone).find('th:last, td:last').remove();
    
    let newWin = window.open('', '', 'width=1200,height=700');
    newWin.document.write('<html><head><title>Suppliers 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('.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('@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-truck"></i> Suppliers List</h2>');
    newWin.document.write('<p>Total Suppliers: <?= $totalSuppliers ?></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>');
    
    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)
$('#searchForm input[name="search"]').on('keyup', function(e) {
    if (e.key === 'Enter') {
        $('#searchForm').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'; ?>