<?php
require_once 'config.php';
require_once "./classes/SQL.php";
require_once "./classes/ApplicationConstants.php";

if (isset($_REQUEST['cmd'])) {
    switch ($_REQUEST['cmd']) {
        case 'getAllParam':
            getAllParam();
            break;
        case 'getAllData':
            getAllData();
            break;
        case 'getAllNews':
            getAllNews();
            break;
        case 'getItemsCount':
            getItemsCount();
            break;
        case 'getBooksCount':
            getBooksCount();
            break;
        case 'getChaptersCount':
            getChaptersCount();
            break;
        case 'getAllItems':
            getAllItems();
            break;
        case 'getAllBooks':
            getAllBooks();
            break;
        case 'getAllChapters':
            getAllChapters();
            break;
        case 'getAllFaqih':
            getAllFaqih();
            break;
        case 'getProblemsByCount':
            getProblemsByCount();
            break;
        case 'getProblemSolutions':
            getProblemSolutions();
            break;
        case 'addProblem':
            addProblem();
            break;
        case 'getProblem':
            getProblem();
            break;
        case 'saveSolution':
            saveSolution();
            break;
        case 'addDevice':
            addDevice();
            break;

    }
} else {
    //$msg = 'no cmd is sent';
    $msg['result'] = '0';
    $msg['message'] = 'fail';
    $msg['data'] = "no cmd is sent";
    $error['status'] = $msg;
    $json_encoded_string = json_encode($error);
    $json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
    print $json_encoded_string;
//exit;
}

function getAllParam()
{
    $connection = db_connect();

    $params = array();
    $is_admin = false;
    $user_name = "";

    if (isset($_REQUEST['device_id'])) {
        $device_id = $_REQUEST['device_id'];
    }
    else
    {
        $device_id = "";
        $is_admin = false;
    }


    ///////////// PARAMS ///////////////////////////////
    $query = "SELECT * FROM `param` WHERE `status` = '1'";

    $result = mysqli_query($connection, $query);
    if (mysqli_num_rows($result) <= 0) {
        $msg = "Data not found...!";
    }

    if ($result) {
        while ($row = mysqli_fetch_array($result)) {
            $updated_on = $row['updated_on'];
            $update = str_replace(':', '', $updated_on);
            $update = str_replace('-', '', $update);
            $update = str_replace(' ', '', $update);
            $params[] = array('param_id' => $row['param_id'], 'name' => $row['name'], 'value' => $row['value'], 'status' => $row['status'],
                'changed_on' => $updated_on, 'update_time' => $update);
        }
    }

    // //////////// check if the user is admin ///////////////
    if($device_id != "")
    {
        $query2 = "SELECT * FROM `user` WHERE `device1_id` = '$device_id' || `device2_id` = '$device_id' LIMIT 1";
        $result2 = mysqli_query($connection, $query2);
        if (mysqli_num_rows($result2) > 0) {
            $row2 = mysqli_fetch_array($result2);
            $is_admin = true;
            $user_name = $row2['user_name'];
        }
    }

    db_disconnect($connection);

    $msg['param_count'] = "6";
    $msg['params'] = $params;
    $msg['is_admin'] = $is_admin;
    $msg['user_name'] = $user_name;
    $msg['success'] = '1';
    $msg['message'] = "Success";

    $output['data'] = $msg;
    $json_encoded_string = json_encode($output);
    $json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
    print $json_encoded_string;
}


///////////////////////////////////////////////////////////////////////////////


