<?php
include '../connection.php';

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

header('Content-Type: application/json');

// Function to handle file upload
function uploadFile($file) {
    if ($file['type'] == 'application/pdf') {
        $uploadDir = '../uploads/Jobs/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        $fileName = uniqid('job_', true) . '.pdf';
        $filePath = $uploadDir . $fileName;
        if (move_uploaded_file($file['tmp_name'], $filePath)) {
            return $fileName;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action']) && $_POST['action'] === 'insert') {
        $full_subject = $_POST['full_subject'];
        $starting_date = $_POST['starting_date'];
        $ending_date = $_POST['ending_date'];

        error_log("full_subject: $full_subject");
        error_log("starting_date: $starting_date");
        error_log("ending_date: $ending_date");

        $check_sql = "SELECT * FROM recruitments WHERE full_subject = ? AND starting_date = ? AND ending_date = ?";
        $check_stmt = $conn->prepare($check_sql);
        $check_stmt->bind_param("sss", $full_subject, $starting_date, $ending_date);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();
        
        if ($check_result->num_rows > 0) {
            echo json_encode(['message' => 'Duplicate record found']);
        } else {
            if (isset($_FILES['file_location']) && $_FILES['file_location']['error'] === UPLOAD_ERR_OK) {
                $fileName = uploadFile($_FILES['file_location']);
                if ($fileName) {
                    error_log("file uploaded: $fileName");

                    $sql = "INSERT INTO recruitments (full_subject, starting_date, ending_date, file_location, status) VALUES (?, ?, ?, ?, ?)";
                    $stmt = $conn->prepare($sql);
                    $status = 1; // Set status
                    $stmt->bind_param("sssss", $full_subject, $starting_date, $ending_date, $fileName, $status);

                    error_log("SQL Query: $sql");
                    error_log("Parameters: full_subject=$full_subject, starting_date=$starting_date, ending_date=$ending_date, fileName=$fileName, status=$status");

                    if ($stmt->execute()) {
                        error_log("Record inserted successfully");
                        echo json_encode(['message' => 'Record inserted successfully']);
                    } else {
                        error_log("Error: " . $stmt->error);
                        echo json_encode(['message' => 'Error: ' . $stmt->error]);
                    }

                    $stmt->close();
                } else {
                    echo json_encode(['message' => 'File upload failed. Please upload a valid PDF file.']);
                }
            } else {
                echo json_encode(['message' => 'No file uploaded or there was an error with the file.']);
            }
        }
        $check_stmt->close();
    }

    if (isset($_POST['action']) && $_POST['action'] === 'delete') {
        $id = $_POST['id'];

        $get_file_sql = "SELECT file_location FROM recruitments WHERE ID = ?";
        $get_file_stmt = $conn->prepare($get_file_sql);
        $get_file_stmt->bind_param("i", $id);
        $get_file_stmt->execute();
        $get_file_result = $get_file_stmt->get_result();

        if ($get_file_result->num_rows > 0) {
            $file_row = $get_file_result->fetch_assoc();
            $file_name = $file_row['file_location'];
            $file_path = '../uploads/Jobs/' . $file_name;

            if (file_exists($file_path)) {
                unlink($file_path);
            }
        }

        $get_file_stmt->close();

        $sql = "DELETE FROM recruitments WHERE ID = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $id);

        if ($stmt->execute()) {
            echo json_encode(['message' => 'Record and file deleted successfully']);
        } else {
            echo json_encode(['message' => 'Error: ' . $stmt->error]);
        }

        $stmt->close();
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $sql = "SELECT * FROM recruitments";
    $result = $conn->query($sql);

    $recruitments = [];
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $recruitments[] = $row;
        }
    }

    echo json_encode($recruitments);
}

$conn->close();
?>
