<?php
if (!isset($_SESSION)) {
    session_start();
}

if (!isset($_SESSION['neetuser'])) {
    session_destroy();
    echo("<script LANGUAGE='JavaScript'>
    window.location.href='https://www.keralaneetmodelexam.in/login.php';
    </script>");
}
require_once('lib/dbclass.php');
updateQuery("update tbl_candidates set paymentstatus='Paid' where paymentid!=''");
updateQuery("update tbl_candidates set paymentstatus='Pending' where paymentid=''");
// Database connection
$con = new mysqli('localhost', 'gdhhsxmy_dopa', 'gdhhsxmy_dopa', 'gdhhsxmy_dopa');

if ($con->connect_error) {
    die('Connection failed: ' . $con->connect_error);
}

// Pagination and search variables
$recordsPerPage = 50; // Records per page
$page           = isset($_GET['page']) ? (int) $_GET['page'] : 1;
$page           = max(1, $page); // Ensure the page is at least 1
$offset         = ($page - 1) * $recordsPerPage;

// Get search term
$searchTerm = isset($_GET['search']) ? $con->real_escape_string(trim($_GET['search'])) : '';

// Build the WHERE clause for searching across all fields
$whereClause = '';

if (!empty($searchTerm)) {
    $searchColumns    = ['name', 'Regno', 'mobile', 'state', 'district', 'school',  'neetscore', 'paymentid','paymentstatus'];
    $searchConditions = [];

    foreach ($searchColumns as $column) {
        $searchConditions[] = 'tbl_candidates.' . "$column LIKE '%$searchTerm%'";
    }
    $whereClause = "WHERE tbl_referal.name LIKE '%$searchTerm%' OR " . implode(' OR ', $searchConditions);
}
$_SESSION['export'] = $whereClause;
// Get total matching records
$totalRecordsQuery  = "SELECT COUNT(*) as total FROM tbl_candidates Inner join tbl_referal on tbl_candidates.referal=tbl_referal.id  $whereClause";
$totalRecordsResult = $con->query($totalRecordsQuery);
$totalRecords       = $totalRecordsResult->fetch_assoc()['total'];

// Calculate total pages
$totalPages = ceil($totalRecords / $recordsPerPage);

// Fetch data for the current page
$sql = "SELECT tbl_candidates.*,tbl_referal.name refername FROM tbl_candidates inner join tbl_referal on tbl_candidates.referal=tbl_referal.id  $whereClause ORDER BY tbl_candidates.id DESC LIMIT $offset, $recordsPerPage";


$result = $con->query($sql);

$key = 567;
function xor_encode($input, $key)
{
    $encoded = '';
    for ($i = 0; $i < strlen($input); $i++) {
        $encoded .= chr(ord($input[$i]) ^ $key);
    }

    return $encoded;
}

// Handle course mapping
$course = [
    '0' => 'Select',
    '1' => '12th student',
    '2' => '12th completed',
    '3' => 'Repeater',
    '4' => 'Rerepeater',
    '5' => 'Other',
];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kerala NEET Model Exam</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body>

    <div class="container">
        <center><h1 class="p-4">Registered Students</h1></center>
        
        <!-- Search Form -->
        
        


<!-- Arrange buttons beneath search bar -->
<div class="row mb-3">
    
    <div class="col">
        
        <form method="GET" class="mb-3">
    <div class="input-group">
        <input type="text" name="search" class="form-control" placeholder="Search across all records" value="<?= htmlspecialchars($searchTerm) ?>">
        <button type="submit" class="btn btn-primary">Search</button>
    </div>
</form>
       </div> 
        
    <div class="col">
        <a href="<?= $_SERVER['PHP_SELF'] ?>" class="btn btn-secondary w-100">Reset</a>
    </div>
    <div class="col">
        <form action="export.php" method="GET" class="w-100">
            <input type="hidden" name="search" value="<?= htmlspecialchars($searchTerm) ?>">
            <input type="hidden" name="page" value="<?= $page ?>">
            <button type="submit" class="btn btn-primary w-100">Export</button>
        </form>
    </div>
</div>


        <div class="table-responsive">
            <table id="example" class="table align-middle mb-0 bg-white w-100">
                <thead class="bg-light">
                    <tr>
                        <th>S#</th>
                        <th>Photo</th>
                        <th>Reg.No.</th>
                        <th>Name</th>
                        <th>Mobile</th>
                        <th>Course</th>
                        <th>Institute</th>
                        <th>State</th>
                        <th>District</th>
                        <th>NEET Score</th>
                        <th>Referral</th>
                        <th>Payment</th>
                        <th>Reference ID</th>
                        <th>Edit</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $i = $offset + 1; // Start serial number from the current offset
while ($row = $result->fetch_assoc()) {
    $courses    = isset($course[$row['course']]) ? $course[$row['course']] : '';
    $encoded_id = xor_encode($row['id'], $key);  // URL encode the id value

    // Highlight search term in results
    $highlight = function ($value) use ($searchTerm) {
        return !empty($searchTerm) ? str_ireplace($searchTerm, "<mark>$searchTerm</mark>", $value) : $value;
    };

    echo '<tr>
                            <td>' . $i++ . '</td>
                            <td><img src="uploads/' . $row['photo'] . '" alt="Photo" width="50"></td>
                            <td>' . $highlight($row['Regno']) . '</td>
                            <td>' . $highlight($row['name']) . '</td>
                            <td>' . $highlight($row['mobile']) . '</td>
                            <td>' . $courses . '</td>
                            <td>' . $highlight($row['school']) . '</td>
                            <td>' . $highlight($row['state']) . '</td>
                            <td>' . $highlight($row['district']) . '</td>
                            <td>' . $highlight($row['neetscore']) . '</td>
                            <td>' . $highlight($row['refername']) . '</td>
                            <td>' . $highlight($row['paymentstatus']) . '</td>
                            <td>' . $highlight($row['paymentid']) . '</td>
                            <td>
                                <form action="edit.php" method="GET">
                                    <input type="hidden" name="id" value="' . $encoded_id . '">
                                    <button type="submit" class="btn btn-primary btn-sm">Edit</button>
                                </form>
                            </td>
                        </tr>';
}
?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <nav>
            <ul class="pagination justify-content-center">
                <li class="page-item <?= ($page == 1) ? 'disabled' : '' ?>">
                    <a class="page-link rounded-pill" href="?page=<?= $page - 1 ?>&search=<?= urlencode($searchTerm) ?>">Previous</a>
                </li>
                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                    <li class="page-item <?= ($i == $page) ? 'active' : '' ?>">
                        <a class="page-link rounded-pill" href="?page=<?= $i ?>&search=<?= urlencode($searchTerm) ?>"><?= $i ?></a>
                    </li>
                <?php endfor; ?>
                <li class="page-item <?= ($page == $totalPages) ? 'disabled' : '' ?>">
                    <a class="page-link rounded-pill" href="?page=<?= $page + 1 ?>&search=<?= urlencode($searchTerm) ?>">Next</a>
                </li>
            </ul>
        </nav>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.0/xlsx.full.min.js"></script>
   
    
</body>
</html>
