<?php
global $hooks;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$hooks->add_action('silex_action', 'the_profile');

function myprofile_title() {
    echo "My Profile";
}
function user_profile_title() {
    echo "User Profile";
}

function editprofile_title() {
    echo "Edit Profile";
}

function chpwd_title() {
    echo "Change Password";
}

function chpwd_js() {
    ?>
    <script src="/assets/global/plugins/jquery-validation/js/jquery.validate.min.js" type="text/javascript"></script>
    <script src="/assets/modul-js/common/profile/chpwd.min.js" type="text/javascript"></script>
<?php }

function editprofile_js() {
    ?>
    <script src="/assets/global/plugins/jquery-validation/js/jquery.validate.min.js" type="text/javascript"></script>
	<script src="/assets/modul-js/common/profile/editprofile.js" type="text/javascript"></script>
<?php }


function user_profile_js() {
    ?>
    <script src="/assets/modul-js/common/profile/user-profile.min.js" type="text/javascript"></script>
<?php }

function company_profile_js() {
    ?>
    <script src="/assets/modul-js/common/profile/company-profile.min.js" type="text/javascript"></script>
<?php }

function editprofile_css() {
    ?>
	<link href="/assets/global/plugins/bootstrap-fileinput/bootstrap-fileinput.css" rel="stylesheet" type="text/css" />
	<link href="/assets/modul-css/profile/profile.min.css" rel="stylesheet" type="text/css" />
<?php }

function myprofile_js() {
    ?>
    <script src="/assets/modul-js/common/profile/myprofile.min.js" type="text/javascript"></script>
<?php }

