<?php

namespace App\Http\Controllers\tatausaha;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Validator;
use Response;
use Redirect;
use Session;
use App\Models\Uploads;
use DB;


class UploadsController extends Controller
{
    public function index() {
      
      $pengumuman = Uploads::all();

      return view('tatausaha.upload.index',['pengumuman' => $pengumuman]);
    }


      public function create()
    {
       return view('tatausaha.upload.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request,['nama'=> 'required',]);

        $upload = new pengumuman;
        $upload->nama = $request->nama;
        $upload->jenis = $request->jenis;
        $upload->keterangan = $request->keterangan;
        $upload->save();
        return redirect()->route('upload.index')->with('alert-success','Data Has been Saved');
    }


    public function multiple_upload(Request $request) {

      $this->validate($request,['images'=> 'required',]);
      // getting all of the post data
      $files = Input::file('images');
      // Making counting of uploaded images
      $file_count = count($files);
      // start count how many uploaded
      $uploadcount = 0;

      foreach ($files as $file) {
        $rules = array('file' => 'required'); //'required|mimes:png,gif,jpeg,txt,pdf,doc'
        $validator = Validator::make(array('file'=> $file), $rules);

        if($validator->passes()){
          $destinationPath = 'pengumuman'; // upload folder in public directory
          $filename = $file->getClientOriginalName();
          $upload_success = $file->move($destinationPath, $filename);
          $uploadcount ++;

          // save into database
          $extension = $file->getClientOriginalExtension();
          $entry = new Uploads();
          $entry->mime = $file->getClientMimeType();
          $entry->original_filename = $filename;
          $entry->filename = $file->getFilename().'.'.$extension;
          $entry->judul = $request->judul;
          $entry->jenis = $request->jenis;
          $entry->keterangan = $request->keterangan;
          $entry->id_users = $request->user()->id;
          $entry->save();
        }
      }
      if($uploadcount == $file_count){
        Session::flash('success', 'Upload successfully');
        return redirect()->route('upload.index')->with('alert-success','Data Has been Saved');
      } else {
        return Redirect::to('upload')->withInput()->withErrors($validator);
      }
    }


    public function destroy($id)
    {
      $upload=Uploads::findOrFail($id);
      $upload->delete();
      return redirect()->route('upload.index')->with('alert-success','Data Has been Deleted');  
    }
}
