<?php

namespace App\Http\Controllers;

use App\Media as mMedia;
use App\MediaLocale as mMediaLocale;
use App\General as mGeneral;
use App\GeneralLocale as mGeneralLocale;
use App\Category as mCategory;
use App\CategoryLocale as mCategoryLocale;
use App\Product as mProduct;
use App\ProductLocale as mProductLocale;
use App\ProductDetail as mProductDetail;
use App\Settings;
use App\Currency;
use Storage;
use Image;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Services\Uploader; #custom class

class BackendProduct extends Controller
{
  public function __construct()
  {
      $this->middleware('auth');
  }

  function index(Request $req){
    $data['categories'] = mCategory::orderBy('sort', 'asc')->get();
    $data['currencies'] = Currency::whereIn('currency_code',['IDR','EUR','USD'])->get();
    $data['icon'] = Settings::where('setting_name','all_category_icon')->first();
    $data['page'] = 'category-manager';
    return view('backend.product')->with($data);
  }

  function save_category(Request $req){
    $category_name = $req->category_name;
    $category_alt = $req->category_alt;

    $this->validate($req, [
      'image1' => 'required',
      'image2' => 'required',
      'category_name' => 'required',
    ]);

    # Make new database model
    $db = new mCategory;

    # If new image uploaded
    if($req->image1) {

      # Save uploaded image
      $imageName1 = Uploader::SaveImage($req->image1, 'category_img1_', 'img/products/category/', $category_alt[app()->getLocale()]);

      # Delete old image if new one uploaded
      if($db->category_image1!=''){
        Storage::delete('/img/products/category/'.$db->category_image1);
      }
    }

    if($req->image2) {

      # Save uploaded image
      $imageName2 = Uploader::SaveImage($req->image2, 'category_img2_', 'img/products/category/', $category_alt[app()->getLocale()]);

      # Delete old image if new one uploaded
      if($db->category_image2!=''){
        Storage::delete('/img/products/category/'.$db->category_image2);
      }
    }

    # Insert rquired data
    $db->category_name = $category_name[config('app.locale')];
    $db->category_alt = $category_alt[config('app.locale')];
    $db->category_image1 = $imageName1;
    $db->category_image2 = $imageName2;

    # Save model into database
    $db->save();

    # Saving translation
    foreach (config('translatable.locales') as $lang => $language) {

      # Check if translation is available
      $data = $db->locales()->where('locale',$lang)->first();
      if(empty($data)){
        # Create new translation model
        $translation = new mCategoryLocale;
        $translation->category_id = $db->id;
        $translation->locale = $lang;
      }else{
        # Update existing translation model
        $translation = mCategoryLocale::find($data->id);
      }

      # Insert translation data
      $translation->category_name = $category_name[$lang];
      $translation->category_alt = $category_alt[$lang];
      # Save changes
      $translation->save();
    }

    $req->session()->flash('message-category', 'Added successfully!');
    $req->session()->flash('alert-class', 'alert-success');
		$req->session()->flash('anchor', '#message-category');

    return back();
  }

  function update_category(Request $req){
    $id = $req->id;
    $category_name = $req->category_name;
    $category_alt = $req->category_alt;

    # Make new database model
    $db = mCategory::find($req->id);

    # Get the old image name in case no image uploaded
    $imageName1 = $db->category_image1;
    $imageName2 = $db->category_image2;

    # If new image uploaded
    if($req->image1) {

      # Save uploaded image
      $imageName1 = Uploader::SaveImage($req->image1, 'category_img1_', 'img/products/category/', $category_alt[app()->getLocale()]);

      # Delete old image if new one uploaded
      if($db->category_image1!=''){
        Storage::delete('/img/products/category/'.$db->category_image1);
      }
    }

    if($req->image2) {

      # Save uploaded image
      $imageName2 = Uploader::SaveImage($req->image2, 'category_img2_', 'img/products/category/', $category_alt[app()->getLocale()]);

      # Delete old image if new one uploaded
      if($db->category_image2!=''){
        Storage::delete('/img/products/category/'.$db->category_image2);
      }
    }

    # Insert rquired data
    $db->category_name = $category_name[config('app.locale')];
    $db->category_alt = $category_alt[config('app.locale')];
    $db->category_image1 = $imageName1;
    $db->category_image2 = $imageName2;

    # Save model into database
    $db->save();

    # Saving translation
    foreach (config('translatable.locales') as $lang => $language) {

      # Check if translation is available
      $data = $db->locales()->where('locale',$lang)->first();
      if(empty($data)){
        # Create new translation model
        $translation = new mCategoryLocale;
        $translation->category_id = $db->id;
        $translation->locale = $lang;
      }else{
        # Update existing translation model
        $translation = mCategoryLocale::find($data->id);
      }

      # Insert translation data
      $translation->category_name = $category_name[$lang];
      $translation->category_alt = $category_alt[$lang];
      # Save changes
      $translation->save();
    }

    $req->session()->flash('message-category', 'Updated successfully!');
    $req->session()->flash('alert-class', 'alert-success');
		$req->session()->flash('anchor', '#message-category');

    return back();
  }

