<?php
session_start([0]);

class MainFunction
{
    function __construct()
    {
        $host = "localhost";
        $user = "root";
        $pw = "";
        $db = "daily_prayer_message";
        $this->db = new PDO("mysql:$host", $user, $pw);
        $this->db->exec("set names utf8");
        $this->db->exec("CREATE DATABASE IF NOT EXISTS $db");
        $this->db->exec("USE $db");
    }

    function checkAuth($username, $password)
    {
        $password = md5($password);
        $to = $this->db->query("SELECT * FROM `users` WHERE `username` ='$username' AND `password` ='$password'  ");
        if ($to->rowCount() > 0) {
            $_SESSION['admin'] = $to->fetch(PDO::FETCH_ASSOC);
            return "ok";
        } else {
            return "bad";
        }
    }

    function store($title, $content, $image)
    {
        $url = $this->Slug($title);

        $stmt = $this->db->prepare("insert into articles (title,content,image,url) values (?,?,?,?) ");
        if (!empty($image['tmp_name'])) {
            $imageName = date('Y-m-d') . "-" . $image['name'];
            $path = "../images/thumb/";
            move_uploaded_file($image['tmp_name'], $path . $imageName);
            $stmt->execute([$title, $content, $imageName,$url]);
        } else {
            $stmt->execute([$title, $content, null,$url]);
        }

    }

    function Slug($string)
    {
        return strtolower(trim(preg_replace('~[^0-9a-z]+~i', '-', html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8')), ENT_QUOTES, 'UTF-8')), '-'));
    }

    function delete($id)
    {
        $this->db->query("delete from articles where id = '$id' ");
        return true;
    }

    function update($title, $content, $image, $id)
    {
        $url = $this->Slug($title);

        if (!empty($image['tmp_name'])) {
            $stmt = $this->db->prepare("update articles set title = ?, url = ? ,content = ?, image = ? where id = ? ");
            $imageName = date('Y-m-d') . "-" . $image['name'];
            $path = "../images/thumb/";
            move_uploaded_file($image['tmp_name'], $path . $imageName);
            $stmt->execute([$title, $url,$content, $imageName, $id]);
        } else {
            $stmt = $this->db->prepare("update articles set title = ?,url = ?, content = ? where id = ? ");
            $stmt->execute([$title,$url, $content, $id]);
        }
    }

    function getArticleById($id)
    {
        return $this->db->query("select * from articles where id = '$id' ")->fetch(PDO::FETCH_ASSOC);
    }

    function getArticleByUrl($url)
    {
        return $this->db->query("select * from articles where url = '$url' ")->fetch(PDO::FETCH_ASSOC);
    }

    function getAllArticles()
    {
        return $this->db->query('select * from articles order by id desc')->fetchAll(PDO::FETCH_ASSOC);
    }

    function angels()
    {
        $data = [
            'reveal_1', 
            'reveal_2',
            'reveal_3',
            'reveal_4',
            'reveal_5',
            'reveal_6'
        ];
        return $data;
    }

    function randomArticleSeven()
    {
        return $this->db->query("SELECT * FROM articles ORDER BY RAND() LIMIT 0,6")->fetchAll(PDO::FETCH_ASSOC);
    }

    function popularArticles()
    {
        return $this->db->query("SELECT * FROM articles ORDER BY articles.views desc LIMIT 0,3")->fetchAll(PDO::FETCH_ASSOC);
    }

    function randomArticleOne()
    {
        return $this->db->query("SELECT * FROM articles ORDER BY RAND() LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    }
    function mergeArray($angels,$articles){
        $newArticle = [];
        foreach ($articles as $key => $val){
            $newArticle[] = [
                'id' => $val['id'],
                'title' => $val['title'],
                'content' => $val['content'],
                'image' => $val['image'],
                'url' => $val['url'],
                'angel' => $angels[$key]
            ];
        }
        return $newArticle;
    }

    function updateView($id, $views)
    {
        $stmt = $this->db->prepare("update articles set views = ? where id = ? ");
        $stmt->execute([$views,$id]);
    }
}

$use = new MainFunction();
