<?php

require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include ('includes/function.php');
//include ('includes/simgeImage.php');

$zdb = $_SESSION["zdbyear_" . $dbname];
$zyear = right($zdb, 4);

$success = "";
$imagedb = "purchimage";
$vouchno = $_POST["vouchno"];
//$imageno = $_POST["imageno"];
//$comp = $_SESSION["comp_" . $dbname];
$myyear = $_SESSION[$myyear];

$path = "images/purchase/".$myyear."/";

$fileName = "image-" . $vouchno . ".jpg";
$img_file = $path . ($fileName);

//$imgp = mysqli_query($conn, "SELECT * FROM `$imagedb` WHERE `code`='$code'")or die(mysqli_error($conn));
//while($gimg = mysqli_fetch_array($imgp)){
    

unlink($img_file);    

//}

//$fileName       = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
//$image = new SimpleImage();
//$image->load($fileTmpLoc);
//$image->resize(700, 500);
//$image->save($fileTmpLoc);

if (!$fileTmpLoc) { // if file not chosen
    echo "ERROR: Please browse for a file before clicking the upload button.";
    exit();
}
if (move_uploaded_file($fileTmpLoc, "$img_file")) {

    echo "$fileName upload is complete";

    ###########################SAVE PART################################################   
    $imgp = mysqli_query($conn, "SELECT `imagepath` FROM `$imagedb`")or die(mysqli_error($conn));
    $gimg = mysqli_fetch_array($imgp);

//    mysqli_query($conn, "DELETE FROM `$imagedb` WHERE vouchno='$vouchno' AND `imageno`='$imageno'") or die(mysqli_error($conn));

    if ($gimg['vouchno'] == $vouchno) {
        mysqli_query($conn, "UPDATE `$imagedb` SET `imgpath`='$path' WHERE `vouchno`='$vouchno' ") or die(mysqli_error($conn));
    }

    mysqli_query($conn, "INSERT INTO `$imagedb`(`imgpath`)
                            VALUES('$path')") or die(mysqli_error($conn));
} else {
    echo "move_uploaded_file function failed";
}

?>