<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Carbon\Carbon;
use Storage;

use App\ProductDetail;
use App\Settings;
use App\Http\Services\Uploader; #custom class
class Manage extends Controller
{
    public function index()
    {
    	return view('manage.home');
    }

    public function settings()
    {
        return view('manage.settings');
    }

    public function settingStore(Request $request)
    {
        Settings::updateOrCreate(
            ['setting_name' => 'companyName'],
            ['setting_value' => $request->name]
        );
        if ($request->icon) {
            $db = Settings::where('setting_name','companyFavicon')->first();

            # Generate unique name
            $fv = explode('=',$db->setting_desc);
            $version = (int)$fv[1];
            $timestamp = str_replace([' ', ':', '-'], '', Carbon::now()->toDateTimeString());
            $x = explode('.',$request->icon->getClientOriginalName());
            $ext = array_last($x);
            $imageName = 'favicon'.$timestamp.'.'.$ext;

            # Save File
            $request->file('icon')->storeAs(
                'img/', $imageName
            );

            # Delete old icon
            $url = 'img/'.$db->setting_value;
            Storage::delete($url);
            
            # Save DB
            $db->setting_value = $imageName;
            $db->setting_desc = 'v='.($version+1);
            $db->save();
        }

        if ($request->logo) {
            $imageName = Uploader::SaveImage($request->logo, 'manage-logo-', 'img/');
            $setting = Settings::where('setting_name','manageLogo')->first();
            $setting->setting_value = $imageName;
            $setting->save();
        }

        if ($request->language) {
            $request->session()->put('app-locale', $request->language);
            app()->setLocale($request->language);
            $previous_url = url()->previous();
            $previous_request = app('request')->create($previous_url);
            $segments = $previous_request->segments();

            $url = url('/').'/'.$request->language;
            
            for ($i=1; $i < count($segments); $i++) {
                $url = $url.'/'.$segments[$i];
            }
            return redirect($url);

        } else {
            return redirect(route('manage.settings'));
        }
    }

    # Handle product image upload
    public function upload(Request $request)
    {
    	$this->validate($request, [
    		'code' => 'required',
    		'image' => 'required'
    	]);
	
	    # If new image uploaded
    	if($request->image) {  
		    # Save uploaded image
		    $imageName = Uploader::SaveImage($request->image, 'product_', 'img/products/'.$request->code.'/');
	    }

	    $db = new ProductDetail;
	    $db->detail_code = $request->code;
	    $db->detail_image = $imageName;
	    $db->save();

	    $newitem = '
			<div class="col-lg-4 thumbnail-card">
              <div class="card">
                <img src="'.asset(config('customvar.storage_url').'img/products/'.$db->detail_code.'/'.$db->detail_image).'" class="img-responsive">  
                <a href="'.route('manage.product.delete-image', $db->id).'" class="btn-rounded ajax-delete">
                  <i class="fa fa-trash"></i>
                </a>
              </div>
            </div>
	    ';

	    return response()->json(['message' => 'Uploaded', 'newItem' => $newitem]);
    }
}
