<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

// include database and object files
include_once '../config/database.php';
include_once 'profileImg.php';

// instantiate database and product object
$database = new Database();
$db = $database->getConnection();

// initialize object
$profileImg = new ProfileImg($db);

$request_method = $_SERVER["REQUEST_METHOD"];

switch($request_method) { 
        
    case 'POST':
        $data = json_decode(file_get_contents("php://input"));
        // Check if form data is received
        if (!empty($_POST['username']) && !empty($_FILES['profileImg'])) {
            $profileImg->username = htmlspecialchars(strip_tags($_POST['username']));
            $profileImg->profileImg = $_FILES['profileImg'];
            
            $accType = $profileImg->getAccType();
            if ($accType) {
                $profileImg->accType = $accType;
                
                // Handle file upload
                if ($_FILES['profileImg']['error'] == UPLOAD_ERR_OK) {
                    // Upload profile image in the database
                    $result = $profileImg->uploadProfileImg();
                    if ($result == false) {
                        http_response_code(404);
                        echo json_encode(array("message" => "Profile image upload failed."));
                    } else {
                        http_response_code(200);
                        echo json_encode($result);
                    }
                } else {
                    http_response_code(404);
                    echo json_encode(array("message" => "File upload failed."));
                }
            } else {
                http_response_code(400);
                echo json_encode(array("message" => "Username and profile image are required."));
            }
            break;
        
        }
        
    default:
        http_response_code(405);
        echo json_encode(array("message" => "Invalid Method"));
        break;
 }

?>