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

use Google\Cloud\Firestore\FirestoreClient;

class Subscription_model extends CI_Model
{
    public function get_subscription($id)
    {
        $x = $this->config->item('firebase_app_key');
        $firebaseProjectID = $this->config->item('firesbase_project_id');
        $db = new FirestoreClient([
            'projectId' => $firebaseProjectID,
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);
        $document = $db->collection('Subscriptions')->document($id)->snapshot()->data();
        return $document;
    }

    public function create_subscription($data)
    {
        $x = $this->config->item('firebase_app_key');
        $firebaseProjectID = $this->config->item('firesbase_project_id');
        $firestore = new FirestoreClient([
            'projectId' => $firebaseProjectID,
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);
        $batch = $firestore->collection('Subscriptions')->document($data['userId']);
        $response = $batch->set($data);
        return $data;
    }

    public function update_subscription($id, $data)
    {
        $x = $this->config->item('firebase_app_key');
        $firebaseProjectID = $this->config->item('firesbase_project_id');
        $db = new FirestoreClient([
            'projectId' => $firebaseProjectID,
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);
        try {
            $customerData = array();
            foreach ($data as $key => $value) {
                $d['path'] = $key;
                $d['value'] = $value;
                array_push($customerData, $d);
            }
            $batch = $db->collection('Subscriptions')->document($id);
            $response = $batch->update($customerData);
        } catch (\Throwable $th) {
            return FALSE;
        }
        return TRUE;
    }

    public function delete_subscription($id)
    {
        try {
            $x = $this->config->item('firebase_app_key');
            $firebaseProjectID = $this->config->item('firesbase_project_id');
            $firestore = new FirestoreClient([
                'projectId' => $firebaseProjectID,
                'keyFile' => json_decode(file_get_contents($x), true)
            ]);
            $firestore->collection('Subscriptions')->document($id)->delete();
        } catch (\Kreait\Firebase\Exception\Auth\UserNotFound $e) {
            return FALSE;
        } catch (\Kreait\Firebase\Exception\AuthException $e) {
            return FALSE;
        }
        return $id;
    }
}
