<?php
/**
 * Created by PhpStorm.
 * User: IOAN
 * Date: 10/2/2015
 * Time: 11:00 AM
 */
//@session_start();
require_once(dirname(__FILE__) . "/../../../adbcon.php");
mysql_query("SET @@global.sql_mode= '';");
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(
        "JobDescription",
        "Qualifications",
        "Other");

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

    return $dirtyHtml;
}

$required = array(

    "CompanyName" => "Company Name",
    "Address" => "Address",
    "Town" => "Town",
    "Phone" => "Phone",
    "ContactPerson" => "Contact Person",

    "job_cat_id" => "Job Category",
    "JobTitle" => "Job Title",
    "JobDescription" => "Job Description",
    "Location" => "Location(s)",

    //"member_id" => ""
);

if(isset($_POST['Town']) && $_POST['Town'] == "other") {
    $required ["OtherTown"] = "Town";
}

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

//$ret['post'] = var_export($_POST, true);

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

// Get member trust
$member_id = isset($session['member_id']) ? intval($session['member_id']) : 0;
$trusted = 0;
$q = "SELECT * FROM job_members WHERE member_id='$member_id'";
$r = @mysql_query($q);
if($r && mysql_num_rows($r) == 1) {
    $row = mysql_fetch_assoc($r);
    $trusted = intval($row['trusted']);
}

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.";
        }
    }

    $job_cat_id = $_POST['job_cat_id'];
    $categs = [];
    foreach($job_cat_id as $i=>$jc) {
        if(intval($jc) > 0) {
            if(!in_array(intval($jc), $categs)) $categs [] = intval($jc);
        }
    }

    if(count($categs) == 0) {
        $ret['error'][] = "You must choose at least one <b>Job Category</b>.";
    }

    if(trim($_POST['salary_min']) != "" && !is_numeric($_POST['salary_min'])) {
        $ret['error'][] = "<b>Min Salary</b> must be a valid number.";
    }
    if(trim($_POST['salary_max']) != "" && !is_numeric($_POST['salary_max'])) {
        $ret['error'][] = "<b>Max Salary</b> must be a valid number.";
    }

    if(intval($_POST['salary_min']) > 0 && intval($_POST['salary_max']) > 0 && (intval($_POST['salary_min']) > intval($_POST['salary_max']))) {
        $tmp = intval($_POST['salary_min']);
        $_POST['salary_min'] = intval($_POST['salary_max']);
        $_POST['salary_max'] = $tmp;
    }
}

if($member_id == 0) {
    $ret['error'][] = "You are not authorised to perform this action.";
}