function getAllData()
{
    $connection = db_connect();

    $items = array();
    $books = array();
    $chapters = array();
    $faqih = array();

    ///////////// ITEMS ///////////////////////////////
    $query = "SELECT * FROM `item` WHERE `status` != '0'";

    $result = mysqli_query($connection, $query);
    if (mysqli_num_rows($result) <= 0) {
        $msg = "Data not found...!";
    }

    if ($result) {
        while ($row = mysqli_fetch_array($result)) {
            $changed_on = $row['changed_on'];
            $update = str_replace(':', '', $changed_on);
            $update = str_replace('-', '', $update);
            $update = str_replace(' ', '', $update);
            $items[] = array('item_id' => $row['item_id'], 'item_icon' => $row['item_icon'], 'item_name' => $row['item_name'], 'seq' => $row['seq'],
                'comment' => $row['comment'], 'status' => $row['status'], 'created_on' => $row['created_on'], 'created_by' => $row['created_by'],
                'changed_on' => $changed_on, 'changed_by' => $row['changed_by'], 'update_time' => $update);
        }
    }
    /////////////////// BOOKS ////////////////////////////////////////////
    $query2 = "SELECT * FROM `book` WHERE `status` = '1'";
    $result2 = mysqli_query($connection, $query2);
    while ($row2 = mysqli_fetch_array($result2)) {
        $changed_on = $row2['changed_on'];
        $update = str_replace(':', '', $changed_on);
        $update = str_replace('-', '', $update);
        $update = str_replace(' ', '', $update);
        $books[] = array('book_id' => $row2['book_id'], 'book_icon' => $row2['book_icon'], 'book_name' => $row2['book_name'], 'book_type' => $row2['book_type'],
            'seq' => $row2['seq'], 'comment' => $row2['comment'], 'status' => $row2['status'], 'created_on' => $row2['created_on'], 'created_by' => $row2['created_by'],
            'changed_on' => $changed_on, 'changed_by' => $row2['changed_by'], 'update_time' => $update);
    }
    //////////////// Chapters /////////////////
    $query3 = "SELECT * FROM `chapter` WHERE `status` = '1'";
    $result3 = mysqli_query($connection, $query3);
    while ($row3 = mysqli_fetch_array($result3)) {
        $changed_on = $row3['changed_on'];
        $update = str_replace(':', '', $changed_on);
        $update = str_replace('-', '', $update);
        $update = str_replace(' ', '', $update);
        $chapters[] = array('chapter_id' => $row3['chapter_id'], 'book_id' => $row3['book_id'], 'chapter_icon' => $row3['chapter_icon'],
            'chapter_name' => $row3['chapter_name'], 'seq' => $row3['seq'], 'comment' => $row3['comment'], 'status' => $row3['status'],
            'created_on' => $row3['created_on'], 'created_by' => $row3['created_by'], 'changed_on' => $changed_on, 'changed_by' => $row3['changed_by'], 'update_time' => $update);
    }

    ////////////////////// FAQIH ///////////////////////////
    $query4 = "SELECT * FROM `faqih` WHERE `status` = '1'";
    $result4 = mysqli_query($connection, $query4);
    while ($row4 = mysqli_fetch_array($result4)) {
        $changed_on = $row4['changed_on'];
        $update = str_replace(':', '', $changed_on);
        $update = str_replace('-', '', $update);
        $update = str_replace(' ', '', $update);
        $faqih[] = array('faqih_id' => $row4['faqih_id'], 'faqih_icon' => $row4['faqih_icon'], 'faqih_name' => $row4['faqih_name'], 'seq' => $row4['seq'],
            'comment' => $row4['comment'], 'status' => $row4['status'], 'created_on' => $row4['created_on'], 'created_by' => $row4['created_by'],
            'changed_on' => $changed_on, 'changed_by' => $row4['changed_by'], 'update_time' => $update);
    }

    /////////////////////// PARAMS ////////////////////
//    $query5 = "SELECT * FROM `param` WHERE `status` = '1'";
//    $result5 = mysqli_query($connection, $query5);
//    $row5 = mysqli_fetch_array($result5);
//    $server_version = $row5['value'];

    db_disconnect($connection);

//    if(count($items)>0)
//    {
    $items = sksort($items, "seq", true);
    $msg['item_count'] = "6";//$changed_on;
    $msg['items'] = $items;
    $books = sksort($books, "seq", true);
    $msg['book_count'] = "4";//$changed_on;
    $msg['books'] = $books;
    $chapters = sksort($chapters, "seq", true);
    $msg['chapter_count'] = "99";//$changed_on;
    $msg['chapters'] = $chapters;
    $faqih = sksort($faqih, "seq", true);
    $msg['faqih_count'] = "20";//$changed_on;
    $msg['faqih'] = $faqih;

    $msg['success'] = '1';
    //$msg['server_version'] = $server_version;
    $msg['message'] = "Success";
    //}

    $output['data'] = $msg;
    $json_encoded_string = json_encode($output);
    $json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
    print $json_encoded_string;
}


///////////////////////////////////////////////////////////////////////////////

function getAllNews()
{
    $connection = db_connect();

    $news = array();

    ///////////// NEWS ///////////////////////////////
    $query = "SELECT * FROM `news` WHERE `status` = '4'";

    $result = mysqli_query($connection, $query);
    if (mysqli_num_rows($result) <= 0) {
        $msg = "Data not found...!";
    }
    db_disconnect($connection);
    if ($result) {
        while ($row = mysqli_fetch_array($result)) {
            $updated_on = $row['changed_on'];
            $update = str_replace(':', '', $updated_on);
            $update = str_replace('-', '', $update);
            $update = str_replace(' ', '', $update);
            $news[] = array('news_id' => $row['news_id'], 'title' => $row['title'], 'summary' => $row['summary'],
                'content' => $row['content'], 'image' => $row['image'], 'comment' => $row['comment'],
                'status' => $row['status'], 'created_on' => $row['created_on'], 'created_by' => $row['created_by'],
                'changed_on' => $updated_on, 'changed_by' => $row['changed_by'], 'update_time' => $update);
        }
    }

    $msg['news_count'] = "6";
    $msg['news'] = $news;
    $msg['success'] = '1';
    $msg['message'] = "Success";

    $output['data'] = $msg;
    $json_encoded_string = json_encode($output);
    $json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
    print $json_encoded_string;
}

///////////////////////////////////////////////////////////////////////////////

function getItemsCount()
{
    $connection = db_connect();

    $item_count = array();
    $time_txt = "";
    if (isset($_REQUEST['time'])) {
        $time = $_REQUEST['time'];
        if ($time != '')
            $time_txt = " AND  `changed_on` > " . $_REQUEST['time'];
    }

    ///////////// Item ///////////////////////////////
    $query = "SELECT Count(`solution_id`) AS count, `item_id` FROM `solution` WHERE `status` = '4'" . $time_txt . " GROUP BY `item_id` ";

    $result = mysqli_query($connection, $query);
    if (mysqli_num_rows($result) <= 0) {
        $msg = "Data not found...!";
    }
    //db_disconnect($connection);
    if ($result) {
        while ($row = mysqli_fetch_array($result)) {
            $item_count[] = array('item_id' => $row['item_id'], 'count' => $row['count']);
        }
    }
    //////////// News ///////////////////////////
    $query2 = "SELECT Count(`news_id`) AS count FROM `news` WHERE `status` = '4' " . $time_txt;

    $result2 = mysqli_query($connection, $query2);
    if (mysqli_num_rows($result) <= 0) {
        $msg = "Data not found...!";
    }
    db_disconnect($connection);
    if ($result2) {
        while ($row2 = mysqli_fetch_array($result2)) {
            $item_count[] = array('item_id' => '5', 'count' => $row2['count']);
        }
    }
    ///////////////////

    //$msg['news_count'] = "6";
    $msg['item_count'] = $item_count;
    $msg['success'] = '1';
    $msg['message'] = "Success";

    $output['data'] = $msg;
    $json_encoded_string = json_encode($output);
    $json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
    print $json_encoded_string;
}


///////////////////////////////////////////////////////////////////////////////

