<?php

namespace App\Http\Controllers;

use App\Downloads;
use App\filehelper;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class DownloadsController extends Controller
{
    public function add()
    {
        return view("downloads_add");
    }

    public function store(Request $request)
    {
        $input = $request->all();
        $rules = [
            'title' => 'required'

        ];

        $messages = [
            'title.required' => 'Title required'

        ];
        $validator = Validator::make($input, $rules, $messages);

        if ($validator->passes()) {
            $downloads = new Downloads();
            $downloads->title = $input['title'];
            $url = $input['url'];

            if (isset($url) && $url != '' && $url != 'undefined') {
                $destinationUrlPath = '/uploads/forms';
                //destination folder
                $destinationPath = public_path() . $destinationUrlPath;

                //create folder to save image
                File::makeDirectory($destinationPath, 0775, true, true);

                // changing file name
                $name = Str::slug($request->title . Carbon::now());
                $filename = $url->getClientOriginalName();
                $ext = $url->getClientOriginalExtension();
                if ($ext == "jpg" || $ext == "jpeg" || $ext == "png" || $ext == "pdf") {
                    $filename = $name . '-' . $filename;
                    $request->url->move($destinationPath, $filename);
                    $downloads->filename = $filename;
                    $downloads->filetype = $ext;
                    $inputs['url'] = $filename . "," . $ext;
                    $downloads->url = $filename;
                } else {
                    $inputs['url'] = "";
                }

            }

            $downloads->save();

            $data['status'] = 1;
            $data['message'] = "Uploaded successully";
            return response($data, 200);
        } else {
            $data['message'] = $validator->errors(0);
            $data['status'] = 0;
            return response($data, 400);
        }

    }

    public function index()
    {
        $downloads = Downloads::all();
        if ($downloads) {
            $data['downloads'] = $downloads;
            $data['status'] = 1;
            $data['message'] = "Downloads retrieved successfully";
            return response($data, 200);
        } else {
            $data['status'] = 0;
            $data['message'] = "Downloads retrieval failed";
            return response($data, 400);
        }
    }

    public function show()
    {
        $downloads = Downloads::orderby('id','desc')->get();
        return view("downloads_list", compact('downloads'));
    }
}