if(count($ret['error']) == 0) {
    if($action == "Edit") {
        $post = $_POST;
        $job_jobs_id = intval($post['job_jobs_id']);
        $flds = array(/*"job_cat_id",*/ "catdom_id", "CompanyName", "Address", "Town", "OtherTown", "Phone", "Mobile", "Fax", "ContactPerson", "EmailAdd", "JobTitle", "JobDescription", "salary_min", "salary_max", "NumberOfPersons", "Qualifications", "Other", "Location", "Conditions", "jversion");

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

        $post['updated'] = $trusted == 1 ? '0' : '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] = strip_tags(stripslashes($post[$fld]), '<strong><em><p><b><i><ul><li><ol><br><u>');
                    $post[$fld] = cleanHtml(trim(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])))) . "'";
                }
            }
        }

        $job_cat_id = $post['job_cat_id'];
        $categs = [];
        foreach($job_cat_id as $i=>$jc) {
            if(intval($jc) > 0) {
                if(!in_array(intval($jc), $categs)) $categs [] = intval($jc);
            }
        }

        if(count($categs) > 0) {

        }
        else {
            $ret['error'][] = "You must choose at least one Job Category.";
        }

        if(count($ret['error']) == 0) {
            $flds_str = implode(", ", $flds_arr);
            $q = "UPDATE job_jobs SET $flds_str WHERE job_jobs_id='$job_jobs_id';";
            $r = @mysql_query($q);

            if ($r && mysql_affected_rows() != -1) {

                // Update categs
                @mysql_query("DELETE FROM job_categs WHERE job_id='$job_jobs_id';");

                foreach($categs as $jc) {
                    @mysql_query("INSERT INTO job_categs (`job_id`, `categ_id`) VALUES ('$job_jobs_id', '$jc');");
                }


                $ret['result'] = 1;
                $ret['success'] = "The job details were successfully updated.";
                $ret['link'] = "account/jobs/job.html?jid=" . $job_jobs_id;
            } else {
                $ret['error'][] = "Database errors occured.";
            }
        }

    }

    if($action == "Add") {
        $post = $_POST;
        $flds = array("catdom_id", "CompanyName", "Address", "Town", "OtherTown", "Phone", "Mobile", "Fax", "ContactPerson", "EmailAdd", "JobTitle", "JobDescription", "salary_min", "salary_max", "NumberOfPersons", "Qualifications", "Other", "Location", "Conditions", "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'] = $trusted == 1 ? 'yes' : '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(trim(stripslashes($post[$fld])), $fld);
                    $fv [] = "'" . mysql_real_escape_string(trim($post[$fld])) . "'";
                }
                else  {
                    $fv [] = "'" . mysql_real_escape_string(stripslashes(trim(implode(";", $post[$fld])))) . "'";
                }
            }
        }

        $job_cat_id = $post['job_cat_id'];
        $categs = [];
        foreach($job_cat_id as $i=>$jc) {
            if(intval($jc) > 0) {
                if(!in_array(intval($jc), $categs)) $categs [] = intval($jc);
            }
        }

        if(count($categs) == 0) {
            $ret['error'][] = "You must choose at least one Job Category.";
        }

        if(count($ret['error']) == 0) {
            $ff_str = implode(", ", $ff);
            $fv_str = implode(", ", $fv);
            $q = "INSERT INTO job_jobs ($ff_str) VALUES ($fv_str);";
            $r = @mysql_query($q);

            if ($r && mysql_affected_rows() == 1) {
                $job_jobs_id = mysql_insert_id();

                // Update categs
                @mysql_query("DELETE FROM job_categs WHERE job_id='$job_jobs_id';");

                foreach($categs as $jc) {
                    @mysql_query("INSERT INTO job_categs (`job_id`, `categ_id`) VALUES ('$job_jobs_id', '$jc');");
                }


                $ret['result'] = 1;
                $ret['success'] = "The job has been saved successfully.";
                $ret['link'] = "account/jobs/job.html?jid=" . $job_jobs_id;
            } else {
                $ret['error'][] = "Database errors occured.<br>$q<br>" . mysql_error();
            }
        }
    }

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

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


            $q = "DELETE FROM job_jobs WHERE job_jobs_id='$job_jobs_id';";
            $r = @mysql_query($q);

            if ($r && mysql_affected_rows() == 1) {

                // Delete categories
                @mysql_query("DELETE FROM job_categs WHERE job_id='$job_jobs_id';");

                $ret['result'] = 1;
                $ret['success'] = "The job has been deleted successfully.";
                $ret['link'] = "account/jobs/my-jobs.html";
            } else {
                $ret['error'][] = "Database errors occured.";
            }
        }
        else {
            $ret['error'][] = "The job you try to delete does not exist.";
        }
    }

    if($action == "Status") {
        //$ret['log'] = var_export($_POST, true);
        $post = $_POST;
        $job_jobs_id = intval($post['job_jobs_id']);
        $job_status = intval($post['job_status']);
        $member_id = intval($session['member_id']);

        $q = "UPDATE job_jobs SET job_status='$job_status' WHERE member_id='$member_id' AND job_jobs_id='$job_jobs_id';";
        $r = @mysql_query($q);
        if($r && mysql_affected_rows() != -1) {
                $ret['result'] = 1;
                $ret['success'] = "The job has been updated successfully.";
                $ret['link'] = "account/jobs/my-jobs.html";
        }
        else {
            $ret['error'][] = "The job 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);
exit;