function getBooksCount()
{
    $connection = db_connect();

    if (isset($_REQUEST['item_id']))
        $item_id = $_REQUEST['item_id'];
    else
        $item_id = "";

    $book_count = array();
    $time_txt = "";
    if (isset($_REQUEST['time'])) {
        $time = $_REQUEST['time'];
        if ($time != '')
            $time_txt = " AND  `changed_on` > " . $_REQUEST['time'];
    }

    ///////////// books ///////////////////////////////
    $query = "SELECT Count(`solution_id`) AS count, `book_id` FROM `solution` WHERE `status` = '4' AND `item_id` = '$item_id' " . $time_txt . " GROUP BY `book_id` ";

    $result = mysqli_query($connection, $query);
    if (mysqli_num_rows($result) <= 0) {
        $msg = "Data not found...!";
    }
    db_disconnect($connection);
    if ($result) {
        while ($row = mysqli_fetch_array($result)) {
            $book_count[] = array('book_id' => $row['book_id'], 'count' => $row['count']);
        }
    }
    ///////////////////

    //$msg['news_count'] = "6";
    $msg['book_count'] = $book_count;
    $msg['success'] = '1';
    $msg['message'] = "Success";

    $output['data'] = $msg;
    $json_encoded_string = json_encode($output);
    $json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
    print $json_encoded_string;
}


///////////////////////////////////////////////////////////////////////////////

function getChaptersCount()
{
    $connection = db_connect();

    if (isset($_REQUEST['item_id']))
        $item_id = $_REQUEST['item_id'];
    else
        $item_id = "";

    if (isset($_REQUEST['book_id']))
        $book_id = $_REQUEST['book_id'];
    else
        $book_id = "";


    $chapters_count = array();
    $time_txt = "";
    if (isset($_REQUEST['time'])) {
        $time = $_REQUEST['time'];
        if ($time != '')
            $time_txt = " AND  `changed_on` > " . $_REQUEST['time'];
    }

    ///////////// books ///////////////////////////////
    $query = "SELECT Count(`solution_id`) AS count, `chapter_id` FROM `solution` WHERE `status` = '4' AND `book_id` = '$book_id' AND `item_id` = '$item_id'" . $time_txt . " GROUP BY `chapter_id` ";

    $result = mysqli_query($connection, $query);
    if (mysqli_num_rows($result) <= 0) {
        $msg = "Data not found...!";
    }
    db_disconnect($connection);
    if ($result) {
        while ($row = mysqli_fetch_array($result)) {
            $chapter_count[] = array('chapter_id' => $row['chapter_id'], 'count' => $row['count']);
        }
    }
    ///////////////////

    //$msg['news_count'] = "6";
    $msg['chapter_count'] = $chapter_count;
    $msg['success'] = '1';
    $msg['message'] = "Success";

    $output['data'] = $msg;
    $json_encoded_string = json_encode($output);
    $json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
    print $json_encoded_string;
}


///////////////////////////////////////////////////////////////////////////////

function getAllItems()
{

    $connection = db_connect();
    $data = array();
    $query = "SELECT * FROM `item` WHERE `status` != '0'";

    $result = mysqli_query($connection, $query);
    if (mysqli_num_rows($result) <= 0) {
        $msg = "Data not found...!";
    }
    db_disconnect($connection);

    //$result=mysql_query("SELECT `story_id`, `image_path`,`story_en_name`,`story_ar_name`,`desc_en`,`desc_ar`, `time` FROM `stories` WHERE DATE( `time` ) >= '$date'");
    if ($result) {

//        if (mysqli_num_rows($result) <= 0) {
//            $msg = "Data not found...!";
//        }

//        $sql="SELECT max( time ) FROM `stories`";
//            $get_nodes = mysql_query($sql);
//	$nodes = mysql_fetch_row($get_nodes);
//
//	$time= $nodes[0];

        while ($row = mysqli_fetch_array($result)) {
            //$my_selfi = explode(",", $test['item_icon']);
            //foreach ($my_selfi as $part) {
            //                $host = $_SERVER['HTTP_HOST'];
            //                $selfi = $_SERVER['PHP_SELF'];
            //                $my_selfi = explode("webservice", $selfi);
            $item_id = $row['item_id'];
            $item_icon = $row['item_icon'];
            $item_name = $row['item_name'];
            $seq = $row['seq'];
            $comment = $row['comment'];
            $status = $row['status'];
            $created_on = $row['created_on'];
            $created_by = $row['created_by'];
            $changed_on = $row['changed_on'];
            $changed_by = $row['changed_by'];
            $update = str_replace(':', '', $changed_on);
            $update = str_replace('-', '', $update);
            $update = str_replace(' ', '', $update);
            //                $my_path = "http://" . $host . $my_selfi[0] . "images/" . $image_path;
            //                $my_icon_path = "http://" . $host . $my_selfi[0] . "images/" . $icon_path;
            // }
            //$path = "http://joomlavogueteamdemo.com.bh-in-7.webhostbox.net/admin_nrm/images/".$my_selfi;
            $data[] = array('item_id' => $item_id, 'item_icon' => $item_icon, 'item_name' => $item_name, 'seq' => $seq,
                'comment' => $comment, 'status' => $status, 'created_on' => $created_on, 'created_by' => $created_by,
                'changed_on' => $changed_on, 'changed_by' => $changed_by, 'update_time' => $update);


        }
        if (count($data) > 0) {
            $data = sksort($data, "seq", true);
            $msg['success'] = '1';
            $msg['message'] = "Success";
            $msg['time'] = "6";//$changed_on;
            $msg['data'] = $data;
        }
    } else {
        $msg['message'] = mysql_error();
    }
    //}else{
    //$msg['result'] = '0';
    //$msg['message'] = 'fail';
    //$msg['data'] = "Missing parameter, Please add required parameter!!!";
//}
    $error['status'] = $msg;
    $json_encoded_string = json_encode($error);
    $json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
    print $json_encoded_string;
}


