<?php
namespace Laraspace\Http\Controllers;

use Illuminate\Http\Request;
use Laraspace\User;
use Laraspace\Setting;
use Laraspace\Company;
use Laraspace\Address;
use Laraspace\Http\Requests\SettingRequest;
use Laraspace\Http\Requests\SettingKeyRequest;
use Laraspace\Http\Requests\ProfileRequest;
use Laraspace\Http\Requests\CompanyRequest;
use Laraspace\Http\Requests\CompanySettingRequest;
use Laraspace\Http\Requests\NotificationSettingsRequest;
use Laraspace\Space\CurrencyFormatter;
use Laraspace\Space\DateFormatter;
use Laraspace\Space\TimeZones;
use Laraspace\Currency;
use Laraspace\CompanySetting;

class CompanyController extends Controller
{
    public function getAdmin()
    {
        return User::find(1);
    }

    public function updateAdminProfile(ProfileRequest $request)
    {
        $verifyEmail = User::where('email', $request->email)->first();

        $user = auth()->user();

        if ($verifyEmail) {
            if ($verifyEmail->id !== $user->id) {
                return response()->json([
                    'error' => 'Email already in use'
                ]);
            }
        }

        $user->name = $request->name;
        $user->email = $request->email;

        if ($request->has('password')) {
            $user->password = bcrypt($request->password);
        }

        $user->save();

        return response()->json([
            'user' => $user,
            'success' => true
        ]);
    }

    public function getAdminCompany()
    {
        $user = User::with(['addresses', 'addresses.country', 'addresses.state', 'addresses.city', 'company'])->find(1);

        return response()->json([
            'user' => $user
        ]);
    }

    public function updateAdminCompany(CompanyRequest $request)
    {
        $user = User::find(1);
        $company = $user->company;
        $company->name = $request->name;
        $company->save();

        if ($request->has('logo')) {
            $company->clearMediaCollection('logo');
            $company->addMediaFromRequest('logo')->toMediaCollection('logo');
        }

        $fields = $request->only(['address_street_1', 'address_street_2', 'city_id', 'state_id', 'country_id', 'zip', 'phone']);
        $address = Address::updateOrCreate(['user_id' => 1], $fields);
        $user = User::with(['addresses', 'addresses.country', 'addresses.state', 'addresses.city', 'company'])->find(1);

        return response()->json([
            'user' => $user,
            'success' => true
        ]);
    }

    public function getGeneralSettings(Request $request)
    {
        $date_formats = DateFormatter::get_list();

        $time_zones = TimeZones::get_list();
        $fiscal_years = [
            ['key' => 'january-december' , 'value' => '1-12'],
            ['key' => 'february-january' , 'value' => '2-1'],
            ['key' => 'march-february'   , 'value' => '3-2'],
            ['key' => 'april-march'      , 'value' => '4-3'],
            ['key' => 'may-april'        , 'value' => '5-4'],
            ['key' => 'june-may'         , 'value' => '6-5'],
            ['key' => 'july-june'        , 'value' => '7-6'],
            ['key' => 'august-july'      , 'value' => '8-7'],
            ['key' => 'september-august' , 'value' => '9-8'],
            ['key' => 'october-september', 'value' => '10-9'],
            ['key' => 'november-october' , 'value' => '11-10'],
            ['key' => 'december-november', 'value' => '12-11'],
        ];

        $languages = [
            "en" => "English",
            "de" => "German",
            "fr" => "French",
            "es" => "Spanish"
        ];

        $language = CompanySetting::getSetting('language', $request->header('company'));
        $carbon_date_format = CompanySetting::getSetting('carbon_date_format', $request->header('company'));
        $moment_date_format = CompanySetting::getSetting('moment_date_format', $request->header('company'));
        $time_zone = CompanySetting::getSetting('time_zone', $request->header('company'));
        $currency = CompanySetting::getSetting('currency', $request->header('company'));
        $fiscal_year = CompanySetting::getSetting('fiscal_year', $request->header('company'));

        $languages = [
            ["code"=>"en", "name" => "English"],
            ["code"=>"de", "name" => "German"],
            ["code"=>"fr", "name" => "French"],
            ["code"=>"es", "name" => "Spanish"]
        ];

        return response()->json([
            'languages' => $languages,
            'date_formats' => $date_formats,
            'time_zones' => $time_zones,
            'time_zone' => $time_zone,
            'currencies' => Currency::all(),
            'fiscal_years' => $fiscal_years,
            'fiscal_year' => $fiscal_year,
            'selectedLanguage' => $language,
            'selectedCurrency' => $currency,
            'carbon_date_format' => $carbon_date_format,
            'moment_date_format' => $moment_date_format,
        ]);
    }

    public function updateGeneralSettings(CompanySettingRequest $request)
    {
        $sets = [
            'currency',
            'time_zone',
            'language',
            'carbon_date_format',
            'fiscal_year',
            'moment_date_format'
        ];

        foreach ($sets as $key) {
            CompanySetting::setSetting($key, $request->$key, $request->header('company'));
        }

        return response()->json([
            'success' => true
        ]);
    }

    public function updateSetting(SettingRequest $request)
    {
        CompanySetting::setSetting($request->key, $request->value, $request->header('company'));

        return response()->json([
            'success' => true
        ]);
    }

    public function getSetting(SettingKeyRequest $request)
    {
        $setting = CompanySetting::getSetting($request->key, $request->header('company'));

        return response()->json([
            $request->key => $setting
        ]);
    }

    public function getColors(Request $request)
    {
        $colors = [
            'invoice_primary_color',
            'invoice_column_heading',
            'invoice_field_label',
            'invoice_field_value',
            'invoice_body_text',
            'invoice_description_text',
            'invoice_border_color',
            'primary_text_color',
            'heading_text_color',
            'section_heading_text_color',
            'border_color',
            'body_text_color',
            'footer_text_color',
            'footer_total_color',
            'footer_bg_color',
            'date_text_color'
        ];

        $colorSettings = CompanySetting::whereIn('option', $colors)
            ->whereCompany($request->header('company'))
            ->get();

        return response()->json([
            'colorSettings' => $colorSettings
        ]);
    }

    /**
     * Upload the company logo to storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function uploadCompanyLogo(Request $request)
    {
        $data = json_decode($request->company_logo);

        if($data) {
            $company = Company::find($request->header('company'));

            if($company) {
                $company->clearMediaCollection('logo');

                $company->addMediaFromBase64($data->data)
                    ->usingFileName($data->name)
                    ->toMediaCollection('logo');
            }
        }

        return response()->json([
            'success' => true
        ]);
    }
}
