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

$msg = '';
$msg1 = '';
$target_dir = $_SERVER['DOCUMENT_ROOT'] . "/API/uploads/profile-photos/";
$target = basename($_FILES["profile_photo"]["name"]);
$target_file = $target_dir . basename($_FILES["profile_photo"]["name"]);
$check = getimagesize($_FILES["profile_photo"]["tmp_name"]);
if (move_uploaded_file($_FILES["profile_photo"]["tmp_name"], $target_file)) {
    $msg =  $target;
}


$profile_photo = $target;
$title = addslashes(isset($_POST['title']) ? $_POST['title'] : '');
$first_name = addslashes(isset($_POST['first_name']) ? $_POST['first_name'] : '');
$middle_name = addslashes(isset($_POST['middle_name']) ? $_POST['middle_name'] : '');
$last_name = addslashes(isset($_POST['last_name']) ? $_POST['last_name'] : '');
$fullname = "" . $first_name . " " . $middle_name . " " . $last_name . "";
$gender = addslashes(isset($_POST['gender']) ? $_POST['gender'] : '');
$dob = addslashes(isset($_POST['dob']) ? $_POST['dob'] : '');
$nationality = addslashes(isset($_POST['nationality']) ? $_POST['nationality'] : '');
$address = addslashes(isset($_POST['address']) ? $_POST['address'] : '');
$phone = addslashes(isset($_POST['phone']) ? $_POST['phone'] : '');
$whatsapp_no = addslashes(isset($_POST['whatsapp_no']) ? $_POST['whatsapp_no'] : '');
$email = addslashes(isset($_POST['email']) ? $_POST['email'] : '');
$role = addslashes(isset($_POST['role']) ? $_POST['role'] : '');
$qualification = addslashes(isset($_POST['qualification']) ? $_POST['qualification'] : '');
$department = addslashes(isset($_POST['department']) ? $_POST['department'] : '');
$employment_status = addslashes(isset($_POST['employment_status']) ? $_POST['employment_status'] : '');
$salary_wage_information = addslashes(isset($_POST['salary_wage_information']) ? $_POST['salary_wage_information'] : '');
$bank_account_details = addslashes(isset($_POST['bank_account_details']) ? $_POST['bank_account_details'] : '');
$ssnit_number = addslashes(isset($_POST['ssnit_number']) ? $_POST['ssnit_number'] : '');
$emergency_phone = addslashes(isset($_POST['emergency_phone']) ? $_POST['emergency_phone'] : '');
$safety_training_completion = addslashes(isset($_POST['safety_training_completion']) ? $_POST['safety_training_completion'] : '');
$medical_conditions_allergies = addslashes(isset($_POST['medical_conditions_allergies']) ? $_POST['medical_conditions_allergies'] : '');
$added_by = isset($_POST['added_by']) ? $_POST['added_by'] : '';

$todays_date = DATE("Y-m-d");
if (empty($added_by)) {
    $added_by = "Self";
}
//  $experience_area = isset($_POST['experience_area']) ? $_POST['experience_area'] : '';