///////////////////////////////////////////////////////////////////////////////
function getAllBooks()
{

    $connection = db_connect();
    $data = array();
    $query = "SELECT * FROM `book` WHERE `status` = '1'";

    $result = mysqli_query($connection, $query);
    if (mysqli_num_rows($result) <= 0) {
        $msg = "Data not found...!";
    }
    db_disconnect($connection);
    //$result=mysql_query("SELECT `story_id`, `image_path`,`story_en_name`,`story_ar_name`,`desc_en`,`desc_ar`, `time` FROM `stories` WHERE DATE( `time` ) >= '$date'");
    if ($result) {

//        if (mysqli_num_rows($result) <= 0) {
//            $msg = "Data not found...!";
//        }

//        $sql="SELECT max( time ) FROM `stories`";
//            $get_nodes = mysql_query($sql);
//	$nodes = mysql_fetch_row($get_nodes);
//
//	$time= $nodes[0];

        while ($row = mysqli_fetch_array($result)) {
            //$my_selfi = explode(",", $test['item_icon']);
            //foreach ($my_selfi as $part) {
            //                $host = $_SERVER['HTTP_HOST'];
            //                $selfi = $_SERVER['PHP_SELF'];
            //                $my_selfi = explode("webservice", $selfi);
            $book_id = $row['book_id'];
            $book_icon = $row['book_icon'];
            $book_name = $row['book_name'];
            $book_type = $row['book_type'];
            $seq = $row['seq'];
            $comment = $row['comment'];
            $status = $row['status'];
            $created_on = $row['created_on'];
            $created_by = $row['created_by'];
            $changed_on = $row['changed_on'];
            $changed_by = $row['changed_by'];
            $update = str_replace(':', '', $changed_on);
            $update = str_replace('-', '', $update);
            $update = str_replace(' ', '', $update);
            //                $my_path = "http://" . $host . $my_selfi[0] . "images/" . $image_path;
            //                $my_icon_path = "http://" . $host . $my_selfi[0] . "images/" . $icon_path;
            // }
            //$path = "http://joomlavogueteamdemo.com.bh-in-7.webhostbox.net/admin_nrm/images/".$my_selfi;
            $data[] = array('book_id' => $book_id, 'book_icon' => $book_icon, 'book_name' => $book_name, 'book_type' => $book_type, 'seq' => $seq,
                'comment' => $comment, 'status' => $status, 'created_on' => $created_on, 'created_by' => $created_by,
                'changed_on' => $changed_on, 'changed_by' => $changed_by, 'update_time' => $update);


        }
        if (count($data) > 0) {
            $data = sksort($data, "seq", true);
            $msg['success'] = '1';
            $msg['message'] = "Success";
            $msg['time'] = "6";//$changed_on;
            $msg['data'] = $data;
        }
    } else {
        $msg['message'] = mysql_error();
    }
    //}else{
    //$msg['result'] = '0';
    //$msg['message'] = 'fail';
    //$msg['data'] = "Missing parameter, Please add required parameter!!!";
//}
    $error['status'] = $msg;
    $json_encoded_string = json_encode($error);
    $json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
    print $json_encoded_string;
}


///////////////////////////////////////////////////////////////////////////////////////////////////


function getAllChapters()
{

    $connection = db_connect();
    $data = array();
    $query = "SELECT * FROM `chapter` WHERE `status` = '1'";

    $result = mysqli_query($connection, $query);
    if (mysqli_num_rows($result) <= 0) {
        $msg = "Data not found...!";
    }
    db_disconnect($connection);
    //$result=mysql_query("SELECT `story_id`, `image_path`,`story_en_name`,`story_ar_name`,`desc_en`,`desc_ar`, `time` FROM `stories` WHERE DATE( `time` ) >= '$date'");
    if ($result) {

//        if (mysqli_num_rows($result) <= 0) {
//            $msg = "Data not found...!";
//        }

//        $sql="SELECT max( time ) FROM `stories`";
//            $get_nodes = mysql_query($sql);
//	$nodes = mysql_fetch_row($get_nodes);
//
//	$time= $nodes[0];

        while ($row = mysqli_fetch_array($result)) {
            //$my_selfi = explode(",", $test['item_icon']);
            //foreach ($my_selfi as $part) {
            //                $host = $_SERVER['HTTP_HOST'];
            //                $selfi = $_SERVER['PHP_SELF'];
            //                $my_selfi = explode("webservice", $selfi);
            $chapter_id = $row['chapter_id'];
            $book_id = $row['book_id'];
            $chapter_icon = $row['chapter_icon'];
            $chapter_name = $row['chapter_name'];
            //$book_type = $row['book_type'];
            $seq = $row['seq'];
            $comment = $row['comment'];
            $status = $row['status'];
            $created_on = $row['created_on'];
            $created_by = $row['created_by'];
            $changed_on = $row['changed_on'];
            $changed_by = $row['changed_by'];
            $update = str_replace(':', '', $changed_on);
            $update = str_replace('-', '', $update);
            $update = str_replace(' ', '', $update);
            //                $my_path = "http://" . $host . $my_selfi[0] . "images/" . $image_path;
            //                $my_icon_path = "http://" . $host . $my_selfi[0] . "images/" . $icon_path;
            // }
            //$path = "http://joomlavogueteamdemo.com.bh-in-7.webhostbox.net/admin_nrm/images/".$my_selfi;
            $data[] = array('chapter_id' => $chapter_id, 'book_id' => $book_id, 'chapter_icon' => $chapter_icon, 'chapter_name' => $chapter_name, 'seq' => $seq,
                'comment' => $comment, 'status' => $status, 'created_on' => $created_on, 'created_by' => $created_by,
                'changed_on' => $changed_on, 'changed_by' => $changed_by, 'update_time' => $update);


        }
        if (count($data) > 0) {
            $data = sksort($data, "seq", true);
            $msg['success'] = '1';
            $msg['message'] = "Success";
            $msg['time'] = "6";//$changed_on;
            $msg['data'] = $data;
        }
    } else {
        $msg['message'] = mysql_error();
    }
    //}else{
    //$msg['result'] = '0';
    //$msg['message'] = 'fail';
    //$msg['data'] = "Missing parameter, Please add required parameter!!!";
//}
    $error['status'] = $msg;
    $json_encoded_string = json_encode($error);
    $json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
    print $json_encoded_string;
}


