<?php
include('dbconnect.php');

if (!isset($_GET['id'])) {
    header("Location: offer_letters.php");
    exit;
}

$applicant_id = intval($_GET['id']);

// Get applicant and offer letter info
$sql = "SELECT j.id, j.name, j.passport_no, j.position, j.job_country, j.reference, 
               ol.offer_status, ol.offer_letter_file
        FROM job_applicants j 
        LEFT JOIN offer_letters ol ON j.id = ol.applicant_id
        WHERE j.id = ?";
$stmt = $con->prepare($sql);
$stmt->bind_param("i", $applicant_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows == 0) {
    $stmt->close();
    header("Location: offer_letters.php");
    exit;
}

$applicant = $result->fetch_assoc();
$stmt->close();

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $offer_status = $_POST['offer_status'] ?? 'Pending';
    $offer_letter_file = $applicant['offer_letter_file'];

    // Handle file upload
    if (isset($_FILES['offer_letter_file']) && $_FILES['offer_letter_file']['error'] === 0) {
        $allowed_mime = ['application/pdf'];
        $file_type = mime_content_type($_FILES['offer_letter_file']['tmp_name']);

        if (!in_array($file_type, $allowed_mime)) {
            $error = "Only PDF files are allowed.";
        } else {
            $upload_dir = 'uploads/offer_letters/';
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }

            $file_name = basename($_FILES['offer_letter_file']['name']);
            $safe_name = preg_replace('/[^a-zA-Z0-9_\.-]/', '_', $file_name);
            $file_path = $upload_dir . uniqid() . "_" . $safe_name;

            if (move_uploaded_file($_FILES['offer_letter_file']['tmp_name'], $file_path)) {
                if (!empty($offer_letter_file) && file_exists($offer_letter_file)) {
                    unlink($offer_letter_file);
                }
                $offer_letter_file = $file_path;
            } else {
                $error = "Failed to upload file.";
            }
        }
    }

    if (!$error) {
        $sql = "INSERT INTO offer_letters (applicant_id, offer_status, offer_letter_file)
                VALUES (?, ?, ?)
                ON DUPLICATE KEY UPDATE offer_status = VALUES(offer_status), offer_letter_file = VALUES(offer_letter_file)";
        $stmt = $con->prepare($sql);
        $stmt->bind_param("iss", $applicant_id, $offer_status, $offer_letter_file);

        if ($stmt->execute()) {
            $stmt->close();
            header("Location: offer_letters.php?updated=1");
            exit;
        } else {
            $error = "Database error: " . $stmt->error;
            $stmt->close();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Edit Offer Letter - <?= htmlspecialchars($applicant['name']); ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"/>

    <style>
        * {
            box-sizing: border-box;
        }
        body {
            margin: 0;
            padding: 20px;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #1e3c72, #2a5298);
            color: #f0f4f8;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .container {
            background: #ffffff;
            color: #1e3c72;
            max-width: 600px;
            width: 100%;
            margin: 40px 15px;
            padding: 35px 30px 40px 30px;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.25);
            border: 3px solid #2a5298;
        }

        h2 {
            text-align: center;
            color: #2a5298;
            margin-bottom: 30px;
            font-weight: 700;
            font-size: 28px;
            letter-spacing: 1px;
        }

        h2 i {
            margin-right: 10px;
            color: #1e3c72;
        }

        label {
            font-weight: 600;
            display: block;
            margin-top: 20px;
            font-size: 16px;
            color: #27496d;
        }

        select, input[type="file"] {
            width: 100%;
            padding: 12px 14px;
            margin-top: 8px;
            border: 2px solid #2a5298;
            border-radius: 10px;
            font-size: 16px;
            background: #e1ecff;
            color: #1e3c72;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        select:focus, input[type="file"]:focus {
            border-color: #1e3c72;
            outline: none;
            background-color: #c3d7ff;
            color: #142850;
        }

        .current-file {
            margin-top: 12px;
            font-size: 16px;
            font-weight: 600;
            color: #1e3c72;
            user-select: none;
        }

        .current-file a {
            color: #27496d;
            text-decoration: none;
            font-weight: 700;
            transition: color 0.3s ease;
        }

        .current-file a:hover {
            text-decoration: underline;
            color: #1e3c72;
        }

        input[type="submit"] {
            margin-top: 35px;
            background: linear-gradient(135deg, #2a5298, #1e3c72);
            color: white;
            font-size: 18px;
            padding: 14px 0;
            border: none;
            width: 100%;
            border-radius: 12px;
            cursor: pointer;
            font-weight: 700;
            box-shadow: 0 8px 20px rgba(42, 82, 152, 0.6);
            transition: background 0.4s ease;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
        }

        input[type="submit"]:hover {
            background: linear-gradient(135deg, #1e3c72, #12294d);
        }

        input[type="submit"] i {
            font-size: 20px;
        }

        .back-link {
            display: block;
            text-align: center;
            margin-top: 30px;
            color: #2a5298;
            text-decoration: none;
            font-weight: 600;
            font-size: 16px;
            transition: color 0.3s ease;
            user-select: none;
        }

        .back-link i {
            margin-right: 8px;
        }

        .back-link:hover {
            text-decoration: underline;
            color: #1e3c72;
        }

        .error {
            background: #ffe6e6;
            border-left: 6px solid #e60000;
            color: #b00000;
            padding: 14px 18px;
            margin-bottom: 20px;
            border-radius: 10px;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 15px;
            user-select: none;
        }

        .error i {
            font-size: 20px;
        }

        p.applicant-info {
            font-size: 17px;
            font-weight: 600;
            margin-bottom: 20px;
            color: #27496d;
            user-select: none;
        }

        @media (max-width: 520px) {
            .container {
                margin: 20px 15px;
                padding: 25px 20px 30px 20px;
            }
            h2 {
                font-size: 24px;
                margin-bottom: 25px;
            }
            label {
                font-size: 15px;
                margin-top: 16px;
            }
            select, input[type="file"] {
                font-size: 15px;
                padding: 10px 12px;
            }
            input[type="submit"] {
                font-size: 16px;
                padding: 12px 0;
            }
            p.applicant-info {
                font-size: 15px;
                margin-bottom: 15px;
            }
            .back-link {
                font-size: 15px;
                margin-top: 25px;
            }
        }
    </style>
</head>
<body>

<div class="container" role="main" aria-labelledby="formTitle">
    <h2 id="formTitle"><i class="fa-solid fa-pen-to-square"></i> Edit Offer Letter Status</h2>

    <?php if ($error): ?>
        <div class="error" role="alert"><i class="fa-solid fa-triangle-exclamation"></i> <?= htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <p class="applicant-info" aria-label="Applicant Info">
        <strong>Applicant:</strong> <?= htmlspecialchars($applicant['name']); ?> 
        (<?= htmlspecialchars($applicant['passport_no']); ?>)
    </p>

    <form method="POST" enctype="multipart/form-data" novalidate>
        <label for="offer_status"><i class="fa-solid fa-clipboard-list"></i> Offer Status</label>
        <select name="offer_status" id="offer_status" required aria-required="true" aria-describedby="statusHelp">
            <option value="Received" <?= ($applicant['offer_status'] === 'Received') ? 'selected' : ''; ?>>Received</option>
            <option value="Rejected" <?= ($applicant['offer_status'] === 'Rejected') ? 'selected' : ''; ?>>Rejected</option>
            <option value="Pending" <?= (empty($applicant['offer_status']) || $applicant['offer_status'] === 'Pending') ? 'selected' : ''; ?>>Pending</option>
        </select>
        <small id="statusHelp" style="color:#27496d; font-size:13px; margin-top:4px; display:block;">
            Select the current status of the offer letter.
        </small>

        <label for="offer_letter_file" style="margin-top: 25px;">
            <i class="fa-solid fa-file-pdf"></i> Upload Offer Letter (PDF)
        </label>
        <input type="file" name="offer_letter_file" id="offer_letter_file" accept="application/pdf" aria-describedby="fileHelp">

        <small id="fileHelp" style="color:#27496d; font-size:13px; margin-top:4px; display:block;">
            Choose a PDF file to upload or replace the current offer letter.
        </small>

        <?php if (!empty($applicant['offer_letter_file']) && file_exists($applicant['offer_letter_file'])): ?>
            <div class="current-file" aria-live="polite" aria-atomic="true">
                <i class="fa-solid fa-file-circle-check"></i> Current file: 
                <a href="<?= htmlspecialchars($applicant['offer_letter_file']); ?>" target="_blank" rel="noopener noreferrer" aria-label="View current offer letter PDF">
                    <i class="fa-solid fa-file-pdf"></i> View PDF
                </a>
            </div>
        <?php endif; ?>

        <input type="submit" value="Update Offer Letter" aria-label="Update Offer Letter">
    </form>

    <a href="offer_letters.php" class="back-link"><i class="fa-solid fa-arrow-left"></i> Back to Offer Letters</a>
</div>

</body>
</html>
