<?php
class category
{
    const TABLE = 'category';
    const DIRECTORY = 'extend/content/category/';
    const LARGE_WIDTH = 600;
    const LARGE_HEIGHT = 600;
    const MEDIUM_WIDTH = 220;
    const MEDIUM_HEIGHT = 220;
    const SMALL_WIDTH = 48;
    const SMALL_HEIGHT = 48;
    
    ////////////////////////////////////////////////////////////////////////////
    // Construct and destruct functions.
    
    ////////////////////////////////////////////////////////////////////////////
    // Overload functions.

    ////////////////////////////////////////////////////////////////////////////
    // Interface functions.
    
    public static function get($id = '')
    {
        $q = db::query()->select(self::TABLE);
        
        if (!$id)
        {
            $q->where('parent_id', null);
        }
        else
        {
            $q->where('id', $id);
        }
        
        return $q->execute()->fetch();
    }
    
    public static function get_by_path(array $path)
    {
        $g = db::query()->select(self::TABLE)
                        ->where('parent_id', null)
                        ->execute()->fetch();
        
        if (!$path)
        {
            return $g;
        }
        
        $parent_id = $g['id'];
        
        foreach ($path as $p)
        {
            $c = db::query()->select(self::TABLE)
                            ->where('path', $p)
                            ->where('parent_id', $parent_id)
                            ->execute()->fetch();
            
            if (!$c)
            {
                return '';
            }
            
            $parent_id = $c['id'];
        }
        
        return $c;
    }
    
    public static function get_child($id = '', $grandchild = false)
    {
        $q = db::query()->select(self::TABLE . ' c1')
                        ->column('c1.id', 'c1.parent_id', 'c1.path', 'c1.name', 'c1.image')
                        ->join('meta m', array('AND', array('=', 'c1.id', (object) array('type' => 'identifier', 'value' => 'm.type_id')), array('=', 'm.type', 'category')), 'left')
                        ->column('m.title meta');
        
        if (!$id)
        {
            $id = db::query()->select(self::TABLE . ' all')
                             ->column('all.id')
                             ->where('all.parent_id', null)
                             ->limit(1);
        }
        
        if ($grandchild)
        {
            $q->join(self::TABLE . ' c2', array('c2.parent_id', 'c1.id'), 'left')
              ->column('c2.id id2', 'c2.parent_id parent_id2', 'c2.path path2', 'c2.name name2', 'c2.image image2')
              ->order('c1.name')
              ->order('c2.name');
        }
        
        return $q->where('c1.parent_id', $id)
                 ->execute();
    }
    
    public static function get_count()
    {
        $q = db::query()->select(self::TABLE)
                        ->column(sql::raw('COUNT(id) as total'));
        $row = $q->execute()->fetch();
        return $row['total'];
    }
    
    public static function get_tree()
    {
        $current = db::query()->select(self::TABLE)
                              ->where('parent_id', null)
                              ->execute()->fetch();
        
        $tree = array();
        
        $child = db::query()->select(self::TABLE)
                            ->where('>', 'left', $current['left'])
                            ->where('<', 'right', $current['right'])
                            //->order('left')
                            ->order('parent_id')
                            ->order('name')
                            ->execute();
        
        foreach ($child as $c)
        {  
            $tree[$c['parent_id']][] = $c;
        }
        
        return $tree;
    }
    
    public static function get_featured($limit = null)
    {
        $q = db::query()->select(self::TABLE . ' c')
                        ->column('c.id', 'c.path', 'c.name', 'c.image')
                        ->join(self::TABLE . '_featured cf', array('c.id', 'cf.category_id'), 'inner')
                        ->order('cf.id', 'desc');
        
        if ($limit !== null)
        {
            $q->limit($limit);
        }
        
        return $q->execute();
    }
    
    public static function get_path($id = '')
    {
        $path = array();
        
        if (!$id)
        {
            return '';
        }
        
        $left = db::query()->select(self::TABLE)
                              ->column('left')
                              ->where('id', $id)
                              ->limit(1);
        
        $right = db::query()->select(self::TABLE)
                            ->column('right')
                            ->where('id', $id)
                            ->limit(1);
        
        $category = db::query()->select(self::TABLE)
                              ->where('!=', 'parent_id', null)
                              ->where('<=', 'left', $left)
                              ->where('>=', 'right', $right)
                              ->order('left')
                              ->execute();
        
        foreach ($category as $c)
        {
            $path[$c['id']] = $c['path'];
        }
        
        return ($path) ? implode('/', $path) . '/' : '';
    }
    