///////////////////////////////////////////////////////////////////////////////////////////////////


function getAllFaqih()
{

    $connection = db_connect();
    $data = array();
    $query = "SELECT * FROM `faqih` WHERE `status` = '1'";

    $result = mysqli_query($connection, $query);
    if (mysqli_num_rows($result) <= 0) {
        $msg = "Data not found...!";
    }
    db_disconnect($connection);
    //$result=mysql_query("SELECT `story_id`, `image_path`,`story_en_name`,`story_ar_name`,`desc_en`,`desc_ar`, `time` FROM `stories` WHERE DATE( `time` ) >= '$date'");
    if ($result) {

//        if (mysqli_num_rows($result) <= 0) {
//            $msg = "Data not found...!";
//        }

//        $sql="SELECT max( time ) FROM `stories`";
//            $get_nodes = mysql_query($sql);
//	$nodes = mysql_fetch_row($get_nodes);
//
//	$time= $nodes[0];

        while ($row = mysqli_fetch_array($result)) {
            //$my_selfi = explode(",", $test['item_icon']);
            //foreach ($my_selfi as $part) {
            //                $host = $_SERVER['HTTP_HOST'];
            //                $selfi = $_SERVER['PHP_SELF'];
            //                $my_selfi = explode("webservice", $selfi);
            $faqih_id = $row['faqih_id'];
            $faqih_icon = $row['faqih_icon'];
            $faqih_name = $row['faqih_name'];
            $seq = $row['seq'];
            $comment = $row['comment'];
            $status = $row['status'];
            $created_on = $row['created_on'];
            $created_by = $row['created_by'];
            $changed_on = $row['changed_on'];
            $changed_by = $row['changed_by'];
            $update = str_replace(':', '', $changed_on);
            $update = str_replace('-', '', $update);
            $update = str_replace(' ', '', $update);
            //                $my_path = "http://" . $host . $my_selfi[0] . "images/" . $image_path;
            //                $my_icon_path = "http://" . $host . $my_selfi[0] . "images/" . $icon_path;
            // }
            //$path = "http://joomlavogueteamdemo.com.bh-in-7.webhostbox.net/admin_nrm/images/".$my_selfi;
            $data[] = array('faqih_id' => $faqih_id, 'faqih_icon' => $faqih_icon, 'faqih_name' => $faqih_name, 'seq' => $seq,
                'comment' => $comment, 'status' => $status, 'created_on' => $created_on, 'created_by' => $created_by,
                'changed_on' => $changed_on, 'changed_by' => $changed_by, 'update_time' => $update);


        }
        if (count($data) > 0) {
            $data = sksort($data, "seq", true);
            $msg['success'] = '1';
            $msg['message'] = "Success";
            $msg['time'] = "6";//$changed_on;
            $msg['data'] = $data;
        }
    } else {
        $msg['message'] = mysql_error();
    }
    //}else{
    //$msg['result'] = '0';
    //$msg['message'] = 'fail';
    //$msg['data'] = "Missing parameter, Please add required parameter!!!";
//}
    $error['status'] = $msg;
    $json_encoded_string = json_encode($error);
    $json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
    print $json_encoded_string;
}

///////////////////////////////////////////////////////////////////////////////////////////////////


