<?php

namespace Wave\Http\Controllers\CMS;

use App\Http\Controllers\Controller;
use App\Models\Subscription;
use App\Models\SubscriptionBasicService;
use App\Models\SubscriptionBasicServiceList;
use App\Models\SubscriptionOptionalService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Yajra\DataTables\Facades\DataTables;

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

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

    public function table($service_type)
    {
        $subscriptions = Subscription::where('service_type', $service_type);

        return Datatables::of($subscriptions)
            ->escapeColumns(['id'])
            ->addColumn('price', function ($subscription) {
                $price = '$' . number_format($subscription->price);

                return $price;
            })
            ->addColumn('period_english', function ($subscription) {
                return ucfirst($subscription->period_english);
            })
            ->addColumn('status', function ($subscription) {
                $status = $subscription->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 ($subscription) {
                if (auth()->user()->userRole->hasAccess('manage-subscription-packages')) {
                    $suspendAction = '<a class="failed item-list-note suspend-subscription" href="#" data-action="' . route('cms.subscriptions.management.suspend', $subscription->id) . '">' . __("Suspend") . '</a>';
                    $activateAction = '<a class="primary-text activate-subscription" href="#" data-action="' . route('cms.subscriptions.management.activate', $subscription->id) . '">' . __("Activate") . '</a>';
                    $viewAction = '<a href="' . route('cms.subscriptions.management.edit', $subscription->id) . '" class="primary-text">' . __("View") . '</a>';
                    $editAction = '<a href="' . route('cms.subscriptions.management.edit', $subscription->id) . '" class="primary-text">' . __("Edit") . '</a>';
                    $actions = $viewAction . '<span class="long-pipe">|</span>' . $editAction . '<span class="long-pipe">|</span>' . ($subscription->status == 'active' ? $suspendAction : $activateAction);
                    return $actions;
                }
                return '';
            })
            ->make(true);
    }

    public function suspend(Subscription $subscription)
    {
        $subscription->status = 'inactive';
        $subscription->save();

        return response()->json([
            'success' => true,
            'message' => __("Subscription has successfully suspended!"),
        ]);
    }

    public function activate(Subscription $subscription)
    {
        $subscription->status = 'active';
        $subscription->save();

        return response()->json([
            'success' => true,
            'message' => __("Subscription has successfully activated!"),
        ]);
    }

    public function create($serviceType)
    {
        return view('theme::cms.subscriptions.management.create', [
            'service_type' => $serviceType,
        ]);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'service_type' => 'required|string',
            'status' => 'required|in:active,inactive',
            'name_english' => 'required|string',
            'name_chinese' => 'required|string',
            'period_english' => 'required|in:annually,monthly,daily',
            'period_chinese' => 'required|in:每年,每月,每日',
            'description_english' => 'required|string',
            'description_chinese' => 'required|string',
            'price' => 'required|numeric',
            'basic_service_title_english' => 'required|array',
            'basic_service_title_chinese' => 'required|array',
            'basic_service_list_title_english' => 'required|array',
            'basic_service_list_title_chinese' => 'required|array',
            'optional_service_title_english' => 'required|array',
            'optional_service_title_chinese' => 'required|array',
            'optional_service_is_custom' => 'required|array',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 422);
        }
        else {
            $subscription = Subscription::create([
                'service_type' => $request->service_type,
                'name_english' => $request->name_english,
                'name_chinese' => $request->name_chinese,
                'period_english' => $request->period_english,
                'period_chinese' => $request->period_chinese,
                'description_english' => $request->description_english,
                'description_chinese' => $request->description_chinese,
                'price' => $request->price,
                'status' => $request->status,
            ]);
            foreach ($request->basic_service_title_english as $key => $basic_service_title_english) {
                $subscriptionBasicService = SubscriptionBasicService::create([
                    'subscription_id' => $subscription->id,
                    'title_english' => $request->basic_service_title_english[$key],
                    'title_chinese' => $request->basic_service_title_chinese[$key],
                ]);
                foreach ($request->basic_service_list_title_english[$key] as $key2 => $basic_service_list_title_english) {
                    SubscriptionBasicServiceList::create([
                        'subscription_basic_service_id' => $subscriptionBasicService->id,
                        'title_english' => $request->basic_service_list_title_english[$key][$key2],
                        'title_chinese' => $request->basic_service_list_title_chinese[$key][$key2],
                    ]);
                }
            }
            foreach ($request->optional_service_title_english as $key => $optional_service_title_english) {
                SubscriptionOptionalService::create([
                    'subscription_id' => $subscription->id,
                    'title_english' => $request->optional_service_title_english[$key],
                    'title_chinese' => $request->optional_service_title_chinese[$key],
                    'is_custom' => $request->optional_service_is_custom[$key] == 'yes' ? true : false,
                    'price' => $request->optional_service_is_custom[$key] == 'yes' ? 0 : $request->optional_service_price[$key],
                    'period' => $request->optional_service_period[$key],
                    'custom_description' => $request->optional_service_is_custom[$key] == 'yes' ? $request->optional_service_custom_description[$key] : null,
                ]);
            }
    
            return response()->json([
                'success' => true,
                'message' => __("All changes have been saved!"),
            ]);
        }
    }

    public function edit(Subscription $subscription)
    {
        return view('theme::cms.subscriptions.management.edit', [
            'subscription' => $subscription,
        ]);
    }

    public function update(Request $request, Subscription $subscription)
    {
        $validator = Validator::make($request->all(), [
            'status' => 'required|in:active,inactive',
            'name_english' => 'required|string',
            'name_chinese' => 'required|string',
            'period_english' => 'required|in:annually,monthly,daily',
            'period_chinese' => 'required|in:每年,每月,每日',
            'description_english' => 'required|string',
            'description_chinese' => 'required|string',
            'price' => 'required|numeric',
            'basic_service_title_english' => 'required|array',
            'basic_service_title_chinese' => 'required|array',
            'basic_service_list_title_english' => 'required|array',
            'basic_service_list_title_chinese' => 'required|array',
            'optional_service_title_english' => 'required|array',
            'optional_service_title_chinese' => 'required|array',
            'optional_service_is_custom' => 'required|array',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 422);
        }
        else {
            $subscription->name_english = $request->name_english;
            $subscription->name_chinese = $request->name_chinese;
            $subscription->period_english = $request->period_english;
            $subscription->period_chinese = $request->period_chinese;
            $subscription->description_english = $request->description_english;
            $subscription->description_chinese = $request->description_chinese;
            $subscription->price = $request->price;
            $subscription->status = $request->status;
            $subscription->save();

            foreach ($subscription->basicServices as $key => $basicService) {
                $basicService->lists()->delete();
            }
            $subscription->basicServices()->delete();

            foreach ($request->basic_service_title_english as $key => $basic_service_title_english) {
                $subscriptionBasicService = SubscriptionBasicService::create([
                    'subscription_id' => $subscription->id,
                    'title_english' => $request->basic_service_title_english[$key],
                    'title_chinese' => $request->basic_service_title_chinese[$key],
                ]);
                foreach ($request->basic_service_list_title_english[$key] as $key2 => $basic_service_list_title_english) {
                    SubscriptionBasicServiceList::create([
                        'subscription_basic_service_id' => $subscriptionBasicService->id,
                        'title_english' => $request->basic_service_list_title_english[$key][$key2],
                        'title_chinese' => $request->basic_service_list_title_chinese[$key][$key2],
                    ]);
                }
            }
            $subscription->optionalServices()->delete();
            foreach ($request->optional_service_title_english as $key => $optional_service_title_english) {
                SubscriptionOptionalService::create([
                    'subscription_id' => $subscription->id,
                    'title_english' => $request->optional_service_title_english[$key],
                    'title_chinese' => $request->optional_service_title_chinese[$key],
                    'is_custom' => $request->optional_service_is_custom[$key] == 'yes' ? true : false,
                    'price' => $request->optional_service_is_custom[$key] == 'yes' ? 0 : $request->optional_service_price[$key],
                    'period' => $request->optional_service_period[$key],
                    'custom_description' => $request->optional_service_is_custom[$key] == 'yes' ? $request->optional_service_custom_description[$key] : null,
                ]);
            }
    
            return response()->json([
                'success' => true,
                'message' => __("All changes have been saved!"),
            ]);
        }
    }
}
