<?php

include_once 'Model.php';
include_once 'Preferences.php';
include_once 'Short_Code.php';

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Controller
 *
 */
class Controller {

    //put your code here

    public static function shorten_url($url, $webhook = "") {

        $exist_already = Model::get_count_longURL($url) > 0;
        if ($exist_already) {
            Model::set_webhook($url, $webhook);
            return Model::get_short_url($url);
        } else {
            $unique_code = Short_Code::get_unique_short_code();
            if (is_null($unique_code) || empty($unique_code)) {
                return FALSE;
            } else {
                $short_url = Preferences::DOMAIN . $unique_code;

                $saved = Model::save_url_link($url, $short_url, $webhook);
                if ($saved !== FALSE) {
                    return $short_url;
                } else {
                    return FALSE;
                }
            }
        }
    }

    public static function get_long_url($short_url) {
        if (is_null($short_url) || empty($short_url)) {
            return FALSE;
        } else {
            $short_url = Preferences::DOMAIN . $short_url;
            $long_url = Model::get_long_url($short_url);
            if (is_null($long_url) || empty($long_url)) {
                return FALSE;
            } else {
                return $long_url;
            }
        }
    }

    public static function run_webhook($short_url) {
        if (is_null($short_url) || empty($short_url)) {
            return FALSE;
        } else {

            $linkid = $short_url;

            $short_url = Preferences::DOMAIN . $short_url;
            $webhook = Model::get_webhook($short_url);
            if (!empty($webhook)) {

                $data = array(
                    'status' => 'click',
                    'linkid' => $linkid,
                );

                Controller::curl_operations($webhook, $data);
            }
        }
    }

    public static function curl_operations($url, $data = NULL) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if (!is_null($data)) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        $response = curl_exec($ch);
        curl_close($ch);

        return $response;
    }

}