function getProblemsByCount()
{
    if (isset($_REQUEST['is_answer']))
        $is_answer = $_REQUEST['is_answer'];
    else
        $is_answer = "false";
    if (isset($_REQUEST['start']))
        $start = $_REQUEST['start'];
    else
        $start = "0";

    if (isset($_REQUEST['count']))
        $count = $_REQUEST['count'];
    else
        $count = "20";
    $item_txt = "";
    $book_txt = "";
    $chapter_txt = "";
    $faqih_text = "";
    $latest_txt = "";
    $device_txt = "";
    $status_txt = "`status` = '4' ";
    if (isset($_REQUEST['faqih_id']) && $_REQUEST['faqih_id'] != 0) {
        $faqih_id = $_REQUEST['faqih_id'];
        $faqih_text = " AND `problem`.`faqih_id` = '$faqih_id' ";
    } //" AND (`problem`.`faqih_id` = '$faqih_id' || `solution`.`faqih_id` = '$faqih_id') ";
    if (isset($_REQUEST['item_id']) && $_REQUEST['item_id'] != 0) {
        $item_id = $_REQUEST['item_id'];
        $item_txt = " AND `problem`.`item_id` = '$item_id' ";
    }
    if (isset($_REQUEST['book_id']) && $_REQUEST['book_id'] != '0') {
        $book_id = $_REQUEST['book_id'];
        $book_txt = " AND `problem`.`book_id` = '$book_id' ";
    }
    if (isset($_REQUEST['chapter_id']) && $_REQUEST['chapter_id'] != '0') {
        $chapter_id = $_REQUEST['chapter_id'];
        $chapter_txt = " AND `problem`.`chapter_id` = '$chapter_id' ";
    }
    if (isset($_REQUEST['problem']) && $_REQUEST['problem'] != "") {
        $problem = $_REQUEST['problem'];
        if ($problem != '')
            $problem_txt = " AND `problem`.`problem_text` LIKE '%$problem%' ";
    } else $problem_txt = '';
    if (isset($_REQUEST['latest']) && $_REQUEST['latest'] == "true") {
        $latest_txt = " ORDER BY  `changed_on` DESC ";
    }
    if (isset($_REQUEST['device_id']) && $_REQUEST['device_id'] != '0') {
        $device_id = $_REQUEST['device_id'];
        $device_txt = " AND `problem`.`device_id` = '$device_id' ";
        $status_txt = "(`status` != '0') ";//  || `status` = '3' || `status` = '2' || `status` = '1')";
    }
    $connection = db_connect();
    $data = array();
    // SELECT *
//    FROM  `problem`
//ORDER BY  `changed_on` DESC
//LIMIT 0 , 5
    // to get the count of questions

    $query1 = "SELECT COUNT(`problem_id`) AS 'count' FROM `problem` WHERE  ".$status_txt . $item_txt . $book_txt . $chapter_txt . $problem_txt . $latest_txt.$device_txt;//." LIMIT ".$start." ,".$count; // need to add faqih as well
    $result1 = mysqli_query($connection, $query1);
    $row1 = mysqli_fetch_array($result1);
    $AllCount = $row1['count'];


    $query = "SELECT * FROM `problem` WHERE  ".$status_txt . $item_txt . $book_txt . $chapter_txt . $problem_txt . $latest_txt . $device_txt . " LIMIT " . $start . " ," . $count; // need to add faqih as well

    if ($is_answer != "false") {
        $query = "SELECT * FROM `problem` WHERE `status` = '1' ||  `status` = '2'";
        $query1 = "SELECT COUNT(`problem_id`) AS 'count' FROM `problem` WHERE `status` = '1' || `status` = '2'";
        $result1 = mysqli_query($connection, $query1);
        $row1 = mysqli_fetch_array($result1);
        $AllCount = $row1['count'];
    }
    $result = mysqli_query($connection, $query);
    if (mysqli_num_rows($result) <= 0) {
        $msg['message'] = "Data not found...!";
    }

    db_disconnect($connection);
    //$result=mysql_query("SELECT `story_id`, `image_path`,`story_en_name`,`story_ar_name`,`desc_en`,`desc_ar`, `time` FROM `stories` WHERE DATE( `time` ) >= '$date'");
    if ($result) {
        while ($row = mysqli_fetch_array($result)) {
            $changed_on = $row['changed_on'];
            $update = str_replace(':', '', $changed_on);
            $update = str_replace('-', '', $update);
            $update = str_replace(' ', '', $update);
            $data[] = array('problem_id' => $row['problem_id'], 'problem_text' => $row['problem_text'], 'book_id' => $row['book_id'],
                'status' => $row['status'], 'name' => $row['name'], 'email' => $row['email'], 'mobile' => $row['mobile'],
                'chapter_id' => $row['chapter_id'], 'item_id' => $row['item_id'], 'faqih_id' => $row['faqih_id'], 'update_time' => $update);

        }
        if (count($data) > 0) {
            $data = sksort($data, "update_time", false);
            $msg['success'] = '1';
            $msg['message'] = "Success";
            $msg['time'] = $AllCount;//$changed_on;
            $msg['data'] = $data;
        }
    } else {
        $msg['message'] = mysql_error();
    }
    //}else{
    //$msg['result'] = '0';
    //$msg['message'] = 'fail';
    //$msg['data'] = "Missing parameter, Please add required parameter!!!";
//}
    $error['status'] = $msg;
    $json_encoded_string = json_encode($error);
    $json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
    print $json_encoded_string;
}


////////////////////////////////////////////////////////////////////

function getProblemSolutions()
{
    if (isset($_REQUEST['problem_id'])) {
        $problem_id = $_REQUEST['problem_id'];
        $connection = db_connect();
        $data = array();
        $query = "SELECT `solution`.*, `faqih`.`faqih_name` FROM `solution`, `faqih`  WHERE `solution`.`status` != '0' AND `solution`.`faqih_id` = `faqih`.`faqih_id`
                  AND `solution`.`problem_id` = " . $problem_id;

        $result = mysqli_query($connection, $query);
        if (mysqli_num_rows($result) <= 0) {
            $msg['message'] = "Data not found...!";
        }
        $query2 = "SELECT * FROM `problem` WHERE `status` != '0' AND `problem_id` = " . $problem_id;

        $result2 = mysqli_query($connection, $query2);
        if (mysqli_num_rows($result2) <= 0) {
            $msg['message'] = "Data not found...!";
            $msg['problem_text'] = "";
        }
        else
        {
            $problem = array();
            while ($row2 = mysqli_fetch_array($result2)) {
                $problem[] = array('problem_id' => $row2['problem_id'], 'problem_text' => $row2['problem_text'], 'name' => $row2['name'], 'mobile' => $row2['mobile'],
                    'email' => $row2['email'], 'faqih_id' => $row2['faqih_id'], 'book_id' => $row2['book_id'], 'chapter_id' => $row2['chapter_id']);
                $msg['problem'] = $problem;
            }
        }
        db_disconnect($connection);
        //$result=mysql_query("SELECT `story_id`, `image_path`,`story_en_name`,`story_ar_name`,`desc_en`,`desc_ar`, `time` FROM `stories` WHERE DATE( `time` ) >= '$date'");
        if ($result) {
            while ($row = mysqli_fetch_array($result)) {
                $changed_on = $row['changed_on'];
                $update = str_replace(':', '', $changed_on);
                $update = str_replace('-', '', $update);
                $update = str_replace(' ', '', $update);
                $data[] = array('solution_id' => $row['solution_id'], 'solution_text' => $row['solution_text'], 'problem_id' => $row['problem_id'],
                    'faqih_name' => $row['faqih_name'], 'faqih_id' => $row['faqih_id'], 'update_time' => $update);

            }
            if (count($data) > 0) {
                $data = sksort($data, "update_time", true);
                $msg['success'] = '1';
                $msg['message'] = "Success";
                $msg['time'] = "6";//$changed_on;
                $msg['data'] = $data;
            }
        } else {
            $msg['message'] = mysql_error();
        }
    } else {
        $msg['message'] = "Missing Parameter";
    }
    $error['status'] = $msg;
    $json_encoded_string = json_encode($error);
    $json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
    print $json_encoded_string;
}


