<?php
header('content-type:application/json');
include($_SERVER['DOCUMENT_ROOT'] . "/API-Others/connection/conn.php");

$unique_user_id = addslashes(isset($_POST['unique_user_id']) ? $_POST['unique_user_id'] : '');
$reverted_by =  addslashes(isset($_GET['reverted_by']) ? $_GET['reverted_by'] : '');
$sql = "INSERT INTO staff (unique_user_id, profile_photo, title, first_name, middle_name, last_name, gender, dob, nationality, address, phone, whatsapp_no, email, role, qualification, department, employment_status, salary_wage_information, bank_account_details, ssnit_number, emergency_phone, safety_training_completion, medical_conditions_allergies, status, added_by, date_of_application) SELECT unique_user_id, profile_photo, title, first_name, middle_name, last_name, gender, dob, nationality, address, phone, whatsapp_no, email, role, qualification, department, employment_status, salary_wage_information, bank_account_details, ssnit_number, emergency_phone, safety_training_completion, medical_conditions_allergies, 'Active', '$reverted_by', date_of_application FROM terminatedappointments WHERE unique_user_id = '$unique_user_id'";
if (mysqli_query($conn, $sql)) {
} else {
}

$query = "SELECT * FROM terminatedappointments WHERE unique_user_id = '$unique_user_id'";
$result = mysqli_query($conn, $query);
while ($spec = mysqli_fetch_assoc($result)) {
    $sql = "INSERT INTO users (unique_user_id, role, profile_photo, nationality, living_town, fullname, dob, email, phone, whatsapp_no, address, status, date_added) SELECT unique_user_id, role, profile_photo, nationality, address, '".$spec["first_name"]." ".$spec["middle_name"]." ".$spec["last_name"]."', dob, email, phone, whatsapp_no, address, 'Active', '".DATE("Y-m-d")."' FROM terminatedappointments WHERE unique_user_id = '$unique_user_id'";
    if (mysqli_query($conn, $sql)) {
        $statusCode = 200;
        $statusMessage = "Staff reverted successfully";
    } else {
        $statusCode = 1042;
        $statusMessage = mysqli_error($conn);
    }
}

$result = mysqli_query($conn, "DELETE FROM terminatedappointments WHERE unique_user_id='$unique_user_id'");

$resultData = array('code' => $statusCode, 'message' => $statusMessage);
echo json_encode($resultData);
