<?php

session_start();

include_once '../config/database.php';
include_once "../resources/manageusers.php";
include_once '../config/properties.php';
include_once "../resources/EncryptDecrypt.php";

$id = $_SESSION['uid'];
$dir =  ADMIN_HTTP_PATH . $properties['jdbc.user_image_folder'] . '/';
$curr_date_ts = clean($date_time);

// initialize objects
$object = new ManageUsers();

switch ($_POST['mode']) {
    case "change": {

            $user_image_from_server = $_POST['name'];
            if ($user_image_from_server != "") {
                $dir1 = $dir . $user_image_from_server;
                if (file_exists($dir1)) {
                    if (unlink($dir1)) {
                        
                    }
                }
            }

            if (!file_exists($dir)) {
                mkdir($dir, 0777, true);
            }

            $length = 10;
            $key = '';
            $keys = array_merge(range(0, 9), range('a', 'z'));

            for ($i = 0; $i < $length; $i++) {
                $key .= $keys[array_rand($keys)];
            }
            $f_name = $curr_date_ts . $id . '.jpg';
            $file = $curr_date_ts . $id . '.jpg';
            $file = trim($file);
            move_uploaded_file(compress($_FILES["cropped_image"]["tmp_name"], $dir . $file, 80), $dir . $file);

            $val2 = $object->UpdateProfileImage($file, $_SESSION['uid'], $date_time);
            if ($val2) {
                echo $dir . $file;
            }
            break;
        }
    case "delete": {
            $name = $_POST['file_name'];
            $dir1 = $dir . $name;
            if (file_exists($dir1)) {
                if (unlink($dir1)) {
                    $val2 = $object->UpdateProfileImage('', $_SESSION['uid'], $date_time);
                    if ($val2) {
                        echo DEFAULT_USER_IMAGE;
                    }
                }
            }
            break;
        }
    default :
        break;
}

function compress($source, $destination, $quality) {
    $info = getimagesize($source);

    if ($info['mime'] == 'image/jpeg')
        $image = imagecreatefromjpeg($source);

    elseif ($info['mime'] == 'image/gif')
        $image = imagecreatefromgif($source);

    elseif ($info['mime'] == 'image/png')
        $image = imagecreatefrompng($source);

    imagejpeg($image, $destination, $quality);
    return $destination;
}

function clean($string) {
    $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
    return preg_replace('/[^A-Za-z0-9]/', '', $string); // Removes special chars.
}

?>