<?php
session_start();
require_once "main.php";
Logger::configure('log4php.xml');
$log = Logger::getLogger('uploaddoc');
global $db;
if ($_SESSION['access']<3){
    $zid = $_POST['masterid'];
    $comz = $_SESSION['comnum'];
    $fileName = $_FILES['userfile']['name'];
    $tmpName = $_FILES['userfile']['tmp_name']; 
    $target_path = 'uploads'.trim($comz).'/';
    if(!is_dir($target_path)) {
        mkdir($target_path);
    }
    $target_path = $target_path . $zid . basename( $_FILES['userfile']['name']); 
    if (!file_exists($target_path)) {
        if(move_uploaded_file($_FILES['userfile']['tmp_name'], $target_path)) {
            echo "The file ".  basename( $_FILES['userfile']['name']). " has been uploaded";
            $sql = 'INSERT INTO xat ( id, masterid, filename ) VALUES ( NULL, "'.$zid.'","'.$zid.$_FILES['userfile']['name'].'");';
            $st = $db->prepare($sql);
            $st->execute();
            //$log->info($_GET['submitType'].' - user = '.$_SESSION['user'].' - '.$_SESSION['comnum'].' = '.$_GET['id']);
            $log->info( (!empty($_GET['submitType']) ? $_GET['submitType'] : null).' - user = '.$_SESSION['user'].' - '.$_SESSION['comnum'].' = '.(!empty($_GET['id']) ? $_GET['id'] : null));            
     /* 
     * fix for undefined index. merickk
     */
        } else {
            $log->warn((!empty($_GET['submitType']) ? $_GET['submitType'] : null).' - user = '.$_SESSION['user'].' - '.$_SESSION['comnum'].' = '.(!empty($_GET['id']) ? $_GET['id'] : null));
            echo "There was an error uploading the file, please try again!";
        }
    } else {
        $log->info((!empty($_GET['submitType']) ? $_GET['submitType'] : null).' - user = '.$_SESSION['user'].' - '.$_SESSION['comnum'].' = '.(!empty($_GET['id']) ? $_GET['id'] : null).' X1 ');
        echo "The file already exists on the server.  If the file doesn't appear in the list, please submit a trouble ticket or contact WtrFlw!";
    }
} else {
?>
    <script>alert('You do not have a high enough access level to post payments\n\
                   or charges!\n\
                   Please see your administrator.');
    </script>
<?php    
}
////echo 'File: <b>' . $fileName . '</b> was uploaded succesfully.<br>';
?>
