<?php
include('dbconnect.php');

$success_message = "";
$error_message = "";

// Fetch offer letter details if applicant is selected for editing
$edit_offer = null;

if (isset($_GET['edit_applicant_id'])) {
    $edit_id = intval($_GET['edit_applicant_id']);
    $stmt = $con->prepare("SELECT o.id AS offer_id, o.applicant_id, o.offer_status, o.offer_letter_file, j.name, j.passport_no 
                           FROM offer_letters o
                           JOIN job_applicants j ON o.applicant_id = j.id
                           WHERE o.applicant_id = ?");
    $stmt->bind_param("i", $edit_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $edit_offer = $result->fetch_assoc();
    } else {
        // If no offer letter record, try to get applicant info only
        $stmt = $con->prepare("SELECT id, name, passport_no FROM job_applicants WHERE id = ?");
        $stmt->bind_param("i", $edit_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            $applicant = $result->fetch_assoc();
            $edit_offer = [
                'applicant_id' => $applicant['id'],
                'name' => $applicant['name'],
                'passport_no' => $applicant['passport_no'],
                'offer_status' => '',
                'offer_letter_file' => ''
            ];
        }
    }
    $stmt->close();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $applicant_id = $_POST['applicant_id'];
    $offer_status = $_POST['offer_status'];

    // Handle file upload if any
    $offer_letter_file = null;

    // First, get current offer_letter_file from DB so we can delete old if replaced
    $stmt = $con->prepare("SELECT offer_letter_file FROM offer_letters WHERE applicant_id = ?");
    $stmt->bind_param("i", $applicant_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $existing_file = null;
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $existing_file = $row['offer_letter_file'];
    }
    $stmt->close();

    if (isset($_FILES['offer_letter_file']) && $_FILES['offer_letter_file']['error'] == 0) {
        $upload_dir = 'uploads/offer_letters/';
        if (!file_exists($upload_dir)) mkdir($upload_dir, 0777, true);

        // To avoid filename conflicts, prepend timestamp
        $file_ext = pathinfo($_FILES['offer_letter_file']['name'], PATHINFO_EXTENSION);
        if (strtolower($file_ext) !== 'pdf') {
            $error_message = "Only PDF files are allowed.";
        } else {
            $file_name = time() . "_" . basename($_FILES['offer_letter_file']['name']);
            $file_path = $upload_dir . $file_name;

            if (move_uploaded_file($_FILES['offer_letter_file']['tmp_name'], $file_path)) {
                $offer_letter_file = $file_path;
                // Delete old file if exists and different
                if ($existing_file && file_exists($existing_file) && $existing_file != $offer_letter_file) {
                    unlink($existing_file);
                }
            } else {
                $error_message = "File upload failed!";
            }
        }
    } else {
        // No new file uploaded, keep old file path
        $offer_letter_file = $existing_file;
    }

    if (empty($error_message)) {
        // Insert or Update record
        $sql = "INSERT INTO offer_letters (applicant_id, offer_status, offer_letter_file, upload_date)
                VALUES (?, ?, ?, NOW())
                ON DUPLICATE KEY UPDATE offer_status = ?, offer_letter_file = ?, upload_date = NOW()";

        if ($stmt = $con->prepare($sql)) {
            $stmt->bind_param("issss", $applicant_id, $offer_status, $offer_letter_file, $offer_status, $offer_letter_file);
            if ($stmt->execute()) {
                $success_message = "✅ Offer letter updated successfully.";
                // Refresh $edit_offer so form updates
                $edit_offer = [
                    'applicant_id' => $applicant_id,
                    'offer_status' => $offer_status,
                    'offer_letter_file' => $offer_letter_file
                ];
            } else {
                $error_message = "Database error: " . $stmt->error;
            }
            $stmt->close();
        } else {
            $error_message = "Failed to prepare statement: " . $con->error;
        }
    }
}

// Search applicants (same as before)
$search_query = "";
if (isset($_GET['search_passport']) && !empty($_GET['search_passport'])) {
    $search_passport = $con->real_escape_string($_GET['search_passport']);
    $search_query = "WHERE passport_no LIKE '%$search_passport%'";
}

$applicants_sql = "SELECT * FROM job_applicants $search_query ORDER BY name ASC";
$applicants_result = $con->query($applicants_sql);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Edit Offer Letter</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
<style>
/* (Use your existing CSS from above, omitted here for brevity) */
</style>
</head>
<body>

<header>
    <h2><i class="fa-solid fa-file-contract"></i> Offer Letter Management</h2>
    <form action="logout.php" method="post" aria-label="Logout Form">
        <button class="logout-btn" type="submit" aria-label="Logout">
            <i class="fa-solid fa-right-from-bracket"></i> Logout
        </button>
    </form>
</header>

<div class="container" role="main" aria-labelledby="mainTitle">
    <h3 id="mainTitle"><i class="fa-solid fa-pen-to-square"></i> Edit Offer Letter</h3>

    <?php if ($success_message): ?>
        <p class="success"><?php echo $success_message; ?></p>
    <?php endif; ?>
    <?php if ($error_message): ?>
        <p class="error"><?php echo $error_message; ?></p>
    <?php endif; ?>

    <!-- Search Form -->
    <form method="GET" action="offer_letters.php" aria-label="Search Applicants by Passport Number">
        <label for="search_passport"><i class="fa-solid fa-magnifying-glass"></i> Search by Passport No:</label>
        <input type="text" id="search_passport" name="search_passport" placeholder="Enter Passport Number" value="<?php echo isset($search_passport) ? htmlspecialchars($search_passport) : ''; ?>" />
        <input type="submit" value="Search" aria-label="Search Applicants">
    </form>

    <!-- Applicant List with Edit Links -->
    <h4>Applicants:</h4>
    <ul>
        <?php while ($row = $applicants_result->fetch_assoc()): ?>
            <li>
                <?php echo htmlspecialchars($row['name']) . " (Passport: " . htmlspecialchars($row['passport_no']) . ")"; ?>
                — <a href="offer_letters.php?edit_applicant_id=<?php echo $row['id']; ?>" style="color:#764ba2;">Edit Offer Letter</a>
            </li>
        <?php endwhile; ?>
    </ul>

    <?php if ($edit_offer): ?>
    <!-- Edit Offer Letter Form -->
    <form method="POST" action="offer_letters.php" enctype="multipart/form-data" aria-label="Update Offer Letter Status Form">
        <input type="hidden" name="applicant_id" value="<?php echo htmlspecialchars($edit_offer['applicant_id']); ?>" />
        <label><i class="fa-solid fa-user"></i> Applicant:</label>
        <input type="text" value="<?php echo htmlspecialchars($edit_offer['name'] ?? ''); ?> (Passport: <?php echo htmlspecialchars($edit_offer['passport_no'] ?? ''); ?>)" disabled />

        <label for="offer_status"><i class="fa-solid fa-list-check"></i> Offer Status:</label>
        <select name="offer_status" id="offer_status" required aria-required="true">
            <option value="">-- Select Status --</option>
            <option value="Received" <?php if (($edit_offer['offer_status'] ?? '') === "Received") echo "selected"; ?>>Received</option>
            <option value="Rejected" <?php if (($edit_offer['offer_status'] ?? '') === "Rejected") echo "selected"; ?>>Rejected</option>
        </select>

        <label for="offer_letter_file"><i class="fa-solid fa-file-pdf"></i> Upload Offer Letter (PDF):</label>
        <?php if (!empty($edit_offer['offer_letter_file']) && file_exists($edit_offer['offer_letter_file'])): ?>
            <p>Current file: <a href="<?php echo htmlspecialchars($edit_offer['offer_letter_file']); ?>" target="_blank" rel="noopener noreferrer">View PDF</a></p>
        <?php else: ?>
            <p>No offer letter uploaded yet.</p>
        <?php endif; ?>
        <input type="file" name="offer_letter_file" id="offer_letter_file" accept="application/pdf" aria-describedby="fileHelp" />
        <small id="fileHelp" style="color:#666; display:block; margin-top:-15px; margin-bottom:20px; font-size:0.85rem;">
            Uploading a new file will replace the existing one. PDF only.
        </small>

        <input type="submit" value="Update Offer Letter Status" />
    </form>
    <?php else: ?>
        <p>Select an applicant above to edit their offer letter status.</p>
    <?php endif; ?>

</div>

</body>
</html>