    public static function get_path_array($id = '')
    {
        $path = array();
        
        if (!$id)
        {
            return $path;
        }
        
        $left = db::query()->select(self::TABLE)
                              ->column('left')
                              ->where('id', $id)
                              ->limit(1);
        
        $right = db::query()->select(self::TABLE)
                            ->column('right')
                            ->where('id', $id)
                            ->limit(1);
        
        $category = db::query()->select(self::TABLE)
                              ->where('!=', 'parent_id', null)
                              ->where('<=', 'left', $left)
                              ->where('>=', 'right', $right)
                              ->order('left')
                              ->execute();
        
        foreach ($category as $c)
        {
            $path[$c['id']] = $c['path'];
        }
        
        return $path;
    }
    
    public static function add(array $data)
    {
        db::get()->begin();
        $parent = db::query()->select(self::TABLE)
                             ->where('id', $data['parent_id'])
                             ->execute()->fetch();
        
        db::query()->update(self::TABLE)
                   ->column('left', sql::raw('`left` + 2'))
                   ->where('>', 'left', $parent['left'])
                   ->execute();
            
        db::query()->update(self::TABLE)
                   ->column('right', sql::raw('`right` + 2'))
                   ->where('>', 'right', $parent['left'])
                   ->execute();
        
        $data['left'] = $parent['left'] + 1;
        $data['right'] = $parent['left'] + 2;
        db::query()->insert(self::TABLE)
                   ->column($data)
                   ->execute();
        
        $id = db::get()->get_last_id();
        unset($data['id'], $data['left'], $data['parent_id'], $data['right']);
        search::save('category', $id, strip_tags(implode(' ', $data)), $data['name']);
        db::get()->commit();
        return $id;
    }
    
    public static function edit($id, array $data)
    {
        db::query()->update(self::TABLE)
                   ->column($data)
                   ->where('id', $id)
                   ->limit(1)
                   ->execute();
        
        unset($data['id'], $data['left'], $data['parent_id'], $data['right']);
        search::save('category', $id, strip_tags(implode(' ', $data)), $data['name']);
    }
    
    public static function delete($id)
    {
        db::get()->begin();
        
        $current = self::get($id);
        
        if (!$current || !$current['parent_id'])
        {
            return;
        }
        
        $product = array();
        $product_image = array();
        $category = array();
        $category_image = array();
        $all = db::query()->select('product p')
                          ->column('p.id', 'p.image')
                          ->join('category c', array('p.category_id', 'c.id'), 'inner')
                          ->where('>=', 'c.left', $current['left'])
                          ->where('<=', 'c.right', $current['right'])
                          ->execute();
        
        foreach ($all as $p)
        {
            $product[] = $p['id'];
            $product_image[] = $p['image'];
        }
        
        $all = db::query()->select(self::TABLE)
                          ->where('>=', 'left', $current['left'])
                          ->where('<=', 'right', $current['right'])
                          ->execute();
        
        foreach ($all as $c)
        {
            $category[] = $c['id'];
            $category_image[] = $c['image'];
        }
        
        if ($product)
        {
            db::query()->delete('product')
                       ->where('id', $product)
                       ->execute();
            
            db::query()->delete('search')
                       ->where('type', 'product')
                       ->where('type_id', $product)
                       ->execute();
        }
        
        db::query()->delete(self::TABLE)
                   ->where('id', $category)
                   ->execute();
        
        db::query()->delete('search')
                   ->where('type', 'category')
                   ->where('type_id', $category)
                   ->execute();
        
        db::query()->delete(self::TABLE . '_featured')
                   ->where('category_id', $category)
                   ->execute();
        
        db::query()->update(self::TABLE)
                   ->column('left', sql::raw('`left` - ' . (count($category) * 2)))
                   ->where('>', 'left', $current['left'])
                   ->execute();
        
        db::query()->update(self::TABLE)
                   ->column('right', sql::raw('`right` - ' . (count($category) * 2)))
                   ->where('>=', 'right', $current['right'])
                   ->execute();
        
        db::get()->commit();
        
        foreach ($product_image as $p)
        {
            if ($p)
            {
                product::delete_image($p);
            }
        }
        
        if ($product)
        {
            foreach (db::query()->select('product_image')->where('product_id', $product)->execute() as $i)
            {
                product::delete_image($i['image']);
            }
            
            db::query()->delete('product_image')
                       ->where('product_id', $product)
                       ->execute();
        }
        
        foreach ($category_image as $c)
        {
            if ($c)
            {
                self::delete_image($c);
            }
        }
    }
    
