<?php

class AxcotoFontBirdFontController extends AxcotoFontBirdBaseController {

    public function __construct() {
        
    }

    public function action_index() {
        $urlregex = '^(https?|ftp)\:\/\/([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*(\:[0-9]{2,5})?(\/([a-z0-9+\$_-]\.?)+)*\/?(\?[a-z+&\$_.-][a-z0-9;:@/&%=+\$_.-]*)?(#[a-z_.-][a-z0-9+\$_.-]*)?\$';
        global $wpdb;
        $sql = "SELECT id, name
                        FROM {$wpdb->prefix}fontbird_fonts as f
                        ORDER by id DESC";
        $fonts = $wpdb->get_results($sql);
        foreach ($fonts as &$font) {
            $font->slug = substr($font->name, 0, strlen($font->name) - 4);
            $font->text = ucfirst(str_replace('_', ' ', $font->slug));
            $font->text = str_replace('-', ' ', $font->text);
        }
        include AxcotoFontBird::singleton()->pluginPath . '/templates/font/index.php';
    }

    public function action_new() {
        include AxcotoFontBird::singleton()->pluginPath . '/templates/font/new.php';
    }

    public function action_add() {
        global $wpdb;
        $sql = "SELECT count(*) as total
                            FROM {$wpdb->prefix}fontbird_fonts 
                            WHERE name=%s
                            ";
        $stmt = $wpdb->prepare($sql, $_POST['name']);
        $result = $wpdb->get_var($stmt);
        if ($result >= 1) {
            die('All');
        }

        $sql = "INSERT INTO {$wpdb->prefix}fontbird_fonts (name)
                        VALUES(%s)
          ";

        $stmt = $wpdb->prepare($sql, $_POST['name']);
        $result = $wpdb->query($stmt);
        echo $result;
    }

    public function action_remove($fontId) {
        global $wpdb;
        $sql = "SELECT id, name
                        FROM {$wpdb->prefix}fontbird_fonts
                        WHERE id=%d
            ";
        $stmt = $wpdb->prepare($sql, $fontId);
        $result = $wpdb->get_row($stmt);
        if (is_file($this->getPath('assets/fonts/' . $result->name))) {
            unlink($this->getPath('assets/fonts/' . $result->name));
        }
        $eotName = substr($result->name, 0, strlen($result->name) -3 ) . 'eot';
        if (is_file($this->getPath('assets/fonts/' . $eotName))) {
            unlink($this->getPath('assets/fonts/' . $eotName));
        }

        $sql = "DELETE FROM {$wpdb->prefix}fontbird_fonts
                        WHERE id=%d
            ";
        $stmt = $wpdb->prepare($sql, $fontId);
        $result = $wpdb->get_row($stmt);
        AxcotoFontBirdUtil::redirect('Success', 'Font was removed', 'font', 'font/index');
    }

}