<?php
require_once('../config.php');
require_once('advancenews-page-sys.php');
$user_id = $the_user['admin_id'];
header('Content-type:application/json;charset=utf-8');

try {
    if (
        !isset($_FILES['file']['error']) ||
        is_array($_FILES['file']['error'])
    ) {
        throw new RuntimeException('Invalid parameters.');
    }

    switch ($_FILES['file']['error']) {
        case UPLOAD_ERR_OK:
            break;
        case UPLOAD_ERR_NO_FILE:
            throw new RuntimeException('No file sent.');
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            throw new RuntimeException('Exceeded filesize limit.');
        default:
            throw new RuntimeException('Unknown errors.');
    }

    // Original filename
    $originalFilename = $_FILES['file']['name'];

    // Generate a unique filename with counter
    $counter = 1;
    $newFilename = $originalFilename;

    while (file_exists("../../uploads/$newFilename")) {
        $newFilename = sprintf('%s_%d', pathinfo($originalFilename, PATHINFO_FILENAME), $counter);
        $newFilename .= '.' . pathinfo($originalFilename, PATHINFO_EXTENSION);
        $counter++;
    }

    $filepath = sprintf('../../uploads/%s', $newFilename);

    if (move_uploaded_file($_FILES['file']['tmp_name'], $filepath)) {
      $file_url = $site_domain.'uploads/'.$newFilename;
      $tt_file_extention = isImage($newFilename) ;
      $entry_sql = "INSERT INTO tt_media (MediaName, MediaUploader, MediaURL, MediaType) VALUES ('$newFilename', '$user_id', '$file_url', '$tt_file_extention') ";
      $entry_doc = $conn->prepare($entry_sql);
      $entry_doc->execute();

    }else {
      throw new RuntimeException('Failed to move uploaded file.');
    }

    // All good, send the response
    echo json_encode([
        'status' => 'ok',
        'path' => $filepath,
        'file_name' => $newFilename,
    ]);

} catch (RuntimeException $e) {
	// Something went wrong, send the err message as JSON
	http_response_code(400);

	echo json_encode([
		'status' => 'error',
		'message' => $e->getMessage()
	]);
}
