<?php

namespace App\Http\Controllers;

use App\Models\Draft;
use App\Models\DraftItem;
use App\Models\DraftType;
use Input;

class DraftController extends Controller
{
    public function __construct()
    {
       $this->middleware('admin');

    }

    public function index($step = false)
    {
        $data = [
            'drafts' => Draft::all()->sortByDesc("id"),
            'draft_types' => DraftType::all()->sortByDesc("id"),
            'step' => $step
        ];
        return view('drafts.index', $data);


    }

    public function detail($id)
    {
        if($id == "new") {
            $draft = new Draft();
            $draft->active = true;
            $id = 'new';

        }else{
            $draft = Draft::findOrFail($id);
            $id = $draft->id;
        }
            $data = [
                'draft' => $draft,
                'id' => $id,
            ];
        return view('drafts.detail', $data);

    }

    public function store($id)
    {
        $data = Input::all();
        if($id == "new") {
            $draft = new Draft();
        }else{
            $draft = Draft::findOrFail($id);
        }

        $draft->name = $data['name'];
        $draft->active = isset($data['active']) ? true : false;
        $draft->save();

        $i = 1;
        if(isset($data['draft_item'])){
            foreach ($data['draft_item'] as $draft_item_id => $draft_item){
                if($data['action'] == 'saveAllFromOld'){
                    $di = $draft->draft_items()->create([]);
                }else{
                    $di = DraftItem::findOrFail($draft_item_id);
                }
                $di->draft_type_id = $draft_item['draft_type_id'];
                $di->days_start = $draft_item['days_start'];
                $di->days_duration = $draft_item['days_duration'];
                $di->service = $draft_item['service'];
                $di->price_adult = $draft_item['price_adult'];
                $di->adult = $draft_item['adult'];
                $di->price_children = $draft_item['price_children'];
                $di->children = $draft_item['children'];
                $di->in_pdf = isset($draft_item['in_pdf']) ? true : false;
                $di->pos =  $i++;

                $di->save();
            }
        }

        if($data['action'] == 'addItem'){
            $draft->draft_items()->create(['pos' => $i]);
        }
        if(strpos($data['action'], 'up_') !== false) {
            $reId = intval(str_replace('up_', '', $data['action']));
            $d_from = DraftItem::findOrFail($reId);
            $d_to = $draft->findBeforeRelation($reId);
            if($d_to) {
                $t_pos = $d_from->pos;
                $d_from->pos = $d_to->pos;
                $d_to->pos = $t_pos;
                $d_from->save();
                $d_to->save();
            }
        }
        if(strpos($data['action'], 'down_') !== false) {
            $reId = intval(str_replace('down_', '', $data['action']));
            $d_from = DraftItem::findOrFail($reId);
            $d_to = $draft->findAfterRelation($reId);
            if($d_to) {
                $t_pos = $d_from->pos;
                $d_from->pos = $d_to->pos;
                $d_to->pos = $t_pos;
                $d_from->save();
                $d_to->save();
            }
        }
        \Session()->flash('alert-save', '1');
        return redirect(route('draft_detail', [$draft->id]));

    }

    public function delete($id){
        $draft = Draft::findOrFail($id);

        foreach ($draft->draft_items as $draft_item){
            $draft_item->delete();
        }

        foreach ($draft->travel_program_drafts as $travel_program_draft){
            $travel_program_draft->delete();
        }


        $draft->delete();
        \Session()->flash('alert-success', __('Vorlage gelöscht'));
        return redirect(route('drafts'));
    }

    public function itemDelete($id){
        $draft_item = DraftItem::findOrFail($id);
        $draft_id = $draft_item->draft_id;
        $draft_item->delete();
        \Session()->flash('alert-success', __('Eintrag gelöscht'));
        return redirect(route('draft_detail', [$draft_id]));
    }


