<?php

namespace App\Http\Controllers\backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\PublicationDirectory;
use Validator;
use Str;
use Image;

class PublicationDirectoryController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $datas = PublicationDirectory::latest()->get();
        return view('backend.publication_directory',compact(['datas']));
    }

    /**
     * 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)
    {
        //validating data

        $rules = [
            'title' => 'required|unique:publication_directories',
            'description' => 'required',
            'publish_status' => 'required',
        ];

        $error = Validator::make($request->all(),$rules);

        if($error->fails()){
            return response()->json(['errors'=>"Crosscheck The Data possibly the Directory Title Already Exists."]);
        }
        
        //validating if we are having file
        $files = $request->file('file_attachment');
        $image = $request->file('photo');


        //file validation
        if($files != ""){

            $file_rules = [
                'file_attachment' => 'required|mimes:pdf,doc,odf,docx,xls,xlxs|max:5120',
            ];

            $error_file = Validator::make($request->all(),$file_rules);

            if($error_file->fails()){
                return response()->json(['errors'=>"The System Accept PDF, DOC, DOCX, XLS, XLSX File Format Not More than 5MB."]);
            }
            else{
                $file_type = $files->getClientOriginalExtension();
                $file_destination = public_path('/uploads/publication_data/');
                $save_file = time().uniqid().".".$files->getClientOriginalExtension();//to save in db
                $files->move($file_destination, $save_file);
            }
        }

        //image validation
        if($image != ""){
            $image_rules = [
                'photo' => 'required|mimes:png,jpg,jpeg,tiff,gif|max:2048',
            ];

            $error_image = Validator::make($request->all(),$image_rules);

            if($error_image->fails()){
                return response()->json(['errors'=>"The System Accept PNG,JPEG,JPG,GIF,TIFF File Format Not More than 2MB."]);
            }
            else{
                $photo_image = Image::make($image);
                $photo_destination = public_path('/uploads/publication_data/');
                $photo_file = time().uniqid().".".$image->getClientOriginalExtension();//to save in db
                $resized = $photo_image->resize(600,425);
                $resized->save($photo_destination.$photo_file);
            }
        }

        //
        if($files == ""){
            $save_file = "";
            $file_type = "";
        }

        //
        if($image == ""){
            $photo_file = "";
        }

        //get data 
        $data_save = [
            'title' => $request->title,
            'description' => $request->description,
            'slug' => Str::slug($request->title),
            'file_attachment' => $save_file,
            'image_attachment' => $photo_file,
            'file_type' => $file_type,
            'publish_status' => $request->publish_status,
        ];

        $data = PublicationDirectory::create($data_save);

        if($data){
            return response()->json(["success"=>"Proceeding Page Created Successfully."]);
        }
        else{
            return response()->json(["errors"=>"Unable to Create Directory Page."]);
        }
    }

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = PublicationDirectory::findOrFail($id);
        return response()->json(['result'=>$data]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, PublicationDirectory $model)
    {
        //validating general data first
        $rules = [
            'title' => 'required',
            'description' => 'required',
            'publish_status' => 'required',
        ];

        $error = Validator::make($request->all(),$rules);

        if($error->fails()){
            return response()->json(['errors'=>"Crosscheck The Data possibly the Directory Title Already Exists."]);
        }

        //getting the previously data
        $id = $request->hidden_data;

        $previously = $model::where('id',$id)->get();

        //getting specific image and file
        foreach($previously as $data){
            $image_files = $data->image_attachment;
            $data_files = $data->file_attachment;
        }
        
        //validating if we are having file
        $files = $request->file('file_attachment');
        $image = $request->file('photo');

         //file validation
         if($files != ""){

            $file_rules = [
                'file_attachment' => 'required|mimes:pdf,doc,odf,docx,xls,xlxs|max:5120',
            ];

            $error_file = Validator::make($request->all(),$file_rules);

            if($error_file->fails()){
                return response()->json(['errors'=>"The System Accept PDF,DOC,DOCX,XLS,XLSX File Format Not More than 5MB."]);
            }
            else{

                //deleting old file since validation pass
                if(\File::exists(public_path("uploads/publication_data/$data_files"))){
                    \File::delete(public_path("uploads/publication_data/$data_files"));
                }

                $file_type = $files->getClientOriginalExtension();
                $file_destination = public_path('/uploads/publication_data/');
                $save_file = time().uniqid().".".$files->getClientOriginalExtension();//to save in db
                $files->move($file_destination, $save_file);
            }
        }

        //image validation
        if($image != ""){
            $image_rules = [
                'photo' => 'required|mimes:png,jpg,jpeg,tiff,gif|max:2048',
            ];

            $error_image = Validator::make($request->all(),$image_rules);

            if($error_image->fails()){
                return response()->json(['errors'=>"The System Accept PNG,JPEG,JPG,GIF,TIFF File Format Not More than 2MB."]);
            }
            else{

                //deleting old photo since validation pass
                if(\File::exists(public_path("uploads/publication_data/$image_files"))){
                    \File::delete(public_path("uploads/publication_data/$image_files"));
                }

                $photo_image = Image::make($image);
                $photo_destination = public_path('/uploads/publication_data/');
                $photo_file = time().uniqid().".".$image->getClientOriginalExtension();//to save in db
                $resized = $photo_image->resize(600,425);
                $resized->save($photo_destination.$photo_file);
            }
        }

        //if we have new photo and file
        if(($files != "") && ($image != "")){
            
            $data_update = [
                'title' => $request->title,
                'description' => $request->description,
                'slug' => Str::slug($request->title),
                'file_attachment' => $save_file,
                'image_attachment' => $photo_file,
                'file_type' => $file_type,
                'publish_status' => $request->publish_status,
            ];
        }

        //image not empty file empty
        else if(($files == "") && ($image != "")){
            $data_update = [
                'title' => $request->title,
                'description' => $request->description,
                'slug' => Str::slug($request->title),
                'image_attachment' => $photo_file,
                'publish_status' => $request->publish_status,
            ];
        }

        //image empty file not empty
        else if(($files != "") && ($image == "")){
            $data_update = [
                'title' => $request->title,
                'description' => $request->description,
                'slug' => Str::slug($request->title),
                'file_attachment' => $save_file,
                'file_type' => $file_type,
                'publish_status' => $request->publish_status,
            ];
        }

        //means both are empty
        else{
            $data_update = [
                'title' => $request->title,
                'description' => $request->description,
                'slug' => Str::slug($request->title),
                'publish_status' => $request->publish_status,
            ];
        }

        //updating data
        $data_result = $model::whereId($id)->update($data_update);
        
        if($data_result){
            return response()->json(['success'=>"Directory pade updated successfully."]);
        }
        else{
            return response()->json(['errors'=>"Unable to update directory page."]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request,$id)
    {
        //
        $data_delete = PublicationDirectory::where('id',$id)->get();

        //getting specific image and file
        foreach($data_delete as $row){
            $image = $row->image_attachment;
            $data_files = $row->file_attachment;
        }

        if(\File::exists(public_path("uploads/publication_data/$data_files")) || \File::exists(public_path("uploads/publication_data/$image"))){
            //deleting file
            \File::delete(public_path("uploads/publication_data/$data_files"));
            \File::delete(public_path("uploads/publication_data/$image"));
            $data = PublicationDirectory::findOrFail($id);
            
            if($data->delete()){
                return response()->json(['success'=>"Page deleted successfully."]);
            }
            else{
                return response()->json(['errors'=>"Unable to delete page."]);
            }
        }
        else{
            return response()->json(["errors"=>"Unable to delete page."]);
        }
    }
}
