<?php
class product
{
    const TABLE = 'product';
    const DIRECTORY = 'extend/content/product/';
    
    ////////////////////////////////////////////////////////////////////////////
    // Construct and destruct functions.
    
    ////////////////////////////////////////////////////////////////////////////
    // Overload functions.

    ////////////////////////////////////////////////////////////////////////////
    // Interface functions.
    
    public static function get($id)
    {
        return db::query()->select(self::TABLE)
                          ->where('id', $id)
                          ->execute()->fetch();
    }
    
    public static function get_by_path($category_id, $path)
    {
        return db::query()->select(self::TABLE)
                          ->where('category_id', $category_id)
                          ->where('path', $path)
                          ->limit(1)
                          ->execute()->fetch();
    }
    
    public static function get_list($category_id)
    {
        return db::query()->select(self::TABLE . ' p')
                          ->column('p.*')
                          ->where('p.category_id', $category_id)
                          ->join('meta m', array('AND', array('=', 'p.id', (object) array('type' => 'identifier', 'value' => 'm.type_id')), array('=', 'm.type', 'product')), 'left')
                          ->column('m.title meta')
                          ->execute();
    }
    
    public static function get_featured($limit = null)
    {
        $q = db::query()->select(self::TABLE . ' p')
                        ->column('p.*')
                        ->join(self::TABLE . '_featured pf', array('p.id', 'pf.product_id'), 'inner')
                        ->order('pf.id', 'desc');
        
        if ($limit !== null)
        {
            $q->limit($limit);
        }
        
        return $q->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_image($id)
    {
        $product = self::get($id);
        
        if (!$product) {
            throw new Exception('Product does not exist.');
        }
        
        if ($product['image']) {
            $image = self::DIRECTORY . $product['path'] . '/' . $product['image'];
            
            if (is_file($image)) {
                return $product['image'];
            }
        }
        
        $path = self::DIRECTORY . $product['path'] . '/';
        
        if (is_dir($path)) {
            $files = new DirectoryIterator($path);
            
            foreach ($files as $file) {
                if (!$file->isDot() && !$file->isDir()) {
                    return $file->getFilename();
                }
            }
        }
    }
    
    public static function get_image_list($id)
    {
        $product = self::get($id);
        
        if (!$product) {
            throw new Exception('Product does not exist.');
        }
        
        $images = array();
        $path = self::DIRECTORY . $product['path'] . '/';
        
        if (is_dir($path)) {
            $files = new DirectoryIterator($path);
            
            foreach ($files as $file) {
                if (!$file->isDot() && !$file->isDir()) {
                    $images[] = $file->getFilename();
                }
            }
        }
        
        return $images;
    }
    
    public static function get_image_url($id, $filename, $width, $height)
    {
        $product = self::get($id);
        
        if (!$product) {
            throw new Exception('Product does not exist.');
        }
        
        $directory = self::DIRECTORY . $product['path'] . '/thumbnail/';
        
        if (!is_dir($directory)) {
            folder::create($directory);
            folder::mode($directory, 0755);
        }
        
        $file = self::DIRECTORY . $product['path'] . '/' . $filename;
        
        if (!$file) {
            throw new Exception('Product image does not exist.');
        }
        
        $url = self::DIRECTORY . $product['path'] . '/thumbnail/' . $width . '-' . $height . '-' . $filename;
        
        if (!is_file($url)) {
            $image = new image($file);
            $image->resize($width, $height);
            $image->save($url);
            folder::mode($url, 0755);
        }
        
        return $url;
    }
    
    public static function add(array $data)
    {
        db::query()->insert(self::TABLE)
                   ->column($data)
                   ->execute();
        
        $id = db::get()->get_last_id();
        folder::create(self::DIRECTORY . $data['path']);
        folder::mode(self::DIRECTORY . $data['path'], 0755);
        $files = new DirectoryIterator(self::DIRECTORY . 'product/');
        
        foreach ($files as $file) {
            if (!$file->isDot() && !$file->isDir()) {
                folder::move(self::DIRECTORY . 'product/' . $file->getFilename(), self::DIRECTORY . $data['path'] . '/' . $file->getFilename());
                folder::mode(self::DIRECTORY . $data['path'] . '/' . $file->getFilename(), 0755);
            }
        }
        
        unset($data['id']);
        search::save('product', $id, strip_tags(implode(' ', $data)), $data['name']);
        return $id;
    }
    
    public static function edit($id, array $data)
    {
        $product = self::get($id);
        
        if ($product) {
            db::query()->update(self::TABLE)
                       ->column($data)
                       ->where('id', $id)
                       ->limit(1)
                       ->execute();
            
            $current_path = self::DIRECTORY . $product['path'] . '/';
            $new_path = self::DIRECTORY . $data['path'] . '/';
            
            if (!is_dir($current_path)) {
                folder::create($current_path);
                folder::mode($current_path, 0755);
            }
            
            if ($product['path'] !== $data['path']) {
                folder::move($current_path, $new_path);
                $files = new DirectoryIterator($new_path);
                
                foreach ($files as $file) {
                    if (!$file->isDot()) {
                        folder::mode($new_path . $file->getFilename(), 0755);
                    }
                }
            }
            
            unset($data['id']);
            search::save('product', $id, strip_tags(implode(' ', $data)), $data['name']);
        }
    }
    
    public static function delete($id)
    {
        $product = self::get($id);
        
        if ($product) {
            db::query()->delete(self::TABLE)
                       ->where('id', $id)
                       ->limit(1)
                       ->execute();
            
            folder::delete(self::DIRECTORY . $product['path']);
            search::delete('product', $id);
        }
    }
    
    public static function feature($id)
    {
        self::unfeature($id);
        db::query()->insert(self::TABLE . '_featured')
                   ->column(array('product_id' => $id))
                   ->execute();
    }
    
    public static function is_featured($id)
    {
        return (boolean) count(db::query()->select(self::TABLE . '_featured')
                                          ->where('product_id', $id)
                                          ->limit(1)
                                          ->execute());
    }
    
    public static function unfeature($id)
    {
        db::query()->delete(self::TABLE . '_featured')
                   ->where('product_id', $id)
                   ->execute();
    }
    
    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.
}
