<?php

ini_set('upload_max_filesize', '10M');

function uploadFiles($files, $option = [])
{
    $year      = date('Y');
    $m         = date('m');
    $root_path = upload_folder . 'almas/';

    if (!file_exists($root_path . $year)) {
        mkdir($root_path . $year, 0777, true);
    }
    $newpath = $root_path . $year . '/' . $m;

    if (!file_exists($newpath)) {
        mkdir($newpath, 0777, true);
    }
    $path = $newpath . '/';

    $errors = [];
    $status = [];
    for ($i = 0; $i < count($files['name']);$i++) {
        $file_name = $files['name'][$i];
        $file_size = $files['size'][$i];
        $file_tmp  = $files['tmp_name'][$i];
        $file_type = $files['type'][$i];
        $file_ext  = strtolower(end(explode('.', $files['name'][$i])));

        if ($option['excel']) {
            $expensions = ['xls','xl','xlsx'];
        } else {
            $expensions = ['jpeg','jpg','png','doc','pdf','xls','xl'];
        }

        if (in_array($file_ext, $expensions) == false) {
            $errors[$i] = 'extension not allowed, please choose a JPEG or PNG file.';
        }

        if ($file_size > 2097152) {
            $errors[$i] = 'File size must be excately 2 MB';
        }

        //$file_name = time().'.'.$file_ext;
        if (empty($errors[$i]) == true) {
            $target              = $path . $file_name;
            $status['files'][$i] = $target;
            move_uploaded_file($file_tmp, $path . $file_name);
        } else {
            $status['files'][$i] = 'error';
            $status['error']     = $errors[$i];
        }
    }

    return $status;
}