////////////////////////////////////////////////////////////////////
function getProblem()
{
    if (isset($_REQUEST['problem_id'])) {
        $problem_id = $_REQUEST['problem_id'];
        $connection = db_connect();
        $data = array();
        $query = "SELECT * FROM `problem`  WHERE `problem_id` = " . $problem_id;

        $result = mysqli_query($connection, $query);
        if (mysqli_num_rows($result) <= 0) {
            $msg['message'] = "Data not found...!";
        }
        db_disconnect($connection);
        //$result=mysql_query("SELECT `story_id`, `image_path`,`story_en_name`,`story_ar_name`,`desc_en`,`desc_ar`, `time` FROM `stories` WHERE DATE( `time` ) >= '$date'");
        if ($result) {
            while ($row = mysqli_fetch_array($result)) {
                $changed_on = $row['changed_on'];
                $update = str_replace(':', '', $changed_on);
                $update = str_replace('-', '', $update);
                $update = str_replace(' ', '', $update);
                $data[] = array('problem_id' => $row['problem_id'], 'problem_text' => $row['problem_text'], 'item_id' => $row['item_id'], 'book_id' => $row['book_id'],
                    'chapter_id' => $row['chapter_id'], 'device_id' => $row['device_id'],  'email' => $row['email'], 'mobile' => $row['mobile'],
                    'name' => $row['name'], 'faqih_id' => $row['faqih_id'], 'update_time' => $update);

            }
            if (count($data) > 0) {
                $data = sksort($data, "update_time", true);
                $msg['success'] = '1';
                $msg['message'] = "Success";
                $msg['time'] = "6";//$changed_on;
                $msg['data'] = $data;
            }
        } else {
            $msg['message'] = mysql_error();
        }
    } else {
        $msg['message'] = "Missing Parameter";
    }
    $error['status'] = $msg;
    $json_encoded_string = json_encode($error);
    $json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
    print $json_encoded_string;
}


////////////////////////////////////////////////////////////////////

function addProblem()
{
    $data = "";
//    if (!isset($_REQUEST['insert_values']))
//    {
//        $msg = "One or more parameter is missing";
//        $success = "0";
//    }
    if (!isset($_REQUEST['problem'])) {
        $msg = "One or more parameter is missing";
        $success = "0";
    } else {
        $problem = $_REQUEST['problem'];
        $sql = new SQL();
        $values = array();

        if (isset($_REQUEST['created_by']))
            $created_by = $_REQUEST['created_by'];
        else
            $created_by = "";

        if (isset($_REQUEST['email']))
            $email = $_REQUEST['email'];
        else
            $email = "";
        if (isset($_REQUEST['mobile']))
            $mobile = $_REQUEST['mobile'];
        else
            $mobile = "";
        if (isset($_REQUEST['name']))
            $name = $_REQUEST['name'];
        else
            $name = "";
        if (isset($_REQUEST['faqih_id']))
            $faqih_id = $_REQUEST['faqih_id'];
        else
            $faqih_id = "4"; // غير محدد
        if (isset($_REQUEST['book_id']))
            $book_id = $_REQUEST['book_id'];
        else
            $book_id = "0";
        if (isset($_REQUEST['chapter_id']))
            $chapter_id = $_REQUEST['chapter_id'];
        else
            $chapter_id = "0";
        if (isset($_REQUEST['device_id']))
            $device_id = $_REQUEST['device_id'];
        else
            $device_id = "0";
        if (isset($_REQUEST['new_status']))
            $new_status = $_REQUEST['new_status'];
        else
            $new_status = "1";
        if (isset($_REQUEST['problem_id']))
            $problem_id = $_REQUEST['problem_id'];
        else
            $problem_id = "0";

        $item_id = "2"; // means it is for Fatwa
//        $insert_values = json_decode($_REQUEST['insert_values'], true);
//        for ($index = 0; $index < count($insert_values); $index++) {
//            $problem = $insert_values[$index]['problem'];
//            $email = $insert_values[$index]['email'];
//            $mobile = $insert_values[$index]['mobile'];
//            $faqih_id = $insert_values[$index]['faqih_id'];
//            $book_id = $insert_values[$index]['book_id'];
//            $chapter_id = $insert_values[$index]['chapter_id'];
//            $item_id = "2"; // means it is for Fatwa
//
//            $values[] = array('table_name' => 'problem', 'problem_text' => $problem, 'email' => $email, 'mobile' => $mobile, 'faqih_id' => $faqih_id,
//                'item_id' => $item_id, 'book_id' => $book_id, 'chapter_id' => $chapter_id,
//                'created_on' => date("Y-m-d"), 'created_by' => $created_by);
//        }

        $values[] = array('table_name' => 'problem', 'problem_text' => $problem, 'name' => $name, 'email' => $email, 'mobile' => $mobile,
            'device_id' => $device_id, 'faqih_id' => $faqih_id, 'item_id' => $item_id, 'book_id' => $book_id, 'chapter_id' => $chapter_id,
            'created_on' => date("Y-m-d"), 'created_by' => $created_by);
        if($problem_id != "0") // update
        {
            if($new_status == "0") // delete
            {
                $values = array();
                $values[] = array('table_name' => 'problem', 'problem_id' => $problem_id);
                $sql->deleter($values);
                $values = array();
                $values[] = array('table_name' => 'solution', 'problem_id' => $problem_id);
                $sql->deleter($values);
            }
            else{ // update
                $where = array();
                $where[] = array('problem_id' => $problem_id);
                $sql->update($values, $where);
            }
        }
        else{// insert
            $sql->insert($values);
            //$problem_id = 0;
            $problem_id = $sql->inserted_ids[0];
        }


        if ($problem_id > 0) {
            $success = "1";
            $msg = "success";
        } else {
            $success = "0";
            $msg = "could not insert";
        }
    }

    $result_text['success'] = $success;
    $result_text['message'] = $msg;
    $result_text['time'] = "6";
    $result_text['data'] = $data;
    $result_text['status'] = "";
    $json_encoded_string = json_encode($result_text);

    $json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
    print $json_encoded_string;


}