  function delete_category(Request $req){

    # Find model
    $db = mCategory::find($req->id);
    # Delete Category images
    if ($db->category_image1) {
      Storage::delete('/img/products/category/'.$db->category_image1);
    }
    if ($db->category_image2) {
      Storage::delete('/img/products/category/'.$db->category_image2);
    }

    # Find product
    $products = mProduct::where(['product_category'=>$req->id])->get();

    # Delete directory
    foreach ($products as $key => $val) {
      if ($val->product_code) {
        Storage::deleteDirectory('/img/products/'.$val->product_code);
      }
    }

    # Delete translation
    foreach(config('translatable.locales') as $lang => $language){
      $get = $db->locales()->where('locale',$lang)->first();
      if (!empty($get)) {
        $get->delete();
      }
    }

    # Delete model
    $db->delete();

    return back();
  }

  function view_on_category($id){
    $category = mCategory::find($id)
                        ->locales()
                        ->where('locale',config('app.locale'))
                        ->first();
    if(empty($category)){
      $data['category'] = mCategory::find($id)->category_name;
    }else{
      $data['category'] = $category->category_name;
    }
    $data['category_id'] = $id;
    $data['products'] = mProduct::where(['product_category'=>$id])->orderBy('sort', 'asc')->get();
    $data['page'] = str_slug($data['category']);
    return view('backend.product_on_category')->with($data);
  }

  function save_product(Request $req){
    $name = $req->product_name;
    $alt = $req->product_alt;
    $category = $req->product_category;
    $currency = $req->product_currency;
    $price = $req->product_price;
    $content = $req->product_content;
    $stock = $req->product_stock;

    $this->validate($req, [
      'image' => 'required',
      'product_name' => 'required',
      'product_content' => 'required'
    ]);

    $random = str_random(5);
    # Get total record
    $sort = mProduct::all()->count();
    # Make new database model
    $db = new mProduct;

    # If new image uploaded
    if($req->image) {

      # Save uploaded image
      $imageName = Uploader::SaveImage($req->image, 'product_', 'img/products/'.$random.'/', $alt[app()->getLocale()]);
      $imageDetail = Uploader::SaveImageWithThumb($req->image, 'product_', 'img/products/'.$random.'/', $alt[app()->getLocale()]);

      # Delete old image if new one uploaded
      if($db->product_image!=''){
        Storage::delete('/img/products/'.$db->product_image);
      }
    }

    # Insert required data
    $db->product_weight = $req->product_weight;
    $db->product_code = $random;
    $db->product_currency = $currency;
    $db->product_price = $price;
    $db->product_image = $imageName;
    $db->product_category = $category;
    $db->production_time = $req->production_time;
    $db->product_stock = $req->product_stock;
    $db->sort = $sort+1;
    # Save model into database
    $db->save();

    # Saving translation
    foreach (config('translatable.locales') as $lang => $language) {

      # Check if translation is available
      $data = $db->locales()->where('locale',$lang)->first();
      if(empty($data)){
        # Create new translation model
        $translation = new mProductLocale;
        $translation->product_id = $db->id;
        $translation->locale = $lang;
      }else{
        # Update existing translation model
        $translation = mProductLocale::find($data->id);
      }

      # Insert translation data
      $translation->product_name = $name[$lang];
      $translation->product_alt = $alt[$lang];
      $translation->product_content = $content[$lang];
      # Save changes
      $translation->save();
    }


    $db = new mProductDetail;
    $db->detail_code = $random;
    $db->detail_image = $imageDetail['thumb'];
    $db->detail_image_big = $imageDetail['original'];
    $db->save();

    $req->session()->flash('message-product', 'Added successfully!');
    $req->session()->flash('alert-class', 'alert-success');
		$req->session()->flash('anchor', '#message-product');

    return back();
  }

