<?php

require 'helper/converter.php';

$file = empty($_FILES['font']) ? false : $_FILES['font'];
if (!(isset($file['error']) && isset($file['name']) && isset($file['type']) && isset($file['tmp_name']) && isset($file['size']))) {
    die();
}

// Does the file have the right extension?
$ext = substr($_FILES['font']['name'], -3);
$ext = strtolower($ext);
if (!($ext == 'ttf' || $ext == 'otf')) {
    $response = array(
        'error' => 1,
        'msg' => 'File has the wrong extension. The correct file extension is .ttf or .otf',
    );
    die(json_encode($response));
}

if ($_FILES['font']['size'] > 1024000) {
    $response = array(
        'error' => 1,
        'msg' => 'File name can\'t be bigger than 1MB',
    );
    die(json_encode($response));
}

//fix filenames
$_FILES['font']['name'] = trim($_FILES['font']['name']);
$_FILES['font']['name'] = str_replace(" ", "_", $_FILES['font']['name']);
$_FILES['font']['name'] = preg_replace('#[^A-Za-z0-9_-]#', '', substr($_FILES['font']['name'], 0, strlen($_FILES['font']['name']) - 3)) . '.' . $ext;

$updir = dirname(__FILE__) . '/assets/fonts';
$upfile = dirname(__FILE__) . '/assets/fonts/' . ( $_FILES['font']['name']);

if (file_exists($upfile)) {
    $response = array(
        'error' => 1,
        'msg' => 'The font has already existed',
    );
    die(json_encode($response));
}

//tmp_name is the place where the file has been temporarily stored on the server
if (is_uploaded_file($_FILES['font']['tmp_name'])) {

    if (!is_writable(dirname($updir))) {
        $response = array (
            'error' => 1,
            'msg' => 'Cannot write file! Check permission of assets/fonts folder',
        );
        die(json_encode($response));
    }

    if (!@move_uploaded_file($_FILES['font']['tmp_name'], $upfile)) {
        $response = array(
            'error' => 1,
            'msg' => 'Cannot write file! Check permission of assets/fonts folder',
        );

        die(json_encode($response));
    }

    $convertResult = ($ext == 'ttf' ? AxcotoFontBirdConverterHelper::ttf2eot($upfile) : AxcotoFontBirdConverterHelper::otf2eot($upfile));

//set the permissions on the uploaded file
    chmod($upfile, 0755);
    $response = array(
        'error' => 0,
        'msg' => '<li><span style="font-family: ' . $_FILES['font']['name'] . '">Uploaded ' . $_FILES['font']['name'] . '</span></li>',
        'filename' => $_FILES['font']['name']
    );
    die(json_encode($response));
} else {
    $response = array(
        'error' => 1,
        'msg' => 'Hacking attempt',
    );
    die(json_encode($response));
}