function the_profile() {
    global $app;
    $app->post('/profile/edit/update', function (Request $request) {
        global $db;
        $first_name = $request->get('first_name');
        $last_name = $request->get('last_name');
        $email = $request->get('email');
        $website = $request->get('website');
        $position = $request->get('position');
        $user_id = $_SESSION["user_id"];
        // Bind the data
        $db->bind("first_name", $first_name);
        $db->bind("last_name", $last_name);
        $db->bind("position", $position);
        $db->bind("email", $email);
        $db->bind("website", $website);
        $db->bind("user_id", $_SESSION["user_id"]);

        $profileupdate = $db->query("UPDATE user_detail SET first_name = :first_name, last_name = :last_name, email= :email, website= :website , position= :position WHERE user_id = :user_id");
        if ($profileupdate > 0) {
			action_log($_SESSION['user_id'], "Profile Update", "SUCCESS");
            return new Response('Success', 200);
        }
        else if ($profileupdate == 0){
            return new Response('Not affected', 304);
        }
        else {
			action_log($_SESSION['user_id'], "Profile Update", "FAILED");
            return new Response('Failed', 400);
        }
    });
    $app->post('/profile/edit/updatepic', function (Request $request) {
        global $db;
        global $app;
		
		if (!file_exists( __DIR__ . '/../../../uploads/profile/'.$_SESSION['user_id'])) {
			mkdir( __DIR__ . '/../../../uploads/profile/'.$_SESSION['user_id'], 0777, true);
		}
		$uploaddir =  __DIR__ . '/../../../uploads/profile/'.$_SESSION['user_id'];
        $verifyimg = getimagesize($_FILES['image']['tmp_name']);
		$pattern = "#^(image/)[^\s\n<]+$#i";
		if(!preg_match($pattern, $verifyimg['mime'])){
			return new Response('Failed', 201);
		}
		
		$uploadfile = tempnam_sfx($uploaddir, ".tmp");
		
		if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
			$path =  'http://' . $_SERVER['HTTP_HOST'].'/uploads/profile/'.$_SESSION['user_id']."/".basename($uploadfile);
			$data = file_get_contents($path);
			$profile_picture = 'data:' . $_FILES['image']['type'] . ';base64,' . base64_encode($data);
			$profile_picture_mime = $_FILES['image']['type'];
			$db->bind("profile_picture", $profile_picture);
			$db->bind("profile_picture_mime", $profile_picture_mime);
            $db->bind("user_id", $_SESSION["user_id"]);
            
			
			$imageupdate = $db->query("UPDATE user_detail SET profile_picture = :profile_picture, profile_picture_mime= :profile_picture_mime WHERE user_id = :user_id");
		}
		if ($imageupdate) {
			action_log($_SESSION['user_id'], "Profile Picture Update", "SUCCESS");
			delete_directory(__DIR__ ."/../../../uploads/");
			return $app->redirect('/profile/edit?success');
		} else {
			action_log($_SESSION['user_id'], "Profile Picture Update", "FAILED");
			delete_directory(__DIR__ ."/../../../uploads/");
			return $app->redirect('/profile/edit?failed');
		}
    });
    $app->get('/profile/edit', function() {
        global $hooks;
		$hooks->add_action('global_css', 'editprofile_css');
        $hooks->add_action('global_js', 'editprofile_js');
        $hooks->add_action('the_title', "editprofile_title");
        the_head();
        include 'editprofile.tpl.php';
        the_footer();
        return "";
    });
    $app->post('/profile/chpwd/update', function (Request $request) {
        global $db;
        $newpass = $request->get('newpass');
        $oldpass = $request->get('oldpass');
        if (pwdCorrect($oldpass)) {
            $db->bind("user_id", $_SESSION["user_id"]);
            $db->bind("newpass", $newpass);
            $passupdate = $db->query("UPDATE users SET password = :newpass WHERE user_id = :user_id");
            if ($passupdate) {
				action_log($_SESSION['user_id'], "Password Update", "SUCCESS");
                return new Response('Success', 200);
            } else {
				action_log($_SESSION['user_id'], "Password Update", "FAILED");
                return new Response('Failed', 201);
            }
        } else {
            return new Response('Failed', 201);
        }
    });
    $app->get('/profile/chpwd', function() {
        global $hooks;
        $hooks->add_action('global_css', 'editprofile_css');
        $hooks->add_action('global_js', 'chpwd_js');
        $hooks->add_action('the_title', "chpwd_title");
        the_head();
        include 'chpwd.tpl.php';
        the_footer();
        return "";
    });
    $app->get('/profile', function() {
        global $hooks;
        $hooks->add_action('global_css', 'myprofile_css');
        $hooks->add_action('global_js', 'myprofile_js');
        $hooks->add_action('the_title', "myprofile_title");
        the_head();
        include 'myprofile.tpl.php';
        the_footer();
        return "";
    });
	
    $app->get('/user-profile/{id}', function ($id) use ($app) {
				
		unset($user_id);
		unset($encrypted);
        global $hooks;
		global $encrypted;
		global $user_id;
		$encrypted = $id;
		$salt="picard59fJepLkm6Gu5dDV";
		$decrypted_id_raw = base64_decode($id);
		$decrypted_id = preg_replace(sprintf('/%s/', $salt), '', $decrypted_id_raw);
		$user_id = $decrypted_id;
		
		if (!userIDExist($decrypted_id)) {	
			unset($user_id);
			unset($encrypted);
            return $app->redirect('/dashboard');
        }		
		if(is_login()){
		$hooks->add_action('the_title', "user_profile_title");
		$hooks->add_action('global_css', 'editprofile_css');
		$hooks->add_action('global_js', 'user_profile_js');
			
		the_head();
		}
		include 'user-profile.tpl.php';
		if(is_login()){
		the_footer();
		}
        
        return "";
    });
	
    $app->get('/company-profile/{id}', function ($id) use ($app) {
				
		unset($company_id);
		unset($encrypted);
        global $hooks;
		global $encrypted;
		global $company_id;
		$encrypted = $id;
		$salt="picard59fJepLkm6Gu5dDV";
		$decrypted_id_raw = base64_decode($id);
		$decrypted_id = preg_replace(sprintf('/%s/', $salt), '', $decrypted_id_raw);
		$company_id = $decrypted_id;
		
		if (!userIDExist($decrypted_id)) {	
			unset($company_id);
			unset($encrypted);
            return $app->redirect('/dashboard');
        }		
		
		$hooks->add_action('the_title', "user_profile_title");
		$hooks->add_action('global_css', 'editprofile_css');
		$hooks->add_action('global_js', 'company_profile_js');
			
		the_head();
		include 'company-profile.tpl.php';
        the_footer();
        return "";
    });
}

include 'profile.func.php';
