<?php
include 'db.php';

// Get job ID
$job_id = isset($_GET['job_id']) ? intval($_GET['job_id']) : 0;

// Fetch job
$jobQuery = mysqli_query($conn, "SELECT * FROM careers WHERE id = $job_id LIMIT 1");
$job = mysqli_fetch_assoc($jobQuery);

if (!$job) {
    die("Invalid Job ID.");
}

$errors = [];
$successMessage = "";

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $name  = trim($_POST['name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);

    // Validation
    if ($name == "")   
        $errors[] = "Name is required.";

    if ($email == "")  
        $errors[] = "Email is required.";
    elseif (!filter_var($email, FILTER_VALIDATE_EMAIL))  
        $errors[] = "Invalid email address.";

    if ($phone == "")  
        $errors[] = "Phone number is required.";
    elseif (!preg_match('/^\d{10}$/', $phone))  
        $errors[] = "Phone number must be exactly 10 digits.";

    // Resume validation
    if (!isset($_FILES['resume']) || $_FILES['resume']['size'] == 0) {
        $errors[] = "Resume (PDF) is required.";
    } else {
        $ext = strtolower(pathinfo($_FILES['resume']['name'], PATHINFO_EXTENSION));
        if ($ext != "pdf") {
            $errors[] = "Only PDF resumes are allowed.";
        }
    }

    // Save if no errors
    if (empty($errors)) {

        $uploadDir = "uploads/resumes/";
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $fileName = time() . "_" . basename($_FILES["resume"]["name"]);
        $targetFile = $uploadDir . $fileName;

        move_uploaded_file($_FILES["resume"]["tmp_name"], $targetFile);

        // Insert application
        $stmt = $conn->prepare("
            INSERT INTO applications (job_id, name, email, phone, resume)
            VALUES (?, ?, ?, ?, ?)
        ");
        $stmt->bind_param("issss", $job_id, $name, $email, $phone, $fileName);
        $stmt->execute();

        $successMessage = "Your application has been submitted successfully!";
    }
}

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" type="image/png" sizes="16x16" href="asset/images/mk logo1.png">
    <title>Apply - <?= htmlspecialchars($job['title']) ?> | MK Trading</title>

    <link rel="stylesheet" href="assets/css/style.css">

    <style>
        .job-details-box {
    background: #fff;
    padding: 30px;
    border-radius: 12px;
    border: 1px solid #e5e5e5;
    box-shadow: 0px 4px 15px rgba(0,0,0,0.06);
    margin-bottom: 35px;
}

.job-details-box h2 {
    margin-bottom: 18px;
    font-size: 26px;
    font-weight: 600;
}

.job-info {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px 25px;
    margin-bottom: 20px;
}

.job-info span {
    font-size: 1rem;
    padding: 10px 14px;
    background: #f8f8f8;
    border-radius: 8px;
    border: 1px solid #ececec;
}

.job-description {
    margin-top: 15px;
    line-height: 1.7rem;
    font-size: 1rem;
    background: #fafafa;
    padding: 15px;
    border-radius: 8px;
    border: 1px solid #ececec;
}

/* Application form */
.application-form-container {
    background: #fff;
    padding: 30px;
    border-radius: 12px;
    border: 1px solid #e5e5e5;
    box-shadow: 0px 4px 15px rgba(0,0,0,0.06);
}

.form-row {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
}

.form-group {
    flex: 1;
}

.form-group label {
    font-size: 0.95rem;
    margin-bottom: 6px;
    display: block;
    font-weight: 500;
}

.form-input,
input[type="file"] {
    width: 100%;
    padding: 12px;
    border-radius: 8px;
    border: 1px solid #ccc;
    font-size: 1rem;
}

.btn-submit-application {
    background: #333;
    color: #fff;
    padding: 12px 22px;
    font-size: 1rem;
    border-radius: 8px;
    border: none;
    cursor: pointer;
    transition: 0.3s;
}

.btn-submit-application:hover {
    background: #000;
}

/* Responsive */
@media (max-width: 600px) {
    .job-info {
        grid-template-columns: 1fr;
    }
    .form-row {
        flex-direction: column;
    }
}

    </style>
</head>

<body>

<?php include 'nav.php'; ?>

<section class="page-header">
    <div class="container">
        <h1>Apply for <?= htmlspecialchars($job['title']) ?></h1>
    </div>
</section>

<section class="content-section">
    <div class="container">

        <!-- =======================
             JOB DETAILS BOX
        ============================== -->
        <div class="job-details-box">

            <h2><?= htmlspecialchars($job['title']) ?></h2>

            <div class="job-info">
                <span><strong>Department:</strong> <?= htmlspecialchars($job['department']) ?></span>
                <span><strong>Location:</strong> <?= htmlspecialchars($job['location']) ?></span>
                <span><strong>Experience:</strong> <?= htmlspecialchars($job['experience']) ?></span>

                <?php if (!empty($job['salary'])): ?>
                    <span><strong>Salary:</strong> <?= htmlspecialchars($job['salary']) ?></span>
                <?php endif; ?>
            </div>

            <div class="job-description">
    <?= nl2br(htmlspecialchars($job['description'])) ?>
</div>

        </div>

        <!-- =======================
             APPLICATION FORM
        ============================== -->
        <div class="application-form-container">

            <?php if (!empty($errors)): ?>
                <div class="error-box" style="background:#ffe6e6;padding:15px;border-left:4px solid red;">
                    <ul>
                        <?php foreach ($errors as $e): ?>
                            <li><?= $e ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <?php if ($successMessage): ?>
                <div class="success-box" style="background:#e6ffe6;padding:15px;border-left:4px solid green;">
                    <?= $successMessage ?>
                </div>
            <?php endif; ?>

            <?php if (!$successMessage): ?>
            <form method="POST" enctype="multipart/form-data" class="application-form">

                <div class="form-row">
                    <div class="form-group">
                        <label>Your Name</label>
                        <input type="text" name="name" class="form-input" required>
                    </div>

                    <div class="form-group">
                        <label>Email Address</label>
                        <input type="email" name="email" class="form-input" required>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label>Phone Number</label>
                        <input type="tel" name="phone" class="form-input" required>
                    </div>

                    <div class="form-group">
                        <label>Resume (PDF Only)</label>
                        <input type="file" name="resume" accept=".pdf" required>
                    </div>
                </div>

                <button type="submit" class="btn-submit-application">Submit Application</button>

            </form>
            <?php endif; ?>

        </div>

    </div>
</section>

<?php include 'footer.php'; ?>

</body>
</html>
