<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8"); // Set response type to JSON
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// Start session
session_start();
include_once '../config/database.php';
include_once '../objects/user.php';

// Initialize DB connection
$database = new Database();
$db = $database->getConnection();

// Initialize User object
$user = new User($db);

// Handle posted data
$user->staff_id = $_POST['cboStaff'];
$user->username = $_POST['txtUserName'];
$user->userrole_id = $_POST['cboUserRole'];
$user->password = $_POST['txtPassword'];

// Handle file upload
$targetPath = "";
if (!empty($_FILES['image'])) {
    // Check if there were any errors during the upload process
    if ($_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);

        // If the file extension is valid
        if (!empty($ext)) {
            $newname = date("Y-m-d_H-i-s") . "." . $ext;
            $targetPath = './upload/' . $newname;

            // Ensure the upload directory exists and move the uploaded file
            if (!is_dir('./upload/')) {
                mkdir('./upload/', 0777, true);
            }

            // Attempt to move the uploaded file
            if (move_uploaded_file($_FILES['image']['tmp_name'], $targetPath)) {
                $user->profilepicture = $targetPath; // Store file path in user object
            } else {
                // Return error if the file couldn't be moved
                echo json_encode(['message' => 'error_upload']);
                exit;
            }
        } else {
            // Handle case where the file doesn't have an extension
            if ($_POST['formState'] == "Create") {
                $targetPath = "/upload/dummy_user.png";
                $user->profilepicture = $targetPath;
            }
        }
    } else {
        if ($_POST['formState'] == "Create") {
            $targetPath = "./upload/dummy_user.png";
            $user->profilepicture = $targetPath;
        }
    }
}


// If creating a new user
if ($_POST['formState'] == "Create") {
    if ($user->exist2()) {
        echo json_encode(['message' => 'duplicate']); // Return JSON response
    } else if ($user->create()) {
        echo json_encode(['message' => 'created']); // Return JSON response
    } else {
        echo json_encode(['message' => 'error_create']); // Return JSON response
    }
} else {
    $user->id = $_POST['txtAccountId'];
    // If editing an existing user
    if ($user->update()) {
        echo json_encode(['message' => 'updated']); // Return JSON response
    } else {
        echo json_encode(['message' => 'error_edit']); // Return JSON response
    }
}
?>
