<?php

namespace Wave\Http\Controllers\CMS;

use App\Http\Controllers\Controller;
use App\Mail\SendUserInvite;
use App\Models\Company;
use App\Models\InviteUser;
use App\Models\User;
use App\Models\UserAccessLog;
use App\Models\Role;
use App\Models\CompanySubscription;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;

class CompanyController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        return view('theme::cms.companies.index');
    }

    public function table(Request $request)
    {
        $companies = Company::query()
            ->select(
                'companies.id',
                'companies.name_english',
                'companies.name_chinese',
            )
            ->when($request->company_name, function ($query) use ($request) {
                $query->where(function($query2) use ($request){
                    $query2->orWhere('companies.name_english', 'like', '%' . $request->company_name . '%');
                    $query2->orWhere('companies.name_chinese', 'like', '%' . $request->company_name . '%');
                });
            });

        return Datatables::of($companies)
            ->escapeColumns(['id'])
            ->addColumn('bookkeeping_subscription', function ($company) { // Temporary
                return '
                    <span class="success item-list-note d-block">Active</span>
                    <span class="item-list-note d-block">' . __("Expiration") . ': 2024/05/16</span>
                ';
            })
            ->addColumn('bookkeeping_requests_count', function ($company) { // Temporary
                return '0';
            })
            ->addColumn('com_sec_subscription', function ($company) { // Temporary
                return '
                    <span class="failed item-list-note d-block">Expired</span>
                    <span class="item-list-note d-block">' . __("Expiration") . ': 2023/04/16</span>
                ';
            })
            ->addColumn('com_sec_requests_count', function ($company) { // Temporary
                return '0';
            })
            ->addColumn('actions', function ($company) {
                $viewAction = '<a href="' . route('cms.companies.show', $company->id) . '" class="primary-text">' . __("View") . '</a>';
                $editAction = '<a href="' . route('cms.companies.show', $company->id) . '" class="primary-text">' . __("Edit") . '</a>';
                $actions = $viewAction . '<span class="long-pipe">|</span>' . $editAction;
                return $actions;
            })
            ->make(true);
    }

    public function show(Company $company)
    {
        $roles = Role::whereIn('id', [
            Role::OWNER_ROLE,
            Role::ADMINISTRATOR_ROLE,
            Role::BOOKKEEPER_ROLE,
            Role::COMPANY_SECRETARY_ROLE,
        ])->get();

        $company_subscription = CompanySubscription::with('subscription')->where('company_id', $company->id)->get();

        return view('theme::cms.companies.show')->with([
            'company' => $company,
            'roles' => $roles,
            'company_subscription' => $company_subscription,
        ]);
    }

    public function usersTable(Company $company)
    {
        $users = User::query()
            ->select(
                'users.id',
                'users.first_name',
                'users.last_name',
                'users.phone',
                'users.email',
                'roles.display_name',
                'users.status',
            )
            ->leftJoin('roles', 'users.role_id', '=', 'roles.id')
            ->where('users.company_id', $company->id);

        return Datatables::of($users)
            ->escapeColumns(['id'])
            ->addColumn('status', function ($user) {
                $status = $user->status;
                if ($status == 'active') {
                    $status = '<span class="success item-list-note">' . ucwords($status) . '</span>';
                }
                else if ($status == 'inactive') {
                    $status = '<span class="failed item-list-note">' . ucwords($status) . '</span>';
                }

                return $status;
            })
            ->addColumn('actions', function ($user) {
                $suspendAction = '<a class="dropdown-item suspend-user" href="#" data-action="' . route('cms.users.suspend', $user->id) . '">' . __("Suspend user") . '</a>';
                $activateAction = '<a class="dropdown-item activate-user" href="#" data-action="' . route('cms.users.activate', $user->id) . '">' . __("Activate user") . '</a>';
                $removeAction = '<a class="dropdown-item remove-user" href="#" data-action="' . route('cms.users.destroy', $user->id) . '">' . __("Remove user") . '</a>';
                $viewUserLogAction = '<a class="dropdown-item view-user-log" data-action="' . route("cms.users.accessLogsTable", $user->id) . '" href="#">' . __("View user log") . '</a>';
                $editUserAction = '<a class="dropdown-item edit-user" href="#" data-action-show="' . route('cms.users.show', $user->id) . '" data-action-update="' . route('cms.users.update', $user->id) . '">' . __("Edit user") . '</a>';
                $actions = '
                    <div class="dropdown non-custom">
                        <button type="button" data-bs-toggle="dropdown" aria-expanded="false"><img class="max-25" src="' . asset('themes/tailwind/images/more.svg') . '"></button>
                        <div class="dropdown-menu">
                            ' . ($user->status == 'active' ? $suspendAction : $activateAction) . '
                            ' . $removeAction . '
                            ' . $viewUserLogAction . '
                            ' . $editUserAction . '
                        </div>
                    </div>
                ';
                return $actions;
            })
            ->make(true);
    }

    public function accessLogsTable(Company $company)
    {
        $logs = UserAccessLog::query()
            ->select(
                'users.email',
                'user_access_logs.created_at',
                'user_access_logs.event',
                'user_access_logs.description',
                'user_access_logs.status',
            )
            ->leftJoin('users', 'user_access_logs.user_id', '=', 'users.id')
            ->where('users.company_id', $company->id);
        return Datatables::of($logs)
            ->escapeColumns(['id'])
            ->addColumn('date', function ($log) {
                return date('Ymd', strtotime($log->created_at));
            })
            ->addColumn('time', function ($log) {
                return date('H:i', strtotime($log->created_at));
            })
            ->addColumn('status', function ($log) {
                return '<span class="' . $log->status . ' item-list-note">' . ucwords($log->status) . '</span>';
            })
            ->make(true);
    }

    public function updateXeroApi(Company $company, Request $request)
    {
        $validator = Validator::make($request->all(), [
            'xero_api_key' => 'required|string|max:255',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 422);
        }
        else {
            $company->update([
                'xero_api_key' => $request->xero_api_key,
            ]);
    
            return response()->json([
                'success' => true,
                'message' => __("All changes have been saved!"),
            ]);
        }
    }

    public function sendUserInvite(Company $company, Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|string|email|max:255|unique:users',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 422);
        }
        else {
            $token = '';
            while (true) {
                $token = str()->random(20);
                $tokenExists = InviteUser::where('token', $token)->first();
                if (!$tokenExists) {
                    break;
                }
            }
            InviteUser::create([
                'email' => $request->email,
                'token' => $token,
                'user_id' => $request->user()->id,
                'company_id' => $company->id,
                'is_used' => false,
            ]);
            $url = route('register', ['token' => $token]);
            Mail::to($request->email)->send(new SendUserInvite($url, $company->name));
    
            return response()->json([
                'success' => true,
                'message' => __("Invitation sent!"),
            ]);
        }
    }
}
