<?php
/**
 * Created by PhpStorm.
 * User: jaskokoyn
 * Date: 4/25/2015
 * Time: 7:58 PM
 */

require('../../inc/db.php');
include('../../inc/functions.php');

$params                 =   getParams();
$output                 =   array('status' => 1);

if(!isset($_FILES['file']) || $_FILES['file']['error'] !== 0){
    dj($output);
}

$file                   =   $_FILES['file'];
$name                   =   get_random_string(16);
$ext                    =   get_extension($file['name']);
$max                    =   $settings['max_upload_size'] * 1000;
$getUserQuery           =   $db->prepare("SELECT `upl_dir` FROM users WHERE id = :uid");
$getUserQuery->execute(array(":uid"  =>  $_SESSION['uid']));
$getUserRow             =   $getUserQuery->fetch(PDO::FETCH_ASSOC);

if($file['size'] > $max){
    dj($output);
}

$upl                    =   $getUserRow['upl_dir'] . "/" . $name . "." . $ext;

if(!move_uploaded_file( $file['tmp_name'], "../../uploads/" . $upl)){
    dj($output);
}

$insertQuery            =   $db->prepare("INSERT INTO user_files(original_file_name,upl_dir,uid)
                                          VALUES( :ofn, :ud, :uid )");
$insertQuery->execute(array(
    ":ofn"              =>  $file['name'],
    ":ud"               =>  $upl,
    ":uid"              =>  $_SESSION['uid']
));

$output['status']                       =   2;
$output['file']                         =   array(
    'id'                                =>  $db->lastInsertId(),
    'original_file_name'                =>  $file['name']
);
dj($output);