<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

use Google\Cloud\Firestore\FirestoreClient;

class News_model extends CI_Model
{
    public function add_news($data)
    {
        $x = $this->config->item('firebase_app_key');
        $firestore = new FirestoreClient([
            'projectId' => $this->config->item('firebase_project_id'),
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        $newsId = time() . rand();
        $data['newsId'] = $newsId;
        $data['createdDate'] = time() * 1000;
        $data['isActive'] = true;

        $batch = $firestore->collection('News')->document($newsId);
        $response = $batch->create($data);
        return TRUE;
    }

    public function getall_news()
    {
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => $this->config->item('firebase_project_id'),
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        $citiesRef = $db->collection('News')->orderBy('createdDate', 'desc');
        $documents = $citiesRef->documents();
        $output = array();
        foreach ($documents as $document) {
            if ($document->exists()) {
                $output[$document->id()] = $document->data();
            }
        }
        return $output;
    }

    public function get_newsdetails($newsId)
    {
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => $this->config->item('firebase_project_id'),
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);
        $document = $db->collection('News')->document($newsId)->snapshot()->data();

        return $document;
    }

    public function update_news($data)
    {
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => $this->config->item('firebase_project_id'),
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);
        try {
            $newsData = array();
            foreach ($data as $key => $value) {
                $d['path'] = $key;
                $d['value'] = $value;
                array_push($newsData, $d);
            }

            $batch = $db->collection('News')->document($data['newsId']);
            $response = $batch->update($newsData);
        } catch (\Throwable $th) {
            return False;
        }
        return TRUE;
    }

    public function delete_news($newsId)
    {
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => $this->config->item('firebase_project_id'),
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        try {
            $db->collection('News')->document($newsId)->delete();
            return TRUE;
        } catch (\Throwable $th) {
            return FALSE;
        }
    }
}