<?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 'userDoc.php';

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

// initialize object
$userDoc = new UserDoc($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['coachID']) && !empty($_FILES['doc'])) {
            $userDoc->coachID = htmlspecialchars(strip_tags($_POST['coachID']));
            $userDoc->docType = htmlspecialchars(strip_tags($_POST['docType']));
            
            $docName = htmlspecialchars(strip_tags($_POST['docName']));
            
            if(!empty($docName)) $userDoc->docName = $docName;
            
            $userDoc->document = $_FILES['doc'];
            
            // Handle file upload
            if ($_FILES['doc']['error'] == UPLOAD_ERR_OK) {
                // Upload profile image in the database
                $result = $userDoc->uploadUserDoc();
                if ($result == false) {
                    http_response_code(404);
                    echo json_encode(array("message" => "File 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 file(s) are required."));
        }
        
    default:
        http_response_code(405);
        echo json_encode(array("message" => "Invalid Method"));
        break;
 }

?>