  function order_product(Request $req){
    $order = $req->reorder;

    foreach($order as $key => $val){
      $db = mProduct::find($val);
      $db->sort = $key+1;
      $db->save();
    }

    $req->session()->flash('message-content', 'Content rearranged!');
    $req->session()->flash('alert-class', 'alert-success');
    $req->session()->flash('anchor', '#message-content');

    return back();
  }

  function delete_product(Request $req){
    # Find model
    $db = mProduct::find($req->id);

    # Delete directory
    Storage::deleteDirectory('/img/products/'.$db->product_code);

    # Delete translations
    foreach (config('translatable.locales') as $lang => $language) {
      $get = $db->locales()->where('locale',$lang)->first();
      if($get){
        mProductLocale::find($get->id)->delete();
      }
    }

    # Delete detail
    mProductDetail::where('detail_code',$db->product_code)->delete();

    # Delete model
    $db->delete();

    return back();
  }

  function detail_product($id_category, $code){
    $product = mProduct::where(['product_code'=>$code])->first();
    $data['product'] = $product;
    $data['product_detail'] = mProductDetail::where(['detail_code'=>$code])->get();
    $page = mProduct::find($product->id)->locales()->where('locale',config('app.locale'))->first();
    if(empty($page)){
      $data['page'] = $product->product_name;
    }else{
      $data['page'] = $page->product_name;
    }
    return view('backend.product_detail')->with($data);
  }

  function save_detail_image(Request $req){
    $code = $req->code;
    $product = mProduct::where('product_code', $code)->firstOrFail();

    $this->validate($req, [
      'image' => 'required',
    ]);

    # If new image uploaded
    if($req->image) {

      # Save uploaded image
      $imageName = Uploader::SaveImageWithThumb($req->image, 'product_', 'img/products/'.$code.'/', ($product->product_alt ? $product->product_alt : ''));

    }

    # Make new model
    $db = new mProductDetail;
    $db->detail_code = $code;
    $db->detail_image = $imageName['thumb'];
    $db->detail_image_big = $imageName['original'];
    $db->save();

    if(mProductDetail::where('detail_code', $code)->count() == 1){
      $product_id = mProduct::where(['product_code'=>$code])->first()->id;
      $db = mProduct::find($product_id);
      $db->product_image = $imageName;
      $db->save();
    }

    $req->session()->flash('message-image', 'Added successfully!');
    $req->session()->flash('alert-class', 'alert-success');
		$req->session()->flash('anchor', '#message-image');

    return back();
  }

  function delete_detail_image(Request $req){
    $id = $req->id;

    $q = mProductDetail::where('id',$id)->first();
    $code = $q->detail_code;
    $name = $q->detail_image;
    $url = '/img/products/'.$code.'/'.$name;

    Storage::delete($url);

    mProductDetail::where('id',$id)->delete();

    return back();
  }

  function set_primary_detail_image(Request $req){
    $id = $req->id;
    $code = $req->code;

    $name = mProductDetail::where(['id'=>$id])->first()->detail_image;
    $product_id = mProduct::where(['product_code'=>$code])->first()->id;

    $db = mProduct::find($product_id);
    $db->product_image = $name;
    $db->save();

    return back();
  }

