<?php
/**
 * Created by PhpStorm.
 * User: IOAN
 * Date: 10/2/2015
 * Time: 11:00 AM
 */
//@session_start();
require_once(dirname(__FILE__) . "/../../../adbcon.php");
require_once(dirname(__FILE__) . "/../../common/htmlpurifier/HTMLPurifier.standalone.php");

$config = HTMLPurifier_Config::createDefault();

$config->set('Core.Encoding', 'UTF-8'); // replace with your encoding
$config->set('HTML.Doctype', 'XHTML 1.1'); // replace with your doctype
$config->set('HTML.TidyLevel', 'heavy'); // burn baby burn!
$config->set('HTML.AllowedElements', 'strong,em,p,b,i,ul,li,ol,br');
$config->set('HTML.AllowedAttributes', 'p.style');
$config->set('AutoFormat.RemoveEmpty', true); // remove empty tag pairs
$config->set('AutoFormat.RemoveEmpty.RemoveNbsp', true); // remove empty, even if it contains an &nbsp;
$config->set('AutoFormat.AutoParagraph', true); // remove empty tag pairs

// run the escaped html code through the purifier
$purifier = new HTMLPurifier($config);



function cleanHtml($dirtyHtml, $fld)
{
    global $purifier;

    $html_fields = array(
        "Qualifications",
        "ProfessionalExperience",
        "Education",
        "Interests",
        "SpecialSkills",
        "Languages",
        "Training",
        "Affiliations",
        "ReferencesOther"
    );

    if(in_array($fld, $html_fields)) {
        $cleanHtml = $purifier->purify($dirtyHtml);
        return $cleanHtml;
    }
    else {
        $dirtyHtml = strip_tags($dirtyHtml);
    }

    return $dirtyHtml;
}

//echo '<pre>', var_export($_POST, true), '</pre>';
$required = array(

    "job_cat_id" => "Job Category",
    "JobLocation" => "Job Location",
    "FirstName" => "First Name",
    "LastName" => "Last Name",
    "Genre" => "Gender",
    "dob" => "Date Of Birth",
    "CountryOfOrigin" => "Country Of Origin",
    //"MaritalStatus" => "Marital Status",
    //"Children" => "Children",
    "ResCountry" => "Residence Country",
    "ResTown" => "Residence Town",
    "ResAddress" => "Residence Address",
    //"ResPhone" => "",
    //"Mobile" => "",
    "Email" => "Email Address",
    /*"Qualifications" => "",
    "ProfessionalExperience" => "",
    "Education" => "",
    "Interests" => "",
    "SpecialSkills" => "",
    "Languages" => "",
    "Training" => "",
    "Affiliations" => "",
    "ReferencesOther" => "",*/

);

$ret = array(
    "result" => 0,
    "error" => array()
);

$session = $_POST['session'];
$action = trim($_POST['chcAction']);

if($action != "Delete" && $action != "Status") {
    foreach ($required as $key => $label) {
        if (!isset($_POST[$key]) || $_POST[$key] == "" || empty($_POST[$key])) {
            $ret['error'][] = "<b>$label</b> is a required field.";
        }
    }
}