    public static function feature($id)
    {
        self::unfeature($id);
        db::query()->insert(self::TABLE . '_featured')
                   ->column(array('category_id' => $id))
                   ->execute();
    }
    
    public static function is_featured($id)
    {
        return (boolean) count(db::query()->select(self::TABLE . '_featured')
                                          ->where('category_id', $id)
                                          ->limit(1)
                                          ->execute());
    }
    
    public static function unfeature($id)
    {
        db::query()->delete(self::TABLE . '_featured')
                   ->where('category_id', $id)
                   ->execute();
    }
    
    public static function save_image($id, array $file)
    {
        if (!preg_match('~((jpe?g)|(gif)|(png))$~i', $file['name']))
        {
            return;
        }
        
        $temp = self::DIRECTORY . '__temp_' . pathinfo($file['name'], PATHINFO_BASENAME);
        $target['o'] = self::DIRECTORY . pathinfo($file['name'], PATHINFO_FILENAME) . '.jpg';
        $target['l'] = self::DIRECTORY . pathinfo($file['name'], PATHINFO_FILENAME) . '-l.jpg';
        $target['m'] = self::DIRECTORY . pathinfo($file['name'], PATHINFO_FILENAME) . '-m.jpg';
        $target['s'] = self::DIRECTORY . pathinfo($file['name'], PATHINFO_FILENAME) . '-s.jpg';
        
        if (is_file($temp) || is_file($target['o']) || is_file($target['l']) || is_file($target['m']) || is_file($target['s']))
        {
            throw new exception();
        }
        
        folder::move($file['tmp_name'], $temp);
        $image = new image($temp);
        $image->save($target['o'], 100);
        folder::mode($target['o'], 0775);
        
        if ($image->width > self::LARGE_WIDTH || $image->height > self::LARGE_HEIGHT)
        {
            $image->resize(self::LARGE_WIDTH, self::LARGE_HEIGHT);
        }
        
        $image->save($target['l'], 100);
        folder::mode($target['l'], 0775);
        
        if ($image->width > self::MEDIUM_WIDTH || $image->height > self::MEDIUM_HEIGHT)
        {
            $image->resize(self::MEDIUM_WIDTH, self::MEDIUM_HEIGHT);
        }
        
        $image->save($target['m'], 100);
        folder::mode($target['m'], 0775);
        
        if ($image->width > self::SMALL_WIDTH || $image->height > self::SMALL_HEIGHT)
        {
            $image->resize(self::SMALL_WIDTH, self::SMALL_HEIGHT);
        }
        
        $image->save($target['s'], 100);
        folder::mode($target['s'], 0775);
        $image->close();
        folder::delete($temp);
        
        if ($id)
        {
            $c = db::query()->select(self::TABLE)
                            ->where('id', $id)
                            ->limit(1)
                            ->execute()->fetch();
            
            if ($c && $c['image'])
            {
                self::delete_image($c['image']);
            }
            
            db::query()->update(self::TABLE)
                       ->column('image', pathinfo($file['name'], PATHINFO_FILENAME))
                       ->where('id', $id)
                       ->limit(1)
                       ->execute();
        }
    }
    
    public static function delete_image($image)
    {
        if (is_file(self::DIRECTORY . $image . '.jpg'))
        {
            folder::delete(self::DIRECTORY . $image . '.jpg');
            folder::delete(self::DIRECTORY . $image . '-l.jpg');
            folder::delete(self::DIRECTORY . $image . '-m.jpg');
            folder::delete(self::DIRECTORY . $image . '-s.jpg');
        }
    }
    
    public static function get_views($id = null)
    {
        $q = db::query()->select(self::TABLE)
                        ->column(sql::raw('SUM(views) as total'));
        
        if ($id !== null)
        {
            $q->where('id', $id);
        }
        
        $row = $q->execute()->fetch();
        return $row['total'];
    }
    
    public static function save_view($id)
    {
        db::query()->update(self::TABLE)
                   ->column('views', sql::raw('views + 1'))
                   ->where('id', $id)
                   ->execute();
    }
    
    ////////////////////////////////////////////////////////////////////////////
    // Internal functions.
}