////////////////////////////////////////////////////////////////////


function saveSolution()
{
    $data = "";
    if (!isset($_REQUEST['solution']) || !isset($_REQUEST['problem_id'])) {
        $msg = "One or more parameter is missing";
        $success = "0";
    } else {
        $solution = $_REQUEST['solution'];
        $problem_id = $_REQUEST['problem_id'];
        $sql = new SQL();
        $values = array();
        //$values = array();

        if (isset($_REQUEST['created_by']))
            $created_by = $_REQUEST['created_by'];
        else
            $created_by = "";

        if (isset($_REQUEST['faqih_id']))
            $faqih_id = $_REQUEST['faqih_id'];
        else
            $faqih_id = "4"; // غير محدد
        if (isset($_REQUEST['book_id']))
            $book_id = $_REQUEST['book_id'];
        else
            $book_id = "0";
        if (isset($_REQUEST['chapter_id']))
            $chapter_id = $_REQUEST['chapter_id'];
        else
            $chapter_id = "0";

        if (isset($_REQUEST['solution_id']))
            $solution_id = $_REQUEST['solution_id'];
        else
            $solution_id = "0";
        if (isset($_REQUEST['status']))
            $status = $_REQUEST['status'];
        else
            $status = "2";

        $item_id = "2"; // means it is for Fatwa
        if ($solution_id == "0") { // This means it is a new solution
            $values[] = array('table_name' => 'solution', 'solution_text' => $solution, 'problem_id' => $problem_id,
                'faqih_id' => $faqih_id, 'item_id' => $item_id, 'book_id' => $book_id, 'chapter_id' => $chapter_id, 'status' => $status,
                'created_on' => date("Y-m-d"), 'created_by' => $created_by);
            $sql->insert($values);
            $solution_id = $sql->inserted_ids[0];
        } else { // it means that an already existing solution

            $where = array();
            $where[] = array('solution_id' => $solution_id);
            $updateValues = array();
            $updateValues[] = array('table_name' => 'solution', 'solution_text' => $solution, 'problem_id' => $problem_id,
                'faqih_id' => $faqih_id, 'item_id' => $item_id, 'book_id' => $book_id, 'chapter_id' => $chapter_id, 'status' => $status,
                'created_on' => date("Y-m-d"), 'created_by' => $created_by);
            $sql->update($updateValues, $where);
        }
        // update problem
        $where = array();
        $where[] = array('problem_id' => $problem_id);
        $updateValues = array();
        $updateValues[] = array('table_name' => 'problem', 'book_id' => $book_id, 'chapter_id' => $chapter_id,
            'status' => $status, 'changed_by' => $created_by);
        $sql->update($updateValues, $where);

        $success = $sql->status;
        $msg = $sql->status;
    }

    $result_text['success'] = $success;
    $result_text['message'] = $msg;
    $result_text['time'] = "6";
    $result_text['data'] = $data;
    $result_text['status'] = "";
    $json_encoded_string = json_encode($result_text);

    $json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
    print $json_encoded_string;


}

////////////////////////////////////////////////////////////////////

function addDevice()
{
    $data = "";
    $sql = new SQL();
    $values = array();

    if (isset($_REQUEST['device_id']))
        $device_id = $_REQUEST['device_id'];
    else
        $device_id = "0";
    if (isset($_REQUEST['new_status']))
        $new_status = $_REQUEST['new_status'];
    else
        $new_status = "1";

    if (isset($_REQUEST['name']))
        $name = $_REQUEST['name'];
    else
        $name = "NULL";
    if (isset($_REQUEST['mobile']))
        $mobile = $_REQUEST['mobile'];
    else
        $mobile = "0";
    if (isset($_REQUEST['email']))
        $email = $_REQUEST['email'];
    else
        $email = "NULL";
    if (isset($_REQUEST['created_by']))
        $created_by = $_REQUEST['created_by'];
    else
        $created_by = "SYSTEM";

    $values[] = array('table_name' => 'device', 'name' => $name, 'email' => $email, 'mobile' => $mobile,
        'created_on' => date("Y-m-d"), 'created_by' => $created_by);

    if($device_id != "0") // update
    {
        if($new_status == "0") // delete
        {
            $values = array();
            $values[] = array('table_name' => 'device', 'device_id' => $device_id);
            $sql->deleter($values);
        }
        else{ // update
            $where = array();
            $where[] = array('device_id' => $device_id);
            $sql->update($values, $where);
        }
    }
    else{// insert
        $sql->insert($values);
        //$problem_id = 0;
        $device_id = $sql->inserted_ids[0];
    }


    if ($device_id > 0) {
        $success = "1";
        $msg = "success";
    } else {
        $success = "0";
        $msg = "could not insert";
    }

    $result_text['success'] = $success;
    $result_text['message'] = $msg;
    $result_text['time'] = "6";
    $result_text['device_id'] = $device_id;
    $result_text['status'] = "";
    $json_encoded_string = json_encode($result_text);

    $json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
    print $json_encoded_string;


}