<?php
/**
 * Created by PhpStorm.
 * User: foda
 * Date: 1/18/2019
 * Time: 6:33 PM
 */

namespace App;

use Illuminate\Database\Eloquent\Model;

class mainCategory extends model
{
    protected $table = 'main_category';

    public static function getAllMainCategories()
    {
        return \DB::table('main_category')
            ->select([
                'id',
                'name',
                \DB::raw('CONCAT("http://'.$_SERVER["SERVER_NAME"].'/",image) AS image'),
                'created_at'
            ])
            ->get();
    }

    public static function addCategory($category,$attachment)
    {
        return \DB::table('main_category')
            ->insert(['name' => $category
                , 'image' => env('mainCategoryImagePath').$attachment]);
    }

    public static function updateCategory($categoryId,$name,$attachment)
    {
        $category = self::whereId($categoryId)->first();

        if((basename($category->image) != basename($attachment))) {

            if (Util::deleteFile($category->image)) {
                return \DB::table('main_category')
                    ->where('id', '=', $categoryId)
                    ->update(['name' => $name
                        , 'image' => env('mainCategoryImagePath') . basename($attachment)]);
            } else {
                return false;
            }
        } else {
            return \DB::table('main_category')
                ->where('id', '=', $categoryId)
                ->update(['name' => $name
                    , 'image' => env('mainCategoryImagePath') . basename($attachment)]);
        }
    }

    public static function deleteMainCategory($mainCategoryId)
    {
        $category = self::whereId($mainCategoryId)->first();
        if (Util::deleteFile($category->image)) {
            return \DB::table('main_category')
                ->where('id', '=', $mainCategoryId)
                ->delete();
        } else {
            return false;
        }
    }

    //<editor-fold defaultstate="collapsed" desc="table structure">

    public static function whereId($id)
    {
        return \DB::table('main_category')
            ->select([
                '*'
            ])
            ->where('id', '=', $id);
    }

    public static function whereName($category)
    {
        return \DB::table('main_category')
            ->select([
                '*'
            ])
            ->where('name', '=', $category);
    }

    //</editor-fold>
}