<?php

namespace App\Http\Controllers;

use App\Calendar;
use App\CalendarGame;
use App\Season;
use App\Team;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
class CalendarController extends Controller
{

    protected $rules = [
        // 'name' => ['required']
    ];

    public function index()
    {
            $calendars = Calendar::orderBy('position')->orderBy('name')->get(); //->paginate(50);

        return view('calendars.index',compact('calendars'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $seasons = Season::orderBy('name')->pluck('name', 'id')->toArray();;
        return view('calendars.create', compact('seasons'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        //CalendarGame::truncate();
        //Calendar::truncate();

        $request->validate($this->rules);

        $input = $request->all();
        $input["name"] = '';
        $calendar = Calendar::create($input);

        // Creo le giornate
        if(request()->file)
        {

            $file = request()->file;
            $filename  = time() . '_' . $file->getClientOriginalName();

            if (! File::exists(public_path()."/files/calendars"))
                File::makeDirectory(public_path()."/files/calendars");

            $path = public_path('files/calendars');

            request()->file->move($path, $filename);

            $handle = fopen($path . "/" . $filename, "r");
            if ($handle)
            {

                $aTeams = array();

                $aT = array("ANDATA", "RITORNO");

                foreach($aT as $type)
                {
                    $date = '';
                    $day = 0;
                    $insert = false;

                    $handle = fopen($path . "/" . $filename, "r");
                    while (($line = fgets($handle)) !== false)
                    {

                        if (substr($line, 0, 3) == '.--' || substr($line, 0, 3) == '|--')
                        {
                            $insert = false;
                        }

                        if (strpos($line, $type . ':') !== false)
                        {
                            $day += 1;

                            $tmp = $line;
                            if ($type == 'ANDATA')
                            {
                                $start = strpos($tmp, '|');
                                $end = strpos($tmp, '|', 1);
                            }
                            else
                            {
                                $start = strpos($tmp, 'RITORNO: ');
                                $end = strrpos($tmp, '|');
                            }

                            if ($type == 'ANDATA')
                            {
                                $tmp = substr($tmp, $start + 1, $end - 1);
                                $tmp = str_replace($type . ":", "", $tmp);
                            }
                            else
                            {
                                $tmp = substr($tmp, $start + 8, 10);
                            }
                            $tmp = trim($tmp);
                            list($dt, $month, $year) = explode("/", $tmp);
                            $date = "20" . $year . "-" . $month . "-" . $dt;

                        }

                        if($insert)
                        {
                            $tmp = $line;
                            $tmp = trim(str_replace("|", "", $tmp));
                            list($home, $away) = explode("-", $tmp);

                            $home_team_id = $this->getTeam($home, $calendar->season_id);
                            $away_team_id = $this->getTeam($away, $calendar->season_id);

                            $calendar_game = new CalendarGame();
                            $calendar_game->calendar_id = $calendar->id;
                            $calendar_game->home_team_id = $type == 'ANDATA' ? $home_team_id : $away_team_id;
                            $calendar_game->away_team_id = $type == 'ANDATA' ? $away_team_id : $home_team_id;
                            $calendar_game->date = $date;
                            $calendar_game->day = $day;
                            $calendar_game->type = $type;
                            $calendar_game->home_goals = null;
                            $calendar_game->away_goals = null;
                            $calendar_game->home_points = null;
                            $calendar_game->away_points = null;
                            $calendar_game->save();

                        }

                        if (substr($line, 0, 3) == '|--')
                        {
                            $insert = true;
                        }

                    }
                }

                fclose($handle);
            }
            else
            {

            }

        }

        return redirect()->route('calendars.index')
                        ->with('success','Calendar created successfully.');
    }

    public function getTeam($team, $season_id)
    {

        $ret = 0;
        $team = trim($team);

        if (strpos(strtolower($team), 'riposa') !== false)
        {
            $ret = null;
        }
        else
        {
            $t = Team::where('name', '=', $team)->where('season_id', '=', $season_id)->first();
            if($t == null)
            {
                $t = new Team();
                $t->name = $team;
                $t->type = '';
                $t->season_id = $season_id;
                $t->save();
            }
            $ret = $t->id;
        }
        return $ret;
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Calendar  $calendar
     * @return \Illuminate\Http\Response
     */
    public function show(Calendar $calendar)
    {
        return view('calendars.show',compact('calendar'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Calendar  $calendar
     * @return \Illuminate\Http\Response
     */
    public function edit(Calendar $calendar)
    {
        $seasons = Season::orderBy('name')->pluck('name', 'id')->toArray();;
        return view('calendars.edit',compact('calendar', 'seasons'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Calendar  $calendar
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Calendar $calendar)
    {
        $request->validate($this->rules);

        $input = $request->all();

        $input["name"] = '';

        // Creo le giornate
        if(request()->file)
        {

            // Elimino il vecchio
            $aTeams = array();

            $games = CalendarGame::where('calendar_id', '=', $calendar->id)->get();
            foreach($games as $game)
            {
                $home_team_id = $game->home_team_id;
                $away_team_id = $game->away_team_id;

                if ($home_team_id != null)
                {
                    if(!in_array($home_team_id, $aTeams, true))
                    {
                        array_push($aTeams, $home_team_id);
                    }
                }

                if ($away_team_id != null)
                {
                    if(!in_array($away_team_id, $aTeams, true))
                    {
                        array_push($aTeams, $away_team_id);
                    }
                }

                $game->delete();

            }

            foreach($aTeams as $team_id)
            {
                $th = Team::where('id', '=', $team_id)->first();
                if ($th != null)
                    $th->delete();
            }

            $file = request()->file;
            $filename  = time() . '_' . $file->getClientOriginalName();

            if (! File::exists(public_path()."/files/calendars"))
                File::makeDirectory(public_path()."/files/calendars");

            $path = public_path('files/calendars');

            request()->file->move($path, $filename);

            $handle = fopen($path . "/" . $filename, "r");
            if ($handle)
            {

                $aTeams = array();

                $aT = array("ANDATA", "RITORNO");

                foreach($aT as $type)
                {
                    $date = '';
                    $day = 0;
                    $insert = false;

                    $handle = fopen($path . "/" . $filename, "r");
                    while (($line = fgets($handle)) !== false)
                    {

                        if (substr($line, 0, 3) == '.--' || substr($line, 0, 3) == '|--')
                        {
                            $insert = false;
                        }

                        if (strpos($line, $type . ':') !== false)
                        {
                            $day += 1;

                            $tmp = $line;
                            if ($type == 'ANDATA')
                            {
                                $start = strpos($tmp, '|');
                                $end = strpos($tmp, '|', 1);
                            }
                            else
                            {
                                $start = strpos($tmp, 'RITORNO: ');
                                $end = strrpos($tmp, '|');
                            }

                            if ($type == 'ANDATA')
                            {
                                $tmp = substr($tmp, $start + 1, $end - 1);
                                $tmp = str_replace($type . ":", "", $tmp);
                            }
                            else
                            {
                                $tmp = substr($tmp, $start + 8, 10);
                            }
                            $tmp = trim($tmp);
                            list($dt, $month, $year) = explode("/", $tmp);
                            $date = "20" . $year . "-" . $month . "-" . $dt;

                        }

                        if($insert)
                        {
                            $tmp = $line;
                            $tmp = trim(str_replace("|", "", $tmp));
                            list($home, $away) = explode("-", $tmp);

                            $home_team_id = $this->getTeam($home, $calendar->season_id);
                            $away_team_id = $this->getTeam($away, $calendar->season_id);

                            $calendar_game = new CalendarGame();
                            $calendar_game->calendar_id = $calendar->id;
                            $calendar_game->home_team_id = $type == 'ANDATA' ? $home_team_id : $away_team_id;
                            $calendar_game->away_team_id = $type == 'ANDATA' ? $away_team_id : $home_team_id;
                            $calendar_game->date = $date;
                            $calendar_game->day = $day;
                            $calendar_game->type = $type;
                            $calendar_game->home_goals = null;
                            $calendar_game->away_goals = null;
                            $calendar_game->home_points = null;
                            $calendar_game->away_points = null;
                            $calendar_game->save();

                        }

                        if (substr($line, 0, 3) == '|--')
                        {
                            $insert = true;
                        }

                    }
                }

                fclose($handle);
            }
            else
            {

            }

        }

        $calendar->update($input);

        return redirect()->route('calendars.index')
                        ->with('success','Calendar updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Calendar  $calendar
     * @return \Illuminate\Http\Response
     */
    public function destroy(Calendar $calendar)
    {

        $aTeams = array();

        $games = CalendarGame::where('calendar_id', '=', $calendar->id)->get();
        foreach($games as $game)
        {
            $home_team_id = $game->home_team_id;
            $away_team_id = $game->away_team_id;

            if ($home_team_id != null)
            {
                if(!in_array($home_team_id, $aTeams, true))
                {
                    array_push($aTeams, $home_team_id);
                }
            }

            if ($away_team_id != null)
            {
                if(!in_array($away_team_id, $aTeams, true))
                {
                    array_push($aTeams, $away_team_id);
                }
            }

            $game->delete();

        }

        foreach($aTeams as $team_id)
        {
            $th = Team::where('id', '=', $team_id)->first();
            if ($th != null)
                $th->delete();
        }

        // CalendarGame::where('calendar_id', '=', $calendar->id)->delete();

        $calendar->delete();

        return redirect()->route('calendars.index')
                        ->with('success','Calendar deleted successfully');
    }

}