$query = "SELECT * FROM staff WHERE email = '$email' or phone = '$phone' or phone = '$whatsapp_no' or whatsapp_no = '$phone' or whatsapp_no = '$whatsapp_no'";
$result = mysqli_query($conn, $query);
$rowCount = mysqli_num_rows($result);
if ($rowCount > 0) {
    $statusCode = 1062;
    $statusMessage = "Entry was not saved. User with the same email, phone or whatsapp number exists!";
} else {
    $firstChar = substr($first_name, 0, 1);
    $tempUsername = "" . $firstChar . "" . $last_name . "";
    function password()
    {
        $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
        $pass = array(); //remember to declare $pass as an array
        $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
        for ($i = 0; $i < 6; $i++) {
            $n = rand(0, $alphaLength);
            $pass[] = $alphabet[$n];
        }
        return implode($pass); //turn the array into a string
    }
    $password = password();

    if (empty($added_by)) {
        $added_by = $mlss_sos_no;
    }


    $query = "SELECT * FROM staff ORDER BY id DESC LIMIT 1";
    $result = mysqli_query($conn, $query);
    $rowCount = mysqli_num_rows($result);
    if ($rowCount > 0) {
        while ($spec = mysqli_fetch_assoc($result)) {
            $sid = $spec['id'] + 1;
            $iddate = Date('y');
            $user_id = "BOOOMERS/$iddate-000-0$sid";
        }
    } else {
        $iddate = Date('y');
        $user_id = "BOOOMERS/$iddate-000-01";
    }


    $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) VALUES ('$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','$added_by','$todays_date')");
    if (mysqli_query($conn, $sql)) {
    } else {

        $statusCode = 1062;
        $statusMessage = mysqli_error($conn);
    }


    $sql = ("INSERT INTO users(unique_user_id, role, nationality, fullname, dob, email, phone, whatsapp_no, username, password, status, date_added) VALUES ('$user_id', '$role', '$nationality', '$fullname', '$dob', '$email', '$phone', '$whatsapp_no', '$tempUsername', '$password','Active','$todays_date')");
    if (mysqli_query($conn, $sql)) {
        $statusCode = 200;
        $statusMessage = "Saved Successfully";
        $tempUsername = $tempUsername;
        $tempPassword = $password;
    } else {
        $statusCode = 1062;
        $statusMessage = mysqli_error($conn);
    }


    foreach ($_FILES['attachment']['tmp_name'] as $key => $tmp_name) {
        $document_type = $_POST['document_type'][$key];
        $start_date = $_POST['start_date'][$key];
        $end_date = $_POST['end_date'][$key];
        $file_name = $key . $_FILES['attachment']['name'][$key];
        $file_size = $_FILES['attachment']['size'][$key];
        $file_tmp = $_FILES['attachment']['tmp_name'][$key];
        $file_type = $_FILES['attachment']['type'][$key];
        if (!empty($document_type)) {
            move_uploaded_file($file_tmp, $_SERVER['DOCUMENT_ROOT'] . "/API/uploads/other-documents/" . $file_name);
            $sql = ("INSERT INTO documents(unique_user_id, document_type, attachment, start_date, end_date, date_added) VALUES ('$user_id','$document_type','$file_name','$start_date', '$end_date','$todays_date')");
            if (mysqli_query($conn, $sql)) {
            } else {
                $statusCode = 1062;
                $statusMessage = mysqli_error($conn);
            }
        }
    }


    foreach ($_POST['skill_experience'] as $key => $skill_experience) {
        $skill_experience = isset($_POST['skill_experience']) ? $_POST['skill_experience'] : '';
        $skill_experience = mysqli_real_escape_string($conn, $skill_experience[$key]);
        if (!empty($skill_experience)) {
            $sql = ("INSERT INTO experience_area(unique_user_id, experience_area, date_added) VALUES ('$user_id', '$skill_experience', '$todays_date')");
            if (mysqli_query($conn, $sql)) {
            } else {
                $statusCode = 1062;
                $statusMessage = mysqli_error($conn);
            }
        }
    }


    foreach ($_POST['job_roles_responsibilities'] as $key => $job_roles_responsibilities) {
        $job_roles_responsibilities = isset($_POST['job_roles_responsibilities']) ? $_POST['job_roles_responsibilities'] : '';
        $date_of_employment_from = isset($_POST['date_of_employment_from']) ? $_POST['date_of_employment_from'] : '';
        $date_of_employment_to = isset($_POST['date_of_employment_to']) ? $_POST['date_of_employment_from'] : '';
        $job_roles_responsibilities = mysqli_real_escape_string($conn, $job_roles_responsibilities[$key]);
        $date_of_employment_from = mysqli_real_escape_string($conn, $date_of_employment_from[$key]);
        $date_of_employment_to = mysqli_real_escape_string($conn, $date_of_employment_to[$key]);
        if (!empty($job_roles_responsibilities)) {
            $sql = ("INSERT INTO work_history(unique_user_id, work_history, date_from, date_to, date_added) VALUES ('$user_id', '$job_roles_responsibilities', '$date_of_employment_from', '$date_of_employment_to', '$todays_date')");
            if (mysqli_query($conn, $sql)) {
            } else {
                $statusCode = 1062;
                $statusMessage = mysqli_error($conn);
            }
        }
    }
}
$resultData = array('code' => $statusCode, 'message' => $statusMessage, 'tempUsername' => $tempUsername, 'tempPassword' => $tempPassword);
echo json_encode($resultData);