    /**
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function typeUpdate(){

        $data = Input::all();
        if($data['id'] == "new"){
            $draft_type = DraftType::create([
                'name' => $data['name'],
                'active' => isset($data['active']) ? true : false,
                'color' => $data['color'],
            ]);
        }else{
            $draft_type = DraftType::find($data['id']);
            $draft_type->name = $data['name'];
            $draft_type->active = isset($data['active']) ? true : false;
            $draft_type->color = $data['color'];

            $draft_type->save();
        }

        \Session()->flash('alert-save', '1');
        return redirect(route('drafts', ['type']));

    }
    public function typeDelete($id){

        if(DraftItem::where('draft_type_id', $id)->count()){
            \Session()->flash('alert-error', 'Eintrag wird verwendet');
            return redirect(route('drafts'));
        }
        $draft_type = DraftType::findOrFail($id);
        $draft_type->delete();
        \Session()->flash('alert-success', 'Eintrag gelöscht');
        return redirect(route('drafts', ['type']));
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function loadOldAction(){
        $data = Input::all();
        $template = \App\Models\Sym\ArrangementTemplate::findOrFail($data['load_old']);

        $draft = new Draft();
        $draft->active = true;
        $draft->name = $template->title;

        $draft_items = [];
        foreach ($template->arrangements as $arrangement){
            $data_s = explode("\n", $arrangement->data_s);
            $service = "";
            $priceAdult = false;
            $adult = false;
            $priceChildren = false;
            $children = false;

            foreach ($data_s as $ds){
                if(strpos($ds, 'Name:') !== false){
                    $service .= str_replace('Name: ', '', $ds);
                    $ds = "";
                }
                if(strpos($ds, 'Preis:') !== false){
                    $p = floatval(str_replace('Preis: ', '', $ds));
                    $priceAdult = number_format($p, 2, ',', '.');
                    $ds = "";
                }
                if(strpos($ds, 'Teilnehmer:') !== false){
                    $adult = intval(str_replace('Teilnehmer: ', '', $ds));
                    $ds = "";
                }
                if(strpos($ds, 'KindPreis:') !== false){
                    $p = floatval(str_replace('KindPreis: ', '', $ds));
                    $priceChildren = number_format($p, 2, ',', '.');
                    $ds = "";
                }
                if(strpos($ds, 'Kind:') !== false){
                    $children = intval(str_replace('Kind: ', '', $ds));
                    $ds = "";
                }
                if($ds != ""){
                    $service .= $ds;
                }
            }
            $draft_items[] = array(
                'draft_type_id' => $arrangement->type_id,
                'in_pdf' => $arrangement->in_pdf,
                'service' => trim($service),
                'price_adult' => $priceAdult,
                'adult' => $adult,
                'price_children' => $priceChildren,
                'children' => $children,
                'days_start' => null,
                'days_duration' => null,
            );
        }
        $data = [
            'draft' => $draft,
            'draft_items' => $draft_items,
            'id' => 'new',
        ];
        return view('drafts.detail', $data);

    }

    public function loadNew(){
        $data = [
            'drafts' => Draft::all()->sortByDesc("id"),
        ];
        return view('drafts.load_new', $data);
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function loadNewAction(){
        $data = Input::all();
        $d = Draft::findOrFail($data['load_new']);
        $draft = new Draft();
        $draft->active = true;
        $draft->name = $d->name;

        $draft_items = [];
        foreach ($d->draft_items as $di){
            $draft_items[] = array(
                'draft_type_id' => $di->draft_type_id,
                'in_pdf' => $di->in_pdf,
                'service' => $di->service,
                'price_adult' => $di->price_adult,
                'adult' => $di->adult,
                'price_children' => $di->price_children,
                'children' => $di->children,
                'days_start' => $di->days_start,
                'days_duration' => $di->days_duration,
            );
        }
        $data = [
            'draft' => $draft,
            'draft_items' => $draft_items,
            'id' => 'new',
        ];
        return view('drafts.detail', $data);

    }

    public function loadOld(){
        $data = [
            'templates' => \App\Models\Sym\ArrangementTemplate::all(),
        ];
        return view('drafts.load_old', $data);
    }
}


