<?php
/*
 * Created on 25.04.2010
 *
 * imageupload.php
 * Author: Alex Sam <greeka@gmail.com>
 *
 */

include 'func.php';
error_reporting(E_ALL);

$allowed_data = array('image_data_front', 'image_data_back', 'image_rendered_front', 'image_rendered_back', 'data_front', 'data_back', 'pdf_front', 'pdf_back', 'pdf_proof', 'user_file_front', 'user_file_back');

$action = isset($_POST['action']) ? $_POST['action'] : ''; 


if(!isset($_COOKIE["PHPSESSID"]))
  {
session_start();
  }

$res = new stdClass();
$res->result = 'success';

$userData = isset($_SESSION['userdata']) ? $_SESSION['userdata'] : null;

if (empty($userData)) {
    $res->result = 'error';
    $res->message = 'User not logged';
    echo json_encode($res);
    die;
}

if ($action != 'newcard' && $action != 'updcard' && !isset($_POST['file'])) {
    $res->result = 'error';
    $res->message = 'Data not valid';
    $res->code = 1;
    echo json_encode($res);
    die;
}

if ($action != 'newcard' && $action != 'updcard' && !isset($_POST['filedata'])) {
    $res->result = 'error';
    $res->message = 'Data not valid';
    $res->code = 2;
    echo json_encode($res);
    die;
}

if ($action != 'newcard' && $action != 'updcard' && isset($_POST['file']) && !in_array($_POST['file'], $allowed_data)) {
    $res->result = 'error';
    $res->message = 'Data not valid';
    $res->code = 3;
    echo json_encode($res);
    die;
}