if(count($ret['error']) == 0) {
    if($action == "Edit") {
        $post = $_POST;
        $job_cv_id = intval($post['job_cv_id']);
        $flds = array("job_cat_id", "catdom_id", "JobLocation", "FirstName", "LastName", "Genre", "dob", "CountryOfOrigin", "MaritalStatus", "Children", "ResCountry", "ResTown", "ResAddress", "ResPhone", "Mobile", "Email", "Qualifications", "ProfessionalExperience", "Education", "Interests", "SpecialSkills", "Languages", "Training", "Affiliations", "ReferencesOther", "jversion");

        $flds_extra = array("updated", "updated_at");
        $flds = array_merge($flds, $flds_extra);

        $post['updated'] = '1';
        $post['updated_at'] = date("Y-m-d H:i:s", time());

        $flds_arr = array();
        foreach($flds as $fld) {
            if(isset($post[$fld])) {
                if(!is_array($post[$fld])) {
                    $post[$fld] = cleanHtml(stripslashes($post[$fld]), $fld);
                    $flds_arr [] = "`$fld`='" . mysql_real_escape_string(trim($post[$fld])) . "'";
                }
                else  {
                    $flds_arr [] = "`$fld`='" . mysql_real_escape_string(stripslashes(trim(implode(";", $post[$fld])))) . "'";
                }
            }
        }
        $flds_str = implode(", ", $flds_arr);
        $q = "UPDATE job_cvs SET $flds_str WHERE job_cv_id='$job_cv_id';";
        $ret['q'] = $q;
        $r = @mysql_query($q);

        if($r && mysql_affected_rows() != -1) {
            $ret['result'] = 1;
            $ret['success'] = "The resume details were successfully updated.";
            $ret['link'] = "account/resume/my-resume.html";
        }
        else {
            $ret['error'][] = "Database errors occured.";
        }

    }

    if($action == "Add") {
        $post = $_POST;
        $flds = array("job_cat_id", "catdom_id", "JobLocation", "FirstName", "LastName", "Genre", "dob", "CountryOfOrigin", "MaritalStatus", "Children", "ResCountry", "ResTown", "ResAddress", "ResPhone", "Mobile", "Email", "Qualifications", "ProfessionalExperience", "Education", "Interests", "SpecialSkills", "Languages", "Training", "Affiliations", "ReferencesOther", "jversion");
        $flds_extra = array("added_on", "added_on_time", "created_at", "updated_at", "member_id", "active");
        $flds = array_merge($flds, $flds_extra);


        $post['added_on'] = date("Y-m-d");
        $post['added_on_time'] = date("H:i:s");
        $post['created_at'] = $post['added_on'] . ' ' . $post['added_on_time'];
        $post['updated_at'] = $post['added_on'] . ' ' . $post['added_on_time'];
        $post['member_id'] = $session['member_id'];
        $post['active'] = 'new';


        $ff = array();
        $fv = array();

        $flds_arr = array();
        foreach($flds as $fld) {
            if(isset($post[$fld])) {
                $ff [] = "`$fld`";
                if(!is_array($post[$fld])) {
                    $post[$fld] = cleanHtml(stripslashes($post[$fld]), $fld);
                    $fv [] = "'" . mysql_real_escape_string(trim($post[$fld])) . "'";
                }
                else  {
                    $fv [] = "'" . mysql_real_escape_string(stripslashes(trim(implode(";", $post[$fld])))) . "'";
                }
            }
        }
        $ff_str = implode(", ", $ff);
        $fv_str = implode(", ", $fv);
        $q = "INSERT INTO job_cvs ($ff_str) VALUES ($fv_str);";
        $r = @mysql_query($q);

        if($r && mysql_affected_rows() == 1) {
            $job_cv_id = mysql_insert_id();
            $ret['result'] = 1;
            $ret['success'] = "The resume has been saved successfully.";
            $ret['link'] = "account/resume/my-resume.html";
        }
        else {
            $ret['error'][] = "Database errors occured.";
        }
    }

    if($action == "Delete") {
        $post = $_POST;
        $job_cv_id = intval($post['job_cv_id']);
        $member_id = intval($session['member_id']);

        $q = "SELECT * FROM job_cvs WHERE member_id='$member_id' AND job_cv_id='$job_cv_id';";
        $r = @mysql_query($q);
        if($r && mysql_num_rows($r) == 1) {


            $q = "DELETE FROM job_cvs WHERE job_cv_id='$job_cv_id';";
            $r = @mysql_query($q);

            if ($r && mysql_affected_rows() == 1) {
                $ret['result'] = 1;
                $ret['success'] = "Your resume has been deleted successfully.";
                $ret['link'] = "account/resume/my-resume.html";
            } else {
                $ret['error'][] = "Database errors occured.";
            }
        }
        else {
            $ret['error'][] = "The resume you try to delete does not exist.";
        }
    }

    if($action == "Status") {
        $post = $_POST;
        $job_cv_id = intval($post['job_cv_id']);
        $resume_status = intval($post['resume_status']);
        $member_id = intval($session['member_id']);

        $q = "UPDATE job_cvs SET resume_status='$resume_status' WHERE member_id='$member_id' AND job_cv_id='$job_cv_id';";
        $r = @mysql_query($q);
        if($r && mysql_affected_rows() != -1) {
            $ret['result'] = 1;
            $ret['success'] = "Your Resume has been updated successfully.";
            $ret['link'] = "account/resume/my-resume.html";
        }
        else {
            $ret['error'][] = "The Resume you try to update does not exist.";
        }
    }
}

if(count($ret['error']) > 0) {
    $ret['error'] = implode('<br>', $ret['error']);
}
elseif(isset($ret['success']) && trim($ret['success']) != "") {
    $ret['flashm'] = $ret['success'];
}

echo json_encode($ret);