<?php
include '../connection.php'; // Ensure this path is correct for your setup

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Personal Information
    $name = $_POST['name'];
    $fatherName = $_POST['fatherName'];
    $address = $_POST['address'];
    $domicile = $_POST['domicile'];
    $cnic = $_POST['cnic'];
    $phoneNumber = $_POST['phoneNumber'];
    $selectedProject = $_POST['selectedProject'];

    // Insert personal information into Job_Applicants table
    $stmt = $conn->prepare("INSERT INTO Job_Applicants (Name, FatherName, Address, Domicile, CNIC, PhoneNumber, ProjectID) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param('ssssssi', $name, $fatherName, $address, $domicile, $cnic, $phoneNumber, $selectedProject);
    if ($stmt->execute()) {
        $applicantID = $stmt->insert_id;
    } else {
        echo "Error: " . $stmt->error;
        exit;
    }
    $stmt->close();

    // Qualifications
    if (isset($_POST['degree'])) {
        foreach ($_POST['degree'] as $index => $degree) {
            $institution = $_POST['institution'][$index];
            $yearOfCompletion = $_POST['yearOfCompletion'][$index];
            $totalMarks = $_POST['totalMarks'][$index];
            $obtainedMarks = $_POST['obtainedMarks'][$index];
            $grade = $_POST['grade'][$index];

            $stmt = $conn->prepare("INSERT INTO Applicant_Qualification (ApplicantID, Degree, Institution, YearOfCompletion, TotalMarks, ObtainedMarks, Grade) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param('isssiis', $applicantID, $degree, $institution, $yearOfCompletion, $totalMarks, $obtainedMarks, $grade);
            $stmt->execute();
            $stmt->close();
        }
    }

    // Experience
    if (isset($_POST['jobTitle'])) {
        foreach ($_POST['jobTitle'] as $index => $jobTitle) {
            if (!empty($jobTitle)) {
                $organization = $_POST['organization'][$index];
                $startDate = $_POST['startDate'][$index];
                $endDate = $_POST['endDate'][$index];
                $responsibilities = $_POST['responsibilities'][$index];

                $stmt = $conn->prepare("INSERT INTO Applicant_Experience (ApplicantID, JobTitle, Organization, StartDate, EndDate, Responsibilities) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->bind_param('isssss', $applicantID, $jobTitle, $organization, $startDate, $endDate, $responsibilities);
                $stmt->execute();
                $stmt->close();
            }
        }
    }

    echo 'Application submitted successfully!';
}
?>
