<?php

namespace App\Http\Controllers;

use App\Album;
use Illuminate\Http\Request;
use Response;
use Storage;

class AlbumController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $db = new Album();
        $db->name = $request->name;
        $db->save();

        return redirect()->back();
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Album  $album
     * @return \Illuminate\Http\Response
     */
    public function show(Album $album)
    {
        $data['album'] = $album;
        $data['page'] = 'albums';
        return view('backend.album.index')->with($data);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Album  $album
     * @return \Illuminate\Http\Response
     */
    public function edit(Album $album)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Album  $album
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Album $album)
    {
        $album->name = $request->name;
        $album->save();

        return redirect()->back();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Album  $album
     * @return \Illuminate\Http\Response
     */
    public function destroy(Album $album)
    {
        $album->galleries()->delete();
        Storage::deleteDirectory('/img/gallery/'.$album->slug);
        $album->delete();

        return redirect()->route('backendHome');
    }

    # Added Functions
    public function list($slug)
    {
        $album = Album::where('slug', $slug)->first();

        $galleries = $album->galleries->sortBy('order');
        $list = '<li class="first-toggle"></li>';

        foreach($galleries as $value) {
            $list = $list.'
                <li>
                    <div class="control-item"> 
                        <img class="preview-toggle" src="'.asset(config("customvar.storage_url").'img/gallery/'.$slug.'/'.str_replace(".", "_tn.", $value->path)).'" alt="'.$value->path.'" data-caption="'.$value->caption.'"> 
                    </div> 
                </li>';
        }

        $list = $list.'<li class="last-toggle"></li>';

        return Response::json(['list' => $list, 'count' => $galleries->count()]);

    }
}
