<?php
session_start();

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: application/json; charset=utf-8');

if (isset($_POST['user_id']) && isset($_POST['auth']) && isset($_POST['application_id']) && isset($_FILES['file'])) {
    require 'config.php';

    // Sanitize input
    function check_input($par) {
        return htmlspecialchars(stripslashes(trim($par)));
    }

    $auth = check_input($_POST['auth']);
    $user_id = check_input($_POST['user_id']);
    $application_id = check_input($_POST['application_id']);

    $auth = mysqli_escape_string($con, $auth);
    $user_id = mysqli_escape_string($con, $user_id);
    $application_id = mysqli_escape_string($con, $application_id);

    // Check if the user exists
    $sql_user = "SELECT * FROM users WHERE user_id = '$user_id' AND auth = '$auth'";
    $result_user = $con->query($sql_user);

    if ($result_user && $result_user->num_rows === 1) {
        $user_row = $result_user->fetch_assoc();
        $phone = $user_row['phone'];
        $email = $user_row['email'];
        $firstname = $user_row['firstname'];
        $lastname = $user_row['lastname'];

        // Check if the student exists
        $sql_student = "SELECT * FROM exam_applications WHERE user_id = '$user_id' AND application_id = '$application_id'";
        $result_student = $con->query($sql_student);

        if ($result_student && $result_student->num_rows === 1) {
            // File upload processing
            $file = $_FILES['file'];
            $allowed_extensions = ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx'];
            $max_file_size = 5 * 1024 * 1024; // 5 MB

            $file_name = $file['name'];
            $file_tmp = $file['tmp_name'];
            $file_size = $file['size'];
            $file_error = $file['error'];

            $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
            $file_new_name = $user_id . "_" . time() . "." . $file_ext;
            $upload_dir = "../others/";
            $upload_path = $upload_dir . $file_new_name;

            if ($file_error === 0) {
                if (in_array($file_ext, $allowed_extensions)) {
                    if ($file_size <= $max_file_size) {
                        if (move_uploaded_file($file_tmp, $upload_path)) {
                            $file_url = $p_url . "/others/" . $file_new_name;

                            // Update user and student records
                           // $sql_update_user = $con->query("UPDATE users SET id_doc = '$file_url' WHERE user_id = '$user_id' AND auth = '$auth'");
                            $sql_update_student = $con->query("UPDATE exam_applications SET  other_doc = '$file_url' WHERE user_id = '$user_id' AND application_id = '$application_id'");

                            if ($sql_update_student) {
                                $suc = "File uploaded and records updated successfully.";
                                $status = true;
                            } else {
                                $suc = "Failed to update records: " . $con->error;
                                $status = false;
                            }
                        } else {
                            $suc = "Failed to move uploaded file.";
                            $status = false;
                        }
                    } else {
                        $suc = "File size exceeds the limit of 5MB.";
                        $status = false;
                    }
                } else {
                    $suc = "Invalid file type. Allowed types: " . implode(', ', $allowed_extensions);
                    $status = false;
                }
            } else {
                $suc = "Error during file upload.";
                $status = false;
            }
        } else {
            $suc = "Application record does not exist.";
            $status = false;
        }
    } else {
        $suc = "User does not exist.";
        $status = false;
    }

    $con->close();
    echo json_encode(['status' => $status, 'success' => $suc]);
} else {
    echo json_encode(['status' => false, 'success' => 'Invalid request.']);
}