if ($action == 'newcard' && $action != 'updcard' && (!isset($_POST['card']) || !is_numeric($_POST['card']))) {
    $res->result = 'error';
    $res->message = 'Card not valid';
    $res->code = 4;
    echo json_encode($res);
    die;
} elseif($action == 'newcard' || $action == 'updcard') {
	$card = $_POST['card'];
}

    if ($action == 'newcard' || $action == 'updcard' ) {

        $tempArray1 = stripslashes($_REQUEST['data_front']);
        $dataFrontEncoded = json_decode($tempArray1);
        $tempArray2 = stripslashes($_REQUEST['data_back']);
        $dataBackEncoded = json_decode($tempArray2);
		$cid = isset($_POST['cid']) ? $_POST['cid'] : null;
		if ($action == 'updcard' && $cid) {
			$qry = 'select * from usercard where usercard_ = ' . mysql_escape_string($cid) .  ' and user_ = ' . $userData['user_'];
	        $_res = @mysql_query($qry);
	        $cardData = @mysql_fetch_assoc($_res);
	        if (empty($cardData)) {
	        	$cardID = time();
	        	$action = 'newcard';
	        } else {
	        	$cardID = $cardData['cardid'];
	        }
		} elseif ($action == 'newcard') {
        	$cardID = time();
        	$action = 'newcard';
		}

        $cdir = $base_dir . '/usdata/' . $userData['user_'] . '/' . $cardID . '/';
        if (!is_dir($cdir)) {
            mkdir($cdir, 0777, true);
        #    exec('chmod -R u=rwX,g=rwX,o=rX ' . $base_dir . '/usdata/');
        }



        if (isset($dataFrontEncoded->texts))
            $frontdata = json_encode($dataFrontEncoded->texts);
        else
            $frontdata = '';

        if (isset($dataBackEncoded->texts))
            $backdata = json_encode($dataBackEncoded->texts);
        else
            $backdata = '';
		if ($action == 'updcard') {
			$qry = 'update usercard set frontdata = "' . mysql_escape_string($frontdata) . '", backdata = "' . mysql_escape_string($backdata) . '", card_  = "' . mysql_escape_string($card) . '" where usercard_ = ' . mysql_escape_string($cid);
			mysql_query($qry) or die(mysql_error());
			$userCardID =  $cid;
		} else {

                $productid=$_POST['productId'];
                $producttype=$_POST['productType'];
	        $qry = 'insert into usercard (user_, cardid, frontdata, backdata, card_,Product_Id,Product_Type) values (' . $userData['user_'] . ', ' . $cardID . ', "' . mysql_escape_string($frontdata) . '", "' . mysql_escape_string($backdata) . '", ' . mysql_escape_string($card) . ','. mysql_escape_string($productid) . ','. mysql_escape_string($producttype) . ')';
	        mysql_query($qry) or die(mysql_error());
	        $userCardID = mysql_insert_id();
		}
        
        $_SESSION['_tmp_card_id'] = $cardID;
        $_SESSION['_tmp_user_card_id'] = $userCardID;

        if (isset($dataFrontEncoded->images) && !empty($dataFrontEncoded->images)) {
            $resFrontImages = array();
        	foreach ($dataFrontEncoded->images as $k => $v) {
                unset($v->image);
                if (!(int)$v->id || (int)$v->id < 100) {
                    $qry = 'insert into user_image (user_, adddate) values (' . $userData['user_'] . ',\'' . date('Y-m-d H:i:s') . '\')';
                    mysql_query($qry) or die(mysql_error());
                    $imgID = mysql_insert_id();
                    $qry = 'insert into card_image (usercard_, image_, side, data) values (' . $_SESSION['_tmp_user_card_id'] . ', ' . $imgID . ', \'front\', \'' . mysql_real_escape_string(json_encode($v)) . '\')';
                    mysql_query($qry) or die(mysql_error());
                } elseif ((int)$v->id && (int)$v->id > 100) {
                    $imgID = (int)$v->id;
                } else {
                    die('Hacking atempt');
                }
                $resFrontImages[$v->id] = $imgID;
        	}
            $_SESSION['rfi'] = $resFrontImages;
        }

        if (isset($dataBackEncoded->images) && !empty($dataBackEncoded->images)) {
            $resBackImages = array();
            foreach ($dataBackEncoded->images as $k => $v) {
                unset($v->image);
                if (!(int)$v->id || (int)$v->id < 100) {
                    $qry = 'insert into user_image (user_, adddate) values (' . $userData['user_'] . ',\'' . date('Y-m-d H:i:s') . '\')';
                    mysql_query($qry) or die(mysql_error());
                    $imgID = mysql_insert_id();
                    $qry = 'insert into card_image (usercard_, image_, side, data) values (' . $_SESSION['_tmp_user_card_id'] . ', ' . $imgID . ', \'front\', \'' . mysql_real_escape_string(json_encode($v)) . '\')';
                    mysql_query($qry) or die(mysql_error());
                } elseif ((int)$v->id && (int)$v->id > 100) {
                    $imgID = (int)$v->id;
                } else {
                    die('Hacking atempt');
                }
                $resBackImages[$v->id] = $imgID;
            }
            $_SESSION['rbi'] = $resBackImages;
        }

    } elseif ($action == 'file_data' && isset($_POST['filedata']) && !empty($_POST['filedata']) && isset($_SESSION['_tmp_card_id']) && !empty($_SESSION['_tmp_card_id']) && !empty($_SESSION['_tmp_user_card_id'])) {
        $cdir = $base_dir . '/usdata/' . $userData['user_'] . '/' . $_SESSION['_tmp_card_id'] . '/';
        $cdirUImages = $base_dir . '/usdata/' . $userData['user_'] . '/images/';
        if (!is_dir($cdirUImages)) {
            mkdir($cdirUImages, 0777, true);
        #    exec('chmod -R u=rwX,g=rwX,o=rX ' . $base_dir . '/usdata/');
        }
        $file = isset($_POST['file']) ? $_POST['file'] : '';
        if ($file == 'image_data_front') {
            $fh = fopen($cdir . 'front_preview.png', 'w+');
            fwrite($fh, base64_decode($_POST['filedata']));
            fclose($fh);
//        #    chmod($cdir . 'front_preview.png', 0777);
        }
        if ($file == 'image_data_back') {
            $fh = fopen($cdir . 'back_preview.png', 'w+');
            fwrite($fh, base64_decode($_POST['filedata']));
            fclose($fh);
//        #    chmod($cdir . 'back_preview.png', 0777);
        }
        if ($file == 'image_rendered_front') {
            $fh = fopen($cdir . 'rendered_front.png', 'w+');
            fwrite($fh, base64_decode($_POST['filedata']));
            fclose($fh);
//            $imcmd = $im_path . ' ' . $cdir . 'rendered_front.png' . ' -density 300x300 -units pixelsperinch ' . $cdir . 'rendered_front.png';
//            exec($imcmd);
//        #    chmod($cdir . 'rendered_front.png', 0777);
        }
        if ($file == 'image_rendered_back') {
            $fh = fopen($cdir . 'rendered_back.png', 'w+');
            fwrite($fh, base64_decode($_POST['filedata']));
            fclose($fh);
//            $imcmd = $im_path . ' ' . $cdir . 'rendered_back.png' . ' -density 300x300 -units pixelsperinch ' . $cdir . 'rendered_back.png';
//            exec($imcmd);
//        #    chmod($cdir . 'rendered_back.png', 0777);
        }
        if ($file == 'pdf_front') {
            $fh = fopen($cdir . 'rendered_pdf_front.pdf', 'w+');
            fwrite($fh, base64_decode($_POST['filedata']));
            fclose($fh);
//        #    chmod($cdir . 'rendered_back.png', 0777);
        }
        if ($file == 'pdf_back') {
            $fh = fopen($cdir . 'rendered_pdf_back.pdf', 'w+');
            fwrite($fh, base64_decode($_POST['filedata']));
            fclose($fh);
//        #    chmod($cdir . 'rendered_back.png', 0777);
        }
    	if ($file == 'pdf_proof') {
            $fh = fopen($cdir . 'proof.pdf', 'w+');
            fwrite($fh, base64_decode($_POST['filedata']));
            fclose($fh);
//        #    chmod($cdir . 'rendered_back.png', 0777);
        }
        if ($file == 'user_file_front' && isset($_POST['id'])) {
            $rfi = isset($_SESSION['rfi']) ? $_SESSION['rfi'] : array();
            if (!isset($rfi[$_POST['id']])) {
                die('Hacking atempt');
            } else {
            	$imgID = $rfi[$_POST['id']];
            }
            $fh = fopen($cdirUImages . 'image_' . $imgID . '.png', 'w+');
            fwrite($fh, base64_decode($_POST['filedata']));
            fclose($fh);
            $cmd = $im_path . " " . $cdirUImages . 'image_' . $imgID . '.png' . " -thumbnail 150x113 -strip -quality 85 " . $cdirUImages . 'thumb_' . $imgID . '.jpg';
            exec($cmd);
//        #    chmod($cdir . 'rendered_back.png', 0777);
        }

        if ($file == 'user_file_back' && isset($_POST['id'])) {
            $rbi = isset($_SESSION['rbi']) ? $_SESSION['rbi'] : array();
            if (!isset($rbi[$_POST['id']])) {
                die('Hacking atempt');
            } else {
                $imgID = $rbi[$_POST['id']];
            }
            $fh = fopen($cdirUImages . 'image_' . $imgID . '.png', 'w+');
            fwrite($fh, base64_decode($_POST['filedata']));
            fclose($fh);
            $cmd = $im_path . " " . $cdirUImages . 'image_' . $imgID . '.png' . " -thumbnail 150x113 -strip -quality 85 " . $cdirUImages . 'thumb_' . $imgID . '.jpg';
            exec($cmd);
//        #    chmod($cdir . 'rendered_back.png', 0777);
        }
    }

echo json_encode($res);

//print_r(json_decode($_POST['data_front']));

?>