<?php
    header('Content-Type: application/json');
    
    if(isset($_GET['remove']) && trim($_GET['remove']) == 'yes' && isset($_POST['file_name']) && strlen(trim($_POST['file_name'])) > 3){
        $deleteFile = $_SERVER['DOCUMENT_ROOT'].'/uploads/files/'.trim($_POST['file_name']);
        
        if(file_exists($deleteFile)){
            unlink($deleteFile);
        }
        
        echo json_encode([
            'message' => 'The file removed successfully.',
            'status' => 1
        ],true);
        exit;
    }
    
    
    if(!isset($_FILES['file']['name'])){
        echo json_encode([
            'message' => 'Wrong request. Please select a file to upload.',
            'status' => 0
        ],true);
        
        exit;
    }
    
    //getting file name
    $file_name =  $_FILES['file']['name'];
    
    // getting temp_name of file
    $tmp_name = $_FILES['file']['tmp_name'];
    
    // making file name dynamic by adding time before file name
    // $file_up_name = time().'_'.$file_name;
    
     $file_up_name =  $file_name ;
    
    // $allowed = ['gif', 'png', 'jpg', 'mp3', 'mp4', 'webp', 'webm', 'wav', 'aac', 'opus'];
    $allowed = ['mp3'];
    $ext = pathinfo($file_name, PATHINFO_EXTENSION);
    
    if (!in_array($ext, $allowed)) {
        echo json_encode([
            'message' => 'The '.$ext.' file extension not allowed.',
            'status' => 0,
            'new_name' => null
        ],true);
        
        exit;
    }
    
    $moveTo = $_SERVER['DOCUMENT_ROOT'].'/uploads/files/'.$file_up_name;
    
    //moving file to the specified folder with dynamic name
    move_uploaded_file($tmp_name, $moveTo);
    
    // Get website protocol
    $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    
    // Get website url
    $url = $protocol.$_SERVER['HTTP_HOST'];
    $url = trim($url, '/').'/uploads/files/'.$file_up_name;
    
    echo json_encode([
        'message' => 'The file has been uploaded successfully',
        'status' => 1,
        'name' => $file_name,
        'new_name' => $file_up_name,
        'url' => $url
    ],true);
    
    exit;
?>
