<?php

namespace MtcPharmacy\Subscriptions\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Mtc\Modules\Members\Models\Member;
use Mtc\Shop\Item as ShopItem;
use Mtc\Shop\Item\Size as ShopItemSize;
use MtcPharmacy\Subscriptions\Classes\Subscription;
use MtcPharmacy\Subscriptions\Classes\SubscriptionItem;


class SubscriptionsController extends \App\Http\Controllers\Controller
{

    public function manage()
    {
        return template('admin/subscriptions_manage.twig', [
            'selected_tab' => 'manage',
            'title' => 'Subscriptions',
        ]);
    }


    public function create($member_id, Request $request)
    {
        $member = Member::findOrFail($member_id);

        $subscription = new Subscription();
        $subscription->member()->associate($member);
        $subscription->save();

        return redirect()->route('admin-subscriptions-edit', [ $subscription->id ]);
    }


    private function add_shop_item(Subscription $subscription, $item_to_add)
    {
        list($shop_item_id, $shop_item_size_id) = explode(':', $item_to_add);

        $shop_item = ShopItem::find($shop_item_id);
        $shop_item_size = ShopItemSize::find($shop_item_id);
        $si = SubscriptionItem::createFromShopItem($shop_item, $shop_item_size);

        $subscription->items()->save($si);
        Session::flash('success_message', [ 'type' => 'success', 'content' => 'Added.' ]);

        return redirect()->route('admin-subscriptions-edit', [ $subscription->id ]);
    }


    public function delete_item(int $subscription_item_id, Request $request)
    {
        $subscription_item = SubscriptionItem::findOrFail($subscription_item_id);

        $subscription_item->delete();
        Session::flash('success_message', [ 'type' => 'success', 'content' => 'Item deleted.' ]);

        return redirect()->route('admin-subscriptions-edit', [ $subscription_item->subscription->id ]);
    }


    public function update(int $subscription_id, Request $request)
    {
        $subscription = Subscription::findOrFail($subscription_id);

        if ($request->input('button_pressed') == 'add_item') {

            return $this->add_shop_item($subscription, $request->input('item_to_add'));

        } else {

            $subscription->fill($request->input());
            if (! $request->input('can_be_paused')) {
                $subscription->can_be_paused = false;
            }

            $errors_bag = $subscription->validate()->errors();
            if ($errors_bag->isEmpty()) {
                $subscription->save();
                Session::flash('success_message', [ 'type' => 'success', 'content' => 'Saved.' ]);
            } else {
                $form_errors = \App\FlashMessage::getImplodedMessages($errors_bag);
                Session::flash('form_errors', $form_errors);
            }

        }

        return redirect()->route('admin-subscriptions-edit', [ $subscription->id ]);
    }


    public function edit(int $subscription_id, Request $request)
    {
        $subscription = Subscription::findOrFail($subscription_id);
        $messages = $this->getFormMessages();

        return template('admin/subscription_edit.twig', [
            'subscription' => $subscription,
            'selected_tab' => 'edit',
            'title' => '',
            'allowed_statuses' => array_combine(
                Subscription::get_allowed_statuses(),
                Subscription::get_allowed_statuses()
            ),
            'allowed_intervals' => array_combine(
                Subscription::get_allowed_intervals(),
                Subscription::get_allowed_intervals()
            ),
            'messages' => $messages,
            'allowed_items' => SubscriptionItem::getAllowedItems(),
        ]);
    }


    private function getFormMessages()
    {
        $messages = [];

        if ($success_message = Session::pull('success_message')) {
            $messages[] = $success_message;
        }

        if ($form_errors = Session::pull('form_errors')) {
            $messages[] = ['type' => 'error', 'content' => 'Something went wrong!'];
            $messages['errors'] = $form_errors;
        }

        return $messages;
    }


    public function data()
    {
        $offset = request()->input('start', 0);
        $limit = request()->input('length', 10);
        $draw = request()->input('draw', 1);

        $subscriptions = Subscription::query()
            ->offset($offset)
            ->limit($limit)
            ->get()
        ;

        $data = [];
        foreach ($subscriptions as $subscription) {

            $subscription_items_array = [];
            foreach ($subscription->items as $subscription_item) {
                $subscription_items_array[] = $subscription_item->getDisplayName();
            }

            $subscription_items_string = implode('<br />', $subscription_items_array);

            $sim_subs = [];
            foreach ($subscription->getSimilarSubscriptions() as $sim_sub) {
                $sim_subs[$sim_sub->id] = "#{$sim_sub->id}";
            }

            $data[] = [
                'id' => $subscription->id,
                'items' => $subscription_items_string,
                'member' => "{$subscription->member->full_name} ({$subscription->member->email})",
                'interval_multiplier' => $subscription->interval_multiplier,
                'interval' => $subscription->interval,
                'status' => $subscription->status,
                'can_be_paused' => $subscription->getCanBePausedString(),
                'similar_subscriptions' => implode(', ', $sim_subs),
                'max_number_of_issues' => $subscription->getMaxNumberOfIssues(),
                'next_issue_date' => $subscription->getNextIssueDate(),
                'actions' => [
                    'edit' => route('admin-subscriptions-edit', $subscription->id),
                ],
            ];

        }

        $records_total = Subscription::count();

        return [
            "draw" => $draw,
            "recordsTotal" => $records_total,
            "recordsFiltered" => $records_total,
            'data' => $data,
        ];
    }


    public function generate_order($subscription_id, Request $request)
    {
        $subscription = Subscription::findOrFail($subscription_id);

        $ignore_checks = $request->input('ignore_checks');
        $attempt_token_payment = $request->input('attempt_token_payment');

        $new_order = $subscription->generateNewOrder($ignore_checks, $attempt_token_payment);

        return [
            'generated_order_id' => $new_order->id ?? null,
            'payment_captured' => $new_order->paid ?? null,
        ];
    }

}
