<?php
// Include the database connection
include('dbconnect.php');

// Pagination logic
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$start_from = ($page - 1) * $limit;

// Search functionality
$search_query = '';
if (isset($_GET['search']) && !empty($_GET['passport_no'])) {
    $passport_no = $con->real_escape_string($_GET['passport_no']);
    $search_query = " AND j.passport_no LIKE '%$passport_no%'";
}

// Fetch applicants
$applicants_sql = "SELECT j.id, j.name, j.passport_no, j.position, j.job_country, j.reference, 
                          c.interview_status, c.selection_status, c.interview_date, c.selection_date 
                   FROM job_applicants j 
                   LEFT JOIN candidate_selection c ON j.id = c.applicant_id
                   WHERE 1=1 $search_query
                   ORDER BY j.name ASC
                   LIMIT $start_from, $limit";

$applicants_result = $con->query($applicants_sql);

// Pagination count
$total_sql = "SELECT COUNT(*) FROM job_applicants j LEFT JOIN candidate_selection c ON j.id = c.applicant_id WHERE 1=1 $search_query";
$total_result = $con->query($total_sql);
$total_rows = $total_result->fetch_row()[0];
$total_pages = ceil($total_rows / $limit);

// Handle update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['applicant_id'])) {
    $applicant_id = (int)$_POST['applicant_id'];
    $interview_date = $_POST['interview_date'];
    $selection_status = $_POST['selection_status'];

    $sql = "INSERT INTO candidate_selection (applicant_id, interview_status, selection_status, interview_date, selection_date)
            VALUES (?, 'Completed', ?, ?, NOW())
            ON DUPLICATE KEY UPDATE interview_status = 'Completed', selection_status = ?, interview_date = ?, selection_date = NOW()";

    if ($stmt = $con->prepare($sql)) {
        $stmt->bind_param("issss", $applicant_id, $selection_status, $interview_date, $selection_status, $interview_date);
        $stmt->execute();
        $stmt->close();
        header("Location: interview.php");
        exit;
    }
}