  function update_product($id, Request $req){
    $name = $req->product_name;
    $alt = $req->product_alt;
    $price = $req->product_price;
    $content = $req->product_content;

    $db = mProduct::find($id);
    $db->product_price = $price;
    $db->product_weight = $req->product_weight;
    $db->production_time = $req->production_time;
    $db->product_stock = $req->product_stock;
    $db->save();

    foreach (config('translatable.locales') as $lang => $language) {
      $get = mProduct::find($id)->locales()->where('locale',$lang)->first();
      if(empty($get)){
        #create
        $db = new mProductLocale;
        $db->locale = $lang;
        $db->product_id = $id;
        $db->product_name = $name[$lang];
        $db->product_content = $content[$lang];
        $db->save();
      }else{
        #update
        $db = mProductLocale::find($get->id);
        $db->product_name = $name[$lang];
        $db->product_alt = $alt[$lang];
        $db->product_content = $content[$lang];
        $db->save();
      }
    }

    $req->session()->flash('message-detail', 'Updated successfully!');
    $req->session()->flash('alert-class', 'alert-success');
		$req->session()->flash('anchor', '#message-detail');

    return back();
  }

  function get_detail_image(Request $req){
    $data['detail'] = mProductDetail::find($req->id);
    return view('backend.product_detail_update')->with($data);
  }

  function update_detail_image(Request $req, $id){
    $is_primary = $req->is_primary;
    # Find the model
    $db = mProductDetail::find($id);
    $product = mProduct::where('product_code', $db->detail_code)->firstOrFail();
    $code = $db->detail_code;

    $this->validate($req, [
      'image' => 'required',
    ]);

    # If new image uploaded
    if($req->image) {

      # Save uploaded image
      $imageName = Uploader::SaveImage($req->image, 'product_', 'img/products/'.$code.'/', ($product->product_alt ? $product->product_alt : ''));

      # Delete old image
      if($db->detail_image!='' && $db->detail_code!=''){
        Storage::delete('/img/products/'.$code.'/'.$db->detail_image);
      }

    }

    # Update data and save
    $db->detail_image = $imageName;
    $db->save();

    if($is_primary == "yes"){
      $product_id = mProduct::where(['product_code'=>$code])->first()->id;
      $db = mProduct::find($product_id);
      $db->product_image = $imageName;
      $db->save();
    }

    $req->session()->flash('message-image', 'Updated successfully!');
    $req->session()->flash('alert-class', 'alert-success');
		$req->session()->flash('anchor', '#message-image');

    return back();
  }

  function save_icon(Request $req){
    $icon = Settings::where('setting_name','all_category_icon')->first();
    $this->validate($req, [
      'image' => 'required',
    ]);

    if(empty($icon)) { # Make new model if $id is empty

      $this->validate($req, [
          'image' => 'required',
      ]);

      # Make new database model
      $db = new Settings;

    } else {

      # Update existing record
      $db = Settings::find($icon->id);

    }

    # Get the old image name incase no image uploaded
    $imageName = $db->setting_value;

    # If new image uploaded
    if($req->image) {

      # Save new image
      $imageName = Uploader::SaveImage($req->image, 'allcategory_', 'img/products/category/');

      # Delete old image if new one uploaded
      if($db->setting_value!=''){
        Storage::delete('/img/products/category/'.$db->setting_value);
      }
    }

    # Insert rquired data
    $db->setting_name = 'all_category_icon';
    $db->setting_value = $imageName;
    $db->setting_desc = "All category icon";

    # Save model into database
    $db->save();

    $req->session()->flash('message-icon', 'Updated successfully!');
    $req->session()->flash('alert-class', 'alert-success');
		$req->session()->flash('anchor', '#message-icon');

    return back();
  }

  function featured($id)
  {
    $product = mProduct::findOrFail($id);
    if($product->is_featured) {
      $product->is_featured = false;
    } else {
      $product->is_featured = true;
    }
    $product->save();
    return back();
  }

  public function orderCategory(Request $request)
  {
    foreach($request->list as $i => $id) {
      mCategory::find($id)->update(['sort' => $i]);
    }
    
    $request->session()->flash('message-content', 'Content rearranged!');
    $request->session()->flash('alert-class', 'alert-success');
    $request->session()->flash('anchor', '#message-content');

    return back();
  }
}
