<?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'])) {
    if (!empty($_GET['passport_no'])) {
        $passport_no = $con->real_escape_string($_GET['passport_no']);
        $search_query .= " AND j.passport_no LIKE '%$passport_no%'";
    }
}

// Date range filtering
$date_query = '';
if (!empty($_GET['from_date']) && !empty($_GET['to_date'])) {
    $from_date = $con->real_escape_string($_GET['from_date']);
    $to_date = $con->real_escape_string($_GET['to_date']);
    $date_query .= " AND c.interview_date BETWEEN '$from_date' AND '$to_date'";
}

// 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 $date_query
                   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 $date_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 = $_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 $date_query";
    $export_result = $con->query($export_sql);

    header('Content-Type: text/csv');
    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</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style>
        body {
            margin: 0;
            font-family: 'Segoe UI', sans-serif;
            background-color: #f5f7fa;
            color: #333;
        }

        header {
            background-color: #2c3e50;
            color: white;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
        }

        header h2 {
            margin: 0;
            font-size: 24px;
        }

        .logout-btn {
            background-color: #e74c3c;
            color: white;
            padding: 8px 14px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            cursor: pointer;
        }

        .logout-btn:hover {
            background-color: #c0392b;
        }

        .container {
            width: 95%;
            max-width: 1200px;
            margin: 30px auto;
            background: #fff;
            padding: 25px;
            border-radius: 12px;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.05);
        }

        form {
            margin-bottom: 20px;
        }

        form div {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: center;
        }

        input[type="text"],
        input[type="date"],
        input[type="datetime-local"],
        select {
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 6px;
            width: 100%;
            max-width: 200px;
            font-size: 14px;
        }

        input[type="submit"],
        button {
            background-color: #34495e;
            color: white;
            padding: 10px 16px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
        }

        input[type="submit"]:hover,
        button:hover {
            background-color: #2c3e50;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            font-size: 14px;
        }

        th, td {
            padding: 12px 10px;
            border-bottom: 1px solid #eee;
            text-align: left;
        }

        th {
            background-color: #3498db;
            color: white;
        }

        .edit-btn {
            background-color: #27ae60;
            color: white;
            padding: 6px 10px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 13px;
        }

        .edit-btn:hover {
            background-color: #219150;
        }

        .status-selected {
            background-color: #28a745;
            color: white;
            padding: 4px 6px;
            border-radius: 4px;
            text-align: center;
            display: inline-block;
            min-width: 70px;
        }

        .status-rejected {
            background-color: #dc3545;
            color: white;
            padding: 4px 6px;
            border-radius: 4px;
            text-align: center;
            display: inline-block;
            min-width: 70px;
        }

        .pagination {
            margin-top: 20px;
            text-align: center;
        }

        .pagination a {
            background: #2980b9;
            color: white;
            padding: 8px 12px;
            margin: 3px;
            text-decoration: none;
            border-radius: 4px;
            font-size: 14px;
        }

        .pagination a:hover {
            background: #1c5985;
        }

        .form-container {
            margin-top: 30px;
        }

        /* Responsive Table */
        @media screen and (max-width: 768px) {
            table, thead, tbody, th, td, tr {
                display: block;
            }

            thead {
                display: none;
            }

            tr {
                background: #fff;
                margin-bottom: 15px;
                border-radius: 10px;
                padding: 10px;
                box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
            }

            td {
                padding-left: 50%;
                position: relative;
                text-align: right;
                font-size: 13px;
            }

            td::before {
                content: attr(data-label);
                position: absolute;
                left: 10px;
                top: 10px;
                font-weight: bold;
                text-align: left;
                color: #555;
                white-space: nowrap;
            }

            input[type="text"],
            input[type="date"],
            input[type="datetime-local"],
            select {
                width: 100%;
                max-width: 100%;
            }

            form div {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>

<header>
    <h2>Interview Dashboard</h2>
    <form action="logout.php" method="post" style="margin:0;">
        <button class="logout-btn">Logout</button>
    </form>
</header>

<div class="container">
    <form method="GET">
        <div>
            <input type="text" name="passport_no" value="<?php echo isset($_GET['passport_no']) ? htmlspecialchars($_GET['passport_no']) : ''; ?>" placeholder="Passport No" />
            <input type="date" name="from_date" value="<?php echo isset($_GET['from_date']) ? htmlspecialchars($_GET['from_date']) : ''; ?>" />
            <input type="date" name="to_date" value="<?php echo isset($_GET['to_date']) ? htmlspecialchars($_GET['to_date']) : ''; ?>" />
            <input type="submit" name="search" value="Search" />
            <a href="interview.php" style="text-decoration:none;">
                <button type="button">Reset</button>
            </a>
        </div>
    </form>

    <form method="POST">
        <input type="submit" name="export" value="Export Data as CSV" />
    </form>

    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Passport No</th>
                <th>Position</th>
                <th>Job Country</th>
                <th>Reference</th>
                <th>Interview Status</th>
                <th>Selection Status</th>
                <th>Interview Date</th>
                <th>Selection Date</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($applicants_result->num_rows > 0) {
                while ($row = $applicants_result->fetch_assoc()) { ?>
                    <tr>
                        <td data-label="Name"><?php echo htmlspecialchars($row['name']); ?></td>
                        <td data-label="Passport No"><?php echo htmlspecialchars($row['passport_no']); ?></td>
                        <td data-label="Position"><?php echo htmlspecialchars($row['position']); ?></td>
                        <td data-label="Job Country"><?php echo htmlspecialchars($row['job_country']); ?></td>
                        <td data-label="Reference"><?php echo htmlspecialchars($row['reference']); ?></td>
                        <td data-label="Interview Status"><?php echo $row['interview_status'] ?: 'Not Scheduled'; ?></td>
                        <td data-label="Selection Status" class="<?php echo $row['selection_status'] == 'Selected' ? 'status-selected' : ($row['selection_status'] == 'Rejected' ? 'status-rejected' : ''); ?>">
                            <?php echo $row['selection_status'] ?: 'Pending'; ?>
                        </td>
                        <td data-label="Interview Date"><?php echo $row['interview_date'] ?: 'Not Scheduled'; ?></td>
                        <td data-label="Selection Date"><?php echo $row['selection_date'] ?: 'Not Assigned'; ?></td>
                        <td data-label="Actions">
                            <a href="interview.php?edit=<?php echo $row['id']; ?>"><button class="edit-btn">Edit</button></a>
                        </td>
                    </tr>
                <?php }
            } else {
                echo "<tr><td colspan='10'>No records found</td></tr>";
            } ?>
        </tbody>
    </table>

    <div class="pagination">
        <?php
        $base_url = "interview.php?";
        // Preserve search params in pagination links
        $params = $_GET;
        unset($params['page']);
        $query_str = http_build_query($params);

        if ($page > 1) {
            echo "<a href='" . $base_url . $query_str . "&page=" . ($page - 1) . "'>Previous</a>";
        }
        for ($i = 1; $i <= $total_pages; $i++) {
            echo "<a href='" . $base_url . $query_str . "&page=$i'>$i</a>";
        }
        if ($page < $total_pages) {
            echo "<a href='" . $base_url . $query_str . "&page=" . ($page + 1) . "'>Next</a>";
        }
        ?>
    </div>

    <?php
    if (isset($_GET['edit'])) {
        $edit_id = (int)$_GET['edit'];
        $applicant_sql = "SELECT j.id, j.name, j.passport_no, j.position, j.job_country, j.reference, c.selection_status, c.interview_date 
                          FROM job_applicants j 
                          LEFT JOIN candidate_selection c ON j.id = c.applicant_id
                          WHERE j.id = $edit_id";
        $applicant_result = $con->query($applicant_sql);
        if ($applicant_result->num_rows == 1) {
            $applicant = $applicant_result->fetch_assoc();
    ?>
            <div class="form-container">
                <h3>Edit Interview Status for <?php echo htmlspecialchars($applicant['name']); ?></h3>
                <form method="POST">
                    <input type="hidden" name="applicant_id" value="<?php echo $applicant['id']; ?>" />
                    <label for="interview_date">Interview Date:</label><br>
                    <input type="datetime-local" id="interview_date" name="interview_date" value="<?php echo $applicant['interview_date'] ? date('Y-m-d\TH:i', strtotime($applicant['interview_date'])) : ''; ?>" required><br><br>

                    <label for="selection_status">Selection Status:</label><br>
                    <select id="selection_status" name="selection_status" required>
                        <option value="">Select</option>
                        <option value="Selected" <?php if ($applicant['selection_status'] == 'Selected') echo 'selected'; ?>>Selected</option>
                        <option value="Rejected" <?php if ($applicant['selection_status'] == 'Rejected') echo 'selected'; ?>>Rejected</option>
                    </select><br><br>

                    <input type="submit" value="Update Status" />
                </form>
            </div>
    <?php
        }
    }
    ?>

</div>

</body>
</html>