// Export to CSV
if (isset($_POST['export'])) {
    $export_sql = "SELECT j.name, j.passport_no, j.position, j.job_country, j.reference, c.interview_status, c.selection_status, c.interview_date, c.selection_date 
                   FROM job_applicants j 
                   LEFT JOIN candidate_selection c ON j.id = c.applicant_id
                   WHERE 1=1 $search_query
                   ORDER BY j.name ASC";
    $export_result = $con->query($export_sql);

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="interview_status.csv"');
    $output = fopen('php://output', 'w');
    fputcsv($output, ['Name', 'Passport No', 'Position', 'Job Country', 'Reference', 'Interview Status', 'Selection Status', 'Interview Date', 'Selection Date']);
    while ($row = $export_result->fetch_assoc()) {
        fputcsv($output, $row);
    }
    fclose($output);
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Interview Status Dashboard</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <!-- FontAwesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" crossorigin="anonymous" />
    <style>
        /* Reset and base */
        * {
            box-sizing: border-box;
        }
        body {
            margin: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #eef2f7;
            color: #333;
        }

        /* Header */
        header {
            background-color: #34495e;
            color: #ecf0f1;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
        }
        header h2 {
            margin: 0;
            font-weight: 700;

            font-size: 1.8rem;
            letter-spacing: 1.5px;
        }
        .logout-btn {
            background-color: #e74c3c;
            border: none;
            padding: 10px 16px;
            border-radius: 6px;
            color: white;
            font-weight: 600;
            font-size: 0.95rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 6px;
            transition: background-color 0.3s ease;
        }
        .logout-btn:hover {
            background-color: #c0392b;
        }

        /* Container */
        .container {
            max-width: 1200px;
            margin: 30px auto 60px auto;
            background: white;
            padding: 30px 25px;
            border-radius: 12px;
            box-shadow: 0 8px 20px rgb(0 0 0 / 0.1);
        }

        /* Forms */
        form.search-form,
        form.export-form {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: center;
            margin-bottom: 20px;
        }
        form.search-form label {
            font-weight: 600;
            min-width: 140px;
            color: #34495e;
        }
        form.search-form input[type="text"] {
            flex: 1;
            padding: 10px 12px;
            border: 1.8px solid #bbb;
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
        }
        form.search-form input[type="text"]:focus {
            border-color: #2980b9;
            outline: none;
        }
        form.search-form input[type="submit"],
        form.export-form input[type="submit"] {
            background-color: #2980b9;
            border: none;
            color: white;
            padding: 10px 20px;
            border-radius: 8px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        form.search-form input[type="submit"]:hover,
        form.export-form input[type="submit"]:hover {
            background-color: #1c5985;
        }

        /* Table styling */
        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.9rem;
            overflow-x: auto;
        }
        thead {
            background: #2980b9;
            color: white;
            font-weight: 700;
        }
        th, td {
            padding: 14px 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
            vertical-align: middle;
        }

        tbody tr:hover {
            background-color: #f0f8ff;
        }

        /* Status badges */
        .status-selected {
            background-color: #28a745;
            color: white;
            padding: 6px 12px;
            border-radius: 20px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            font-size: 0.85rem;
        }
        .status-selected i {
            color: #d4edda;
        }
        .status-rejected {
            background-color: #dc3545;
            color: white;
            padding: 6px 12px;
            border-radius: 20px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            font-size: 0.85rem;
        }
        .status-rejected i {
            color: #f8d7da;
        }
        .status-pending {
            background-color: #ffc107;
            color: #212529;
            padding: 6px 12px;
            border-radius: 20px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            font-size: 0.85rem;
        }

        /* Edit button */
        .edit-btn {
            background-color: #27ae60;
            border: none;
            padding: 8px 14px;
            border-radius: 6px;
            color: white;
            font-weight: 600;
            cursor: pointer;
            font-size: 0.9rem;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: background-color 0.3s ease;
        }
        .edit-btn i {
            font-size: 1rem;
        }
        .edit-btn:hover {
            background-color: #1e8449;
        }

        /* Pagination */
        .pagination {
            margin-top: 30px;
            text-align: center;
        }
        .pagination a {
            display: inline-block;
            margin: 0 5px 5px 5px;
            background: #2980b9;
            color: white;
            padding: 8px 14px;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 600;
            transition: background-color 0.3s ease;
        }
        .pagination a:hover,
        .pagination a.active {
            background-color: #1c5985;
        }

        /* Form container for edit */
        .form-container {
            margin-top: 40px;
            padding: 25px 20px;
            border: 2px solid #2980b9;
            border-radius: 12px;
            background-color: #f0f8ff;
            max-width: 600px;
        }
        .form-container h3 {
            margin-top: 0;
            color: #2980b9;
            font-weight: 700;
            margin-bottom: 20px;
            font-size: 1.4rem;
        }

        .form-container label {
            display: block;
            margin-bottom: 6px;
            font-weight: 600;
            color: #34495e;
        }

        .form-container input[type="datetime-local"],
        .form-container select {
            width: 100%;
            padding: 12px 14px;
            border-radius: 8px;
            border: 1.8px solid #ccc;
            margin-bottom: 20px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
        }
        .form-container input[type="datetime-local"]:focus,
        .form-container select:focus {
            border-color: #2980b9;
            outline: none;
        }
        .form-container input[type="submit"] {
            background-color: #2980b9;
            border: none;
            color: white;
            padding: 12px 24px;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 700;
            font-size: 1.1rem;
            transition: background-color 0.3s ease;
        }
        .form-container input[type="submit"]:hover {
            background-color: #1c5985;
        }

        /* Responsive adjustments */
        @media (max-width: 900px) {
            th, td {
                padding: 10px 8px;
                font-size: 0.85rem;
            }
            .edit-btn {
                padding: 6px 10px;
                font-size: 0.8rem;
            }
            .form-container {
                max-width: 100%;
            }
        }

        @media (max-width: 600px) {
            header {
                flex-direction: column;
                align-items: flex-start;
                gap: 12px;
            }
            .logout-btn {
                width: 100%;
                justify-content: center;
            }
            form.search-form {
                flex-direction: column;
                align-items: stretch;
            }
            form.search-form label {
                min-width: auto;
            }
            form.search-form input[type="text"],
            form.search-form input[type="submit"] {
                width: 100%;
                box-sizing: border-box;
            }
            .pagination a {
                padding: 8px 12px;
                margin: 4px 3px;
            }
            table {
                display: block;
                overflow-x: auto;
                white-space: nowrap;
            }
        }
    </style>
</head>
<body>
<header>
    <h2><i class="fa-solid fa-clipboard-list"></i> Interview Dashboard</h2>
    <form action="logout.php" method="post" style="margin:0;">
        <button class="logout-btn" type="submit"><i class="fa-solid fa-right-from-bracket"></i> Logout</button>
    </form>
</header>

<div class="container">
    <form method="GET" class="search-form" role="search" aria-label="Search applicants by passport number">
        <label for="passport_no"><i class="fa-solid fa-passport"></i> Search by Passport No:</label>
        <input type="text" id="passport_no" name="passport_no" value="<?php echo isset($_GET['passport_no']) ? htmlspecialchars($_GET['passport_no']) : ''; ?>" placeholder="Enter passport no" required />
        <input type="submit" name="search" value="Search" />
    </form>

    <form method="POST" class="export-form" aria-label="Export applicants data">
        <input type="submit" name="export" value="Export Data as CSV" />
    </form>

    <table aria-describedby="applicant-list" role="table">
        <thead>
        <tr>
            <th scope="col"><i class="fa-solid fa-user"></i> Name</th>
            <th scope="col"><i class="fa-solid fa-id-card"></i> Passport No</th>
            <th scope="col"><i class="fa-solid fa-briefcase"></i> Position</th>
            <th scope="col"><i class="fa-solid fa-globe"></i> Job Country</th>
            <th scope="col"><i class="fa-solid fa-link"></i> Reference</th>
            <th scope="col"><i class="fa-solid fa-calendar-check"></i> Interview Status</th>
            <th scope="col"><i class="fa-solid fa-check-to-slot"></i> Selection Status</th>
            <th scope="col"><i class="fa-solid fa-calendar-days"></i> Interview Date</th>
            <th scope="col"><i class="fa-solid fa-calendar-plus"></i> Selection Date</th>
            <th scope="col"><i class="fa-solid fa-pen-to-square"></i> Actions</th>
        </tr>
        </thead>
        <tbody>
        <?php if ($applicants_result->num_rows > 0) :
            while ($row = $applicants_result->fetch_assoc()) : ?>
                <tr>
                    <td><?php echo htmlspecialchars($row['name']); ?></td>
                    <td><?php echo htmlspecialchars($row['passport_no']); ?></td>
                    <td><?php echo htmlspecialchars($row['position']); ?></td>
                    <td><?php echo htmlspecialchars($row['job_country']); ?></td>
                    <td><?php echo htmlspecialchars($row['reference']); ?></td>
                    <td>
                        <?php
                        $interview_status = $row['interview_status'] ?: 'Not Scheduled';
                        if ($interview_status === 'Completed') {
                            echo '<span class="status-selected"><i class="fa-solid fa-circle-check"></i> Completed</span>';
                        } elseif ($interview_status === 'Scheduled') {
                            echo '<span class="status-pending"><i class="fa-solid fa-hourglass-half"></i> Scheduled</span>';
                        } else {
                            echo '<span class="status-pending"><i class="fa-solid fa-clock"></i> Not Scheduled</span>';
                        }
                        ?>
                    </td>
                    <td>
                        <?php
                        $selection_status = $row['selection_status'] ?: 'Pending';
                        if ($selection_status === 'Selected') {
                            echo '<span class="status-selected"><i class="fa-solid fa-thumbs-up"></i> Selected</span>';
                        } elseif ($selection_status === 'Rejected') {
                            echo '<span class="status-rejected"><i class="fa-solid fa-thumbs-down"></i> Rejected</span>';
                        } else {
                            echo '<span class="status-pending"><i class="fa-solid fa-hourglass"></i> Pending</span>';
                        }
                        ?>
                    </td>
                    <td><?php echo $row['interview_date'] ? date('d M Y, H:i', strtotime($row['interview_date'])) : 'Not Scheduled'; ?></td>
                    <td><?php echo $row['selection_date'] ? date('d M Y, H:i', strtotime($row['selection_date'])) : 'Not Assigned'; ?></td>
                    <td>
                        <a href="interview.php?edit=<?php echo (int)$row['id']; ?>" class="edit-btn" aria-label="Edit <?php echo htmlspecialchars($row['name']); ?> interview status">
                            <i class="fa-solid fa-pen-to-square"></i> Edit
                        </a>
                    </td>
                </tr>
            <?php endwhile;
        else : ?>
            <tr>
                <td colspan="10" style="text-align:center; padding: 25px; font-weight: 600; color: #888;">No records found</td>
            </tr>
        <?php endif; ?>
        </tbody>
    </table>

    <nav class="pagination" aria-label="Pagination navigation">
        <?php
        // Previous button
        if ($page > 1) {
            echo '<a href="interview.php?page=' . ($page - 1) . '" aria-label="Previous page"><i class="fa-solid fa-arrow-left"></i> Previous</a>';
        }

        // Page links (limited to max 7 pages for usability)
        $start_page = max(1, $page - 3);
        $end_page = min($total_pages, $page + 3);

        if ($start_page > 1) {
            echo '<a href="interview.php?page=1">1</a>';
            if ($start_page > 2) {
                echo ' ... ';
            }
        }

        for ($i = $start_page; $i <= $end_page; $i++) {
            if ($i == $page) {
                echo '<a href="#" class="active" aria-current="page">' . $i . '</a>';
            } else {
                echo '<a href="interview.php?page=' . $i . '">' . $i . '</a>';
            }
        }

        if ($end_page < $total_pages) {
            if ($end_page < $total_pages - 1) {
                echo ' ... ';
            }
            echo '<a href="interview.php?page=' . $total_pages . '">' . $total_pages . '</a>';
        }

        // Next button
        if ($page < $total_pages) {
            echo '<a href="interview.php?page=' . ($page + 1) . '" aria-label="Next page">Next <i class="fa-solid fa-arrow-right"></i></a>';
        }
        ?>
    </nav>

    <?php if (isset($_GET['edit'])):
        $edit_id = (int)$_GET['edit'];
        $edit_sql = "SELECT j.name, j.passport_no, c.interview_date, c.selection_status
                     FROM job_applicants j 
                     LEFT JOIN candidate_selection c ON j.id = c.applicant_id
                     WHERE j.id = $edit_id
                     LIMIT 1";
        $edit_result = $con->query($edit_sql);
        if ($edit_result->num_rows === 1):
            $edit_row = $edit_result->fetch_assoc();
            ?>
            <div class="form-container" aria-label="Edit interview form for <?php echo htmlspecialchars($edit_row['name']); ?>">
                <h3><i class="fa-solid fa-pen-to-square"></i> Edit Interview - <?php echo htmlspecialchars($edit_row['name']); ?></h3>
                <form method="POST" action="interview.php">
                    <input type="hidden" name="applicant_id" value="<?php echo $edit_id; ?>" />
                    <label for="interview_date"><i class="fa-solid fa-calendar-days"></i> Interview Date & Time</label>
                    <input type="datetime-local" id="interview_date" name="interview_date" required value="<?php
                        echo $edit_row['interview_date'] ? date('Y-m-d\TH:i', strtotime($edit_row['interview_date'])) : '';
                    ?>" />

                    <label for="selection_status"><i class="fa-solid fa-clipboard-check"></i> Selection Status</label>
                    <select id="selection_status" name="selection_status" required>
                        <option value="" disabled>-- Select Status --</option>
                        <option value="Selected" <?php if ($edit_row['selection_status'] === 'Selected') echo 'selected'; ?>>Selected</option>
                        <option value="Rejected" <?php if ($edit_row['selection_status'] === 'Rejected') echo 'selected'; ?>>Rejected</option>
                        <option value="Pending" <?php if (!$edit_row['selection_status'] || $edit_row['selection_status'] === 'Pending') echo 'selected'; ?>>Pending</option>
                    </select>

                    <input type="submit" value="Save Changes" />
                </form>
            </div>
        <?php else: ?>
            <p style="color: red; margin-top: 30px; font-weight: 600;">Applicant not found.</p>
        <?php endif;
    endif; ?>
</div>

</body>
</html>
