<?php
include('include/connection.php');
// require_once 'config.php';

// Search and pagination parameters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 10;

// Calculate offset for pagination
$offset = ($page > 1) ? ($page - 1) * $perPage : 0;

// Build the base query
$query = "SELECT * FROM vehReg WHERE 1=1 ORDER BY regID DESC";
$params = [];

// Add search conditions if search term exists
if (!empty($search)) {
    $query .= " AND (first_name LIKE :search OR last_name LIKE :search OR email LIKE :search OR position LIKE :search)";
    $params[':search'] = "%$search%";
}

// Get total count for pagination
$countStmt = $pdo->prepare(str_replace('*', 'COUNT(*) as total', $query));
$countStmt->execute($params);
$total = $countStmt->fetch()['total'];
$totalPages = ceil($total / $perPage);

// Add sorting, limits for the main query
$query .= " LIMIT :offset, :perPage";
$params[':offset'] = $offset;
$params[':perPage'] = $perPage;

// Prepare and execute main query
$stmt = $pdo->prepare($query);
foreach ($params as $key => &$val) {
    if ($key === ':offset' || $key === ':perPage') {
        $stmt->bindParam($key, $val, PDO::PARAM_INT);
    } else {
        $stmt->bindParam($key, $val);
    }
}
$stmt->execute();
$employees = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Employee Data Table</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            background-color: #f8f9fa;
            padding: 20px;
        }
        .data-table-container {
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            padding: 20px;
            margin-top: 20px;
        }
        .search-container {
            margin-bottom: 20px;
        }
        .pagination {
            justify-content: center;
            margin-top: 20px;
        }
        .table-responsive {
            overflow-x: auto;
        }
        .action-btns .btn {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }
        .highlight {
            background-color: #fffde7;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2 class="text-center mb-4">Employee Records</h2>
        
        <div class="data-table-container">
            <!-- Search Bar -->
            <div class="search-container">
                <form method="get" class="row g-3">
                    <div class="col-md-8">
                        <div class="input-group">
                            <input type="text" class="form-control" name="search" placeholder="Search employees..." 
                                   value="<?php echo htmlspecialchars($search); ?>">
                            <button class="btn btn-primary" type="submit">
                                <i class="fas fa-search"></i> Search
                            </button>
                        </div>
                    </div>
                    <div class="col-md-4 text-end">
                        <a href="data_table.php" class="btn btn-outline-secondary">
                            <i class="fas fa-sync-alt"></i> Reset
                        </a>
                    </div>
                </form>
            </div>

            <!-- Data Table -->
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead class="table-dark">
                        <tr>
                            <th>ID</th>
                            <th>Owner's Name</th>
                            <th>Vehicle Type</th>
                            <th>Vehicle Make</th>
                            <th>Vehicle Model</th>
                            <th>Vehicle Chasis</th>
                            <th>Purpose</th>
                            <th>Date of Application</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($employees)): ?>
                            <tr>
                                <td colspan="8" class="text-center">No records found</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($employees as $employee): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($employee['regID']); ?></td>
                                    <td><?php echo htmlspecialchars($employee['ownerName']); ?></td>
                                    <td><?php echo htmlspecialchars($employee['vehType']); ?></td>
                                    <td><?php echo htmlspecialchars($employee['vehMake']); ?></td>
                                    <td><?php echo htmlspecialchars($employee['vehModel']); ?></td>
                                    <td><?php echo htmlspecialchars($employee['vehChasis']); ?></td>
                                    <td><?php echo htmlspecialchars($employee['vehPurpose'], 2); ?></td>
                                    <td><?php echo date('M j, Y', strtotime($employee['datee'])); ?></td>
                                    <td class="action-btns">
                                        <a href="generatepdf.php?regID=<?php echo $employee['regID']; ?>" class="btn btn-sm btn-warning">
                                            <i class="fas fa-print"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <?php if ($totalPages > 1): ?>
                <nav aria-label="Page navigation">
                    <ul class="pagination">
                        <?php if ($page > 1): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($search); ?>" 
                                   aria-label="Previous">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                        <?php endif; ?>

                        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                            <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>">
                                <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>">
                                    <?php echo $i; ?>
                                </a>
                            </li>
                        <?php endfor; ?>

                        <?php if ($page < $totalPages): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?php echo $page+1; ?>&search=<?php echo urlencode($search); ?>" 
                                   aria-label="Next">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                        <?php endif; ?>
                    </ul>
                </nav>
            <?php endif; ?>

            <div class="text-end">
                <p class="text-muted">
                    Showing <?php echo ($total > 0) ? $offset + 1 : 0; ?> to 
                    <?php echo min($offset + $perPage, $total); ?> of <?php echo $total; ?> records
                </p>
            </div>
        </div>
    </div>

    <!-- JavaScript Libraries -->
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    
    <script>
        // Highlight search terms in the table
        $(document).ready(function() {
            const searchTerm = "<?php echo addslashes($search); ?>";
            if (searchTerm) {
                $('td').each(function() {
                    const text = $(this).text();
                    const highlighted = text.replace(
                        new RegExp(searchTerm, 'gi'),
                        match => `<span class="highlight">${match}</span>`
                    );
                    $(this).html(highlighted);
                });
            }

            // Initialize DataTable with Bootstrap 5 styling
            $('.table').DataTable({
                paging: false,
                searching: false,
                info: false,
                responsive: true
            });
        });
    </script>
</body>
</html>