<?php

class LocationsController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 * GET /locations
	 *
	 * @return Response
	 */
	public function index()
	{
        $locations = Location::all();
        $location = new Location;
		return View::make('locations.index', ['locations' => $locations, 'location' => $location]);
	}

	/**
	 * Show the form for creating a new resource.
	 * GET /locations/create
	 *
	 * @return Response
	 */
	public function create()
	{
		//
	}

	/**
	 * Store a newly created resource in storage.
	 * POST /locations
	 *
	 * @return Response
	 */
	public function store()
	{
        $name = Input::get('name');
        $amount = (int) Input::get('floor_amount');
        if (empty($name) || empty($amount)) {
            return Redirect::back()->withInput()->withMessage('messages.fail-to-create')->with('messageType', 'danger');
        }
        $location = Location::create([
            'name'  =>  $name,
            'floor_amount'  =>  $amount
        ]);
        if ($amount > 0 && $location) {
            for ($i=1; $i <= $amount ; $i++) {
                $floor = Floor::create([
                    'name' => ($i > 9) ? $name."{$i}" : $name."0{$i}",
                    'location_id'  => $location->id
                ]);
            }
        }
        return Redirect::back()->withMessage('messages.success-to-create')->with('messageType', 'success');

	}

	/**
	 * Display the specified resource.
	 * GET /locations/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{

	}

	/**
	 * Show the form for editing the specified resource.
	 * GET /locations/{id}/edit
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
        $locations = Location::where('id', $id)->get();
        $location = Location::find($id);
        if (empty($location)) return Redirect::back();
		return View::make('locations.index', ['locations' => $locations, 'location' => $location]);
	}
    private function changeNameFloor($floors, $newName) {
        $floors = $floors;
        if (count($floors) > 0) {
            $i = 1;
            foreach($floors as $floor) {
                $f = Floor::find($floor->id);
                $f->name = ($i > 9) ? $newName.$i : $newName."0{$i}";
                $boxes = Box::where('floor_id', $floor->id)->get();
                if (count($boxes) > 0) {
                    $j = 1;
                    foreach ($boxes as $box) {
                        $b = Box::find($box->id);
                        $b->name = ($j > 9) ? $f->name.$j : $f->name."0{$j
                        }";
                        $b->save();
                        $j++;
                    }
                }
                $f->save();
                $i++;
            }
        }
    }
	/**
	 * Update the specified resource in storage.
	 * PUT /locations/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
        $name = Input::get('name');
        $amount = (int) Input::get('floor_amount');
        if ($amount <= 0) return Redirect::back()->withMessage('messages.fail-to-update')->with('messageType', 'danger');
        $location_id = (int) Input::get('location_id');
        $location = Location::find($id);
        $floor_amounts = Floor::where('location_id', $id)->count();
        if ($floor_amounts == $amount && $location->name == $name) {
            return Redirect::back()->withMessage('messages.success-to-update')->with('messageType', 'success');
        }
        $newName = ($location->name != $name) ? $name : $location->name;
        // Working Only Change Name
        if ($location->name != $name && $floor_amounts == $amount) {
            $floors = Floor::where('location_id', $id)->get();
            $this->changeNameFloor($floors, $newName);
            $location->name = $newName;
            $location->save();
            return Redirect::back()->withMessage('messages.success-to-update')->with('messageType', 'success');
        }

        // Change Amount of Floor
        if ($amount > $floor_amounts ) {

            $floors = Floor::where('location_id', $id)->get();
            if ($location->name != $name && count($floors) > 0) {
                $this->changeNameFloor($floors, $newName);
            }
            for ($i=$floor_amounts+1; $i <= $amount ; $i++) {
                $box = Floor::create([
                    'name' => ($i > 9) ? $newName.$i : $newName."0{$i}",
                    'location_id' => $location->id
                ]);
            }
            $location->name = $newName;
            $location->floor_amount = $amount;
        } else {
            // Work when Amount lower than old amount
            $limit = $floor_amounts - $amount;
            $floors =  Floor::take($limit)->where('location_id', $id)->orderBy('name', "DESC")->get();
            if ($location->name != $name) {
                $this->changeNameFloor($floors, $newName);
            }
            foreach ($floors as $floor) {
                $b = Floor::find($floor->id);
                $boxes = Box::where('floor_id', $floor->id)->get();
                foreach ($boxes as $box) {
                    $fb = Box::find($box->id);
                    $fb->delete();
                }
                $b->delete();
            }
            $location->name = $newName;
            $location->floor_amount = $amount;
        }
        $location->save();
        return Redirect::back()->withMessage('messages.success-to-update')->with('messageType', 'success');
	}

	/**
	 * Remove the specified resource from storage.
	 * DELETE /locations/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		//
	}

    public function getLocationFloors($id)
    {
        $floors = Floor::where('location_id', $id)->get();
        $floors = Location::find($id)->floors;
        $location = Location::find($id);
        return View::make('locations.floors', ['floors' => $floors, 'location' => $location]);
    }

    public function floorBoxes()
    {
        $name = Input::get('name');
        $amount = (int) Input::get('box_amount');
        $floor_id = (int) Input::get('floor_id');
        $floor = Floor::find($floor_id);
        $box_amounts = Box::where('floor_id', $floor_id)->count();
        if ($box_amounts == $amount) {
            return Redirect::back()->withMessage('messages.success-to-update')->with('messageType', 'success');
        }

        if ($amount > $box_amounts ) {
            for ($i=$box_amounts+1; $i <= $amount ; $i++) {
                $box = Box::create([
                    'name' => ($i > 9) ? $floor->name.$i : $floor->name."0{$i}",
                    'floor_id' => $floor->id
                ]);
            }
            $floor->box_amount = $amount;
        } else {
            $limit = $box_amounts - $amount;
            $boxes =  Box::take($limit)->orderBy('name', "DESC")->get();
            foreach ($boxes as $box) {
                $b = Box::find($box->id);
                $b->delete();
            }
            $floor->box_amount = $amount;
        }
        $floor->save();
        return Redirect::back()->withMessage('messages.success-to-update')->with('messageType', 'success');
    }

    public function getBoxes()
    {
        $boxes = DB::table('boxes')->where('name','LIKE',"%".Input::get('term')."%")->select(['id','name'])->get();
		return Response::json(array(
					'boxes'			=>	$boxes,
					'error' 		=> false),
					200
				);
    }

}
