<?php

/*
 * awframework from aw.inc present aw controller
 * it will help you develop easy and fast with secure tools
 * you can edit and add what you feel right
 * don't change in strucure of file
 */

require_once("imp/_imp.php");

class Controllers {

    //public vars
    public $smarty;
    public $hosturl;

    // it will run in everytime with
    // default requried
    public function __construct() {
        require_once("../public/aw_config.php");
        $this->hosturl = $hosturl;

        //http://stackoverflow.com/questions/18382740/cors-not-working-php
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');    // cache for 1 day
        }

// Access-Control headers are received during OPTIONS requests
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
                header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
                header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

            exit(0);
        }
    }

    public function selectAllArticals() {

        $user_id = $_GET['id'];
        $allArticals = R::getAll('
                select articals.* , cats.name as catName
                from articals
                join cats on cats.id = articals.artical_cat');

        foreach ($allArticals as $val) {
            $favorite = 'no';
            if (!empty($user_id)) {
                //# check artical exist in favorite or not .
                $countRow = R::count('favorites', 'user_id = ? and artical_id = ? ', [$user_id, $val['id']]);
                if ($countRow > 0) {
                    $favorite = 'yes';
                }
            }
            $arrContainer[] = array(
                'id' => $val['id'],
                'artical_name' => $val['artical_name'],
                'artical_cat' => $val['artical_cat'],
                'catName' => $val['catName'],
                'img' => $this->hosturl . '/../upload/m_articals/' . $val['img'],
                'main_txt' => $val['main_txt'],
                'main_txt_content' => $val['main_txt_content'],
                'audio_talker' => $val['audio_talker'],
                'audio_voice' => $this->hosturl . '/../upload/m_articals/' . $val['audio_voice'],
                'main_txt2' => $val['main_txt2'],
                'maintxtcontent2' => $val['maintxtcontent2'],
                'favorite' => $favorite
            );
        }
        echo json_encode($arrContainer);
    }

    public function addUser() {

        $regst = $_GET['id'];
        //# convert json to array .
        $regstObj = json_decode($regst);
//        print_r('<pre>');
//        print_r($regstObj);
//        print_r('<pre>');
        $password = $regstObj->matching_passwords->password;
        $user_password_hash = password_hash($password, PASSWORD_DEFAULT);


        $user = R::dispense('users');
        $user->username = $regstObj->username;
        $user->email = $regstObj->email;
        $user->password = $user_password_hash;
        $user->phone = $regstObj->phone;
        $user->agrrement = $regstObj->agrrement;

        try {
            $id = R::store($user);
            if (!empty($id)) {
                $flag = $id;
            } else {
                $flag = 0;
            }
        } catch (Exception $e) {
            $flag = 0;
        }
        $arrContainer[] = $flag;

        echo json_encode($arrContainer);
    }

    public function loginUser() {


        $regst = $_GET['id'];
        //# convert json to array .
        $regstObj = json_decode($regst);

        $email = $regstObj->email;
        $password = $regstObj->password;

        //$user = R::getRow('SELECT * FROM users WHERE email = "' . $email . '" and password = "' . $password . '" ');
        $user = R::getRow('SELECT * FROM users WHERE email = "' . $email . '"  ');

        if (!empty($user)) {

            $hashed_password = $user['password'];
            if (password_verify($password, $hashed_password)) {
                //# password true .
                $flag = $user['id'];
            } else {
                //# password false .
                $flag = -1;
            }
        } else {
            $flag = 0;
        }
        $arrContainer[] = $flag;

        echo json_encode($arrContainer);
    }

    public function addToFavorite() {

        $user_id = $_GET['id'];
        $artical_id = $_GET['other'];
        $countRow = R::count('favorites', 'user_id = ? and artical_id = ? ', [$user_id, $artical_id]);
        $status = '';
        if ($countRow > 0) {
            //# remove from favorite .
            try {
                $id = R::exec('Delete from favorites where user_id = ? and artical_id = ?', [$user_id, $artical_id]);
                $flag = $id;
                $status = 'unfav';
            } catch (Exception $e) {
                $flag = 0;
                $status = 'error';
            }
        } else {
            $fav = R::dispense('favorites');
            $fav->user_id = $user_id;
            $fav->artical_id = $artical_id;


            try {
                $id = R::store($fav);
                if (!empty($id)) {
                    $flag = $id;
                    $status = 'fav';
                } else {
                    $flag = 0;
                    $status = 'error';
                }
            } catch (Exception $e) {
                $flag = 0;
                $status = 'error';
            }
        }


        $arrContainer = array('status' => $status, 'flag' => $flag);


        echo json_encode($arrContainer);
    }

    public function selectAllArtFav() {

        $user_id = $_GET['id'];
        $allArticals = R::getAll('
                select articals.* , cats.name as catName
                from articals
                join cats on cats.id = articals.artical_cat');

        foreach ($allArticals as $val) {
            $favorite = 'no';
            if (!empty($user_id)) {
                //# check artical exist in favorite or not .
                $countRow = R::count('favorites', 'user_id = ? and artical_id = ? ', [$user_id, $val['id']]);
                if ($countRow > 0) {
                    $favorite = 'yes';
                    $arrContainer[] = array(
                        'id' => $val['id'],
                        'artical_name' => $val['artical_name'],
                        'artical_cat' => $val['artical_cat'],
                        'catName' => $val['catName'],
                        'img' => $this->hosturl . '/../upload/m_articals/' . $val['img'],
                        'main_txt' => $val['main_txt'],
                        'main_txt_content' => $val['main_txt_content'],
                        'audio_talker' => $val['audio_talker'],
                        'audio_voice' => $this->hosturl . '/../upload/m_articals/' . $val['audio_voice'],
                        'main_txt2' => $val['main_txt2'],
                        'maintxtcontent2' => $val['maintxtcontent2'],
                        'favorite' => $favorite
                    );
                }
            }
        }
        echo json_encode($arrContainer);
    }

    public function addToDownload() {

        $user_id = $_GET['id'];
        $artical_id = $_GET['other'];
        $countRow = R::count('downloads', 'user_id = ? and artical_id = ? ', [$user_id, $artical_id]);
        $status = '';
        if ($countRow > 0) {
            //# remove from favorite .
            try {
//                $id = R::exec('Delete from favorites where user_id = ? and artical_id = ?', [$user_id, $artical_id]);
//                $flag = $id;
                $status = 'addedBefore';
            } catch (Exception $e) {
                $flag = 0;
                $status = 'error';
            }
        } else {
            $fav = R::dispense('downloads');
            $fav->user_id = $user_id;
            $fav->artical_id = $artical_id;


            try {
                $id = R::store($fav);
                if (!empty($id)) {
                    $flag = $id;
                    $status = 'added';
                } else {
                    $flag = 0;
                    $status = 'error';
                }
            } catch (Exception $e) {
                $flag = 0;
                $status = 'error';
            }
        }


        $arrContainer = array('status' => $status, 'flag' => $flag);


        echo json_encode($arrContainer);
    }

    public function selectAllArtDownloads() {

        $user_id = $_GET['id'];
        $allArticals = R::getAll('
                select articals.* , cats.name as catName
                from articals
                join cats on cats.id = articals.artical_cat');

        foreach ($allArticals as $val) {
            $statusFav = 'no';
            if (!empty($user_id)) {
                //# check artical exist in favorite or not .
                $countRow = R::count('downloads', 'user_id = ? and artical_id = ? ', [$user_id, $val['id']]);
                if ($countRow > 0) {

                    $countRowFav = R::count('favorites', 'user_id = ? and artical_id = ? ', [$user_id, $val['id']]);
                    $status = '';
                    if ($countRowFav > 0) {
                        $statusFav = 'yes';
                    } else {
                        $statusFav = 'no';
                    }


                    $favorite = 'yes';
                    $arrContainer[] = array(
                        'id' => $val['id'],
                        'artical_name' => $val['artical_name'],
                        'artical_cat' => $val['artical_cat'],
                        'catName' => $val['catName'],
                        'img' => $this->hosturl . '/../upload/m_articals/' . $val['img'],
                        'main_txt' => $val['main_txt'],
                        'main_txt_content' => $val['main_txt_content'],
                        'audio_talker' => $val['audio_talker'],
                        'audio_voice' => $this->hosturl . '/../upload/m_articals/' . $val['audio_voice'],
                        'main_txt2' => $val['main_txt2'],
                        'maintxtcontent2' => $val['maintxtcontent2'],
                        'favorite' => $statusFav
                    );
                }
            }
        }
        echo json_encode($arrContainer);
    }

    public function selectAllCategories() {

        $allCats = R::getAll(' select cats.* from cats ');

        foreach ($allCats as $val) {

            $arrContainer[] = array(
                'id' => $val['id'],
                'name' => $val['name'],
            );
        }
        echo json_encode($arrContainer);
    }

    public function selectAllArtiByCategory() {

        $user_id = $_GET['id'];
        $catId = $_GET['other'];

        $allArticals = R::getAll('
                select articals.* , cats.name as catName
                from articals
                join cats on cats.id = articals.artical_cat
                where cats.id = ' . $catId . '
            ');

        foreach ($allArticals as $val) {
            $favorite = 'no';
            if (!empty($user_id)) {
                //# check artical exist in favorite or not .
                $countRow = R::count('favorites', 'user_id = ? and artical_id = ? ', [$user_id, $val['id']]);
                if ($countRow > 0) {
                    $favorite = 'yes';
                }
            }
            $arrContainer[] = array(
                'id' => $val['id'],
                'artical_name' => $val['artical_name'],
                'artical_cat' => $val['artical_cat'],
                'catName' => $val['catName'],
                'img' => $this->hosturl . '/../upload/m_articals/' . $val['img'],
                'main_txt' => $val['main_txt'],
                'main_txt_content' => $val['main_txt_content'],
                'audio_talker' => $val['audio_talker'],
                'audio_voice' => $this->hosturl . '/../upload/m_articals/' . $val['audio_voice'],
                'main_txt2' => $val['main_txt2'],
                'maintxtcontent2' => $val['maintxtcontent2'],
                'favorite' => $favorite
            );
        }
        echo json_encode($arrContainer);
    }

}
