<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\AdminController;
use Illuminate\Http\Request;
use App\CMSPages;
use Illuminate\Support\Facades\Validator;
use App\PagesAreaSection;
use Illuminate\Support\Facades\Storage;
use App\AreaDetail;
use App\Aws\FileSystem;
use App\WebsiteFaqs;
use App\Media;
class CmsPagesController extends AdminController {
    
    private $action = "pages";


    public function __construct() {
        $this->middleware('auth');

        $this->breadcrumbs = $this->getBreadcrumbs();
        $this->breadcrumbs[1]['link'] = "admin/pages";
        $this->breadcrumbs[1]['name'] = "Pages";
    }

    public function index() {

        $pages = CMSPages::get();
        $data["pageHeader"] = false;
        $data["model"] = $pages;
        $data["title"] = "Pages";
        $data["SubTitle"] = "List";
        $data['breadcrumbs'] = $this->breadcrumbs;
        return view('admin/cms/pages/index', $data);
    }

    public function create() {

        $data["pageHeader"] = false;
        $data["title"] = "Pages";
        $data["subTitle"] = "Create";
        $data["model"] = new CMSPages();
        $this->breadcrumbs[2]['link'] = "#_";
        $this->breadcrumbs[2]['name'] = "Create";
        $data['pages'] = CMSPages::pluck('Title', 'PKPageID');
        $data['pagesSelected'] = null;
        $data['model']['HeaderImageName'] = null;
        $data['model']['Status'] = "Enabled";
        $data["faqs"] = array();

        $data["pages_area"] = null;
        $data['breadcrumbs'] = $this->breadcrumbs;
        return view('admin/cms/pages/create', $data);
    }

    public function save(Request $request) {


        $input = $request->all();
        if ($input['Template'] == "None") {
            $rules = [
                'Title' => 'required|string',
                'AccessURL' => 'required|string|unique:cms_pages|alpha_dash',
                'Content' => 'required|string',
            ];
        } else {
            $rules = [
                 'Title' => 'required|string',
                'AccessURL' => 'required|string|alpha_dash',
            ];
        }

        $message = [];
        $validator = Validator::make($input, $rules, $message);
//
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator->errors())->withInput();
        } else {
           $faqs = empty($input["faqs"]) ? array() : $input["faqs"];


            $input["CreatedDateTime"] = date("Y-m-d H:i:s");

            if (!isset($input["Status"])) {
                $input["Status"] = "Disabled";
            }          
           
            if ($input['Template'] == "None") {
//                unset($input["Latitude"]);
//                unset($input["Longitude"]);
                unset($input["Content2"]);
            } else {
//                unset($input["Content"]);
//                unset($input["HeaderImageName"]);
            }
            
          

             if (!empty($request->HeaderImageName) && $request->HeaderImageName != null) {
                $media_id = Media::getMediaID($request->HeaderImageName);
                $input["HeaderImageName"] = $request->HeaderImageName;
                $input["image_media_id"] = $media_id;
            }
            if (!empty($request->bannerImage) && $request->bannerImage != null) {
                $media_id = Media::getMediaID($request->bannerImage);
                $input["bannerImage"] = $request->bannerImage;
                $input["image_media_id_2"] = $media_id;
            }
            
            
         


            unset($input["_token"]);
            unset($input["SectionTitle1"]);
            unset($input["Content1"]);
            unset($input["faqs"]);
            $pageId = CMSPages::insertGetId($input);
            if(count($faqs)>0){
                WebsiteFaqs::saveFaqs($this->action, $id, $faqs);
            }

//            if ($input['Template'] != "None") {
//                $data = array("FKPageID" => $pageId, "Title" => $Section1Title, "Content" => $Content1, "ImageName" => $HeaderImageName1);
//                $data1 = array("FKPageID" => $pageId, "Title" => $SectionTitle2, "Content" => $Content2, "ImageName" => $HeaderImageName2);
//                PagesAreaSection::insertGetId($data);
//                PagesAreaSection::insertGetId($data1);
//                //                        d($data);
//                //                        d($data1);
//                if ($input['Template'] == "Area") {
//                    foreach ($fkpageareaid as $row) {
//                        $data = array("FKPageID" => $pageId, "FKAreaDetailID" => $row);
//                        AreaDetail::insertGetId($data);
//                    }
//                }
//            }

            \Session::flash('success', 'Page added successfully!');
            return redirect('admin/pages');
        }
    }

    public function show($id) {

        $q = new CMSPages();
        $pages = $q->find($id);
        $data['model'] = $pages;
        $pages_area = PagesAreaSection::where('FKPageID', $id)->get();
//        $fkareadetails = AreaDetail::where('FKPageID', '=', $id)->get();
//        $ids = array();
//        foreach ($fkareadetails as $row) {
//            $ids[] = CMSPages::where('PKPageID', $row->FKAreaDetailID)->first();
//        }
//        $data["details"] = $ids;
        $data["pages_area"] = $pages_area;
        $data["title"] = "Pages";
        $this->breadcrumbs[2]['link'] = "#_";
        $this->breadcrumbs[2]['name'] = "View";
        $data['breadcrumbs'] = $this->breadcrumbs;


        return view('admin/cms/pages/show', $data);
    }

    public function edit($id) {

        $data['pages'] = CMSPages::pluck('Title', 'PKPageID');

//        $fkareadetails = AreaDetail::where('FKPageID', '=', $id)->get(["FKAreaDetailID"]);
//        $arr = json_decode($fkareadetails);
//        $ids = array();
//        foreach ($arr as $row) {
//            $ids[] = $row->FKAreaDetailID;
//        }
//
//        $data['pagesSelected'] = $ids;
        $q = new CMSPages();
        $pages = $q->find($id);
        $data['model'] = $pages;
        $pages_area = PagesAreaSection::where('FKPageID', $id)->get();
        $data["faqs"] = WebsiteFaqs::where("type", $this->action)->where("type_id", $id)->get();

//        if ($pages['Template'] != null) {
//            $count = 1;
//
//            foreach ($pages_area as $rec) {
//                $data['model']["PKSectionID" . $count] = $rec['PKSectionID'];
//                $data['model']["SectionTitle" . $count] = $rec['Title'];
//                $data['model']["Content" . $count] = $rec['Content'];
//                $data['model']["HeaderImageName" . $count] = $rec['ImageName'];
//                $count += 1;
//            }
//        }

        $data["title"] = "Pages";
        $this->breadcrumbs[2]['link'] = "#_";
        $this->breadcrumbs[2]['name'] = "Edit";
        $data['breadcrumbs'] = $this->breadcrumbs;

        return view('admin/cms/pages/edit', $data)->with('id', $id);
    }

    public function update($id, Request $request) {

        $input = $request->all();
        if ($input['Template'] == "None") {
            $rules = [
                'Title' => 'required|string',
                'AccessURL' => 'required|string|alpha_dash',
                'Content' => 'required|string',
            ];
        } else {
            $rules = [
                'Title' => 'required|string',
                'AccessURL' => 'required|string|alpha_dash',
//                'Latitude' => 'required|string',
//                'Longitude' => 'required|string',
//                'HeaderTitle' => 'required|string',
//                'SectionTitle1' => 'required|string',
//                'Content1' => 'required|string',
//                'SectionTitle2' => 'required|string',
//                'Content2' => 'required|string',
            ];
        }

        $message = [];

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

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator->errors())->withInput();
        } else {
            $faqs = empty($input["faqs"]) ? array() : $input["faqs"];

            if (!isset($input["Status"])) {
                $input["Status"] = "Disabled";
            }

//            $HeaderTitle = $input["HeaderTitle"];
//            $Section1Title = $input["SectionTitle1"];
//            $Content1 = $input["Content1"];
//            $SectionTitle2 = $input["SectionTitle2"];
//            $Content2 = $input["Content2"];


            if (isset($input["PKPageAreaID"])) {
                $fkpageareaid = $input["PKPageAreaID"];
            }
            if ($input['Template'] == "None") {
//                unset($input["Latitude"]);
//                unset($input["Longitude"]);
                unset($input["Content2"]);
            } else {
//                unset($input["Content"]);
//                unset($input["HeaderImageName"]);
            }

//            if($request->hasFile('HeaderImageName')) {
//
//            //get filename with extension
//            $filenamewithextension = $request->file('HeaderImageName')->getClientOriginalName();
//
//            //get filename without extension
//            $filename = pathinfo($filenamewithextension, PATHINFO_FILENAME);
//
//            //get file extension
//            $extension = $request->file('HeaderImageName')->getClientOriginalExtension();
//
//            //filename to store
//            $filenametostore = $filename.'.'.$extension;
//            $array=config('params.dir_upload_banners');
//            foreach ($array as $row){
//            //Upload File to external server
//            Storage::disk('ftp')->put($row.$filenametostore, fopen($request->file('HeaderImageName'), 'r+'));
//            }
//                 unset($input["HeaderImageName"]);
//
//                  $input['HeaderImageName']=$filenametostore;
//
//            }
//            if ($request->hasFile('HeaderImageName')) {
//
//                $file = $request->file('HeaderImageName');
//                $fileName = rand(111, 999) . time();
//                $input['HeaderImageName'] = FileSystem::storeImage($fileName, $file, 'uploads/pages/', 'uploads/pages/thumbnails/', 1366, 768);
////                BlogCategories::where('id', $id)->update(array("image" => $input['image']));
//            }
            if (!empty($request->HeaderImageName) && $request->HeaderImageName != null) {
                $media_id = Media::getMediaID($request->HeaderImageName);
                $input["HeaderImageName"] = $request->HeaderImageName;
                $input["image_media_id"] = $media_id;
            }
            
            if (!empty($request->bannerImage) && $request->bannerImage != null) {
                $media_id = Media::getMediaID($request->bannerImage);
                $input["bannerImage"] = $request->bannerImage;
                $input["image_media_id_2"] = $media_id;
            }
           

//            if ($request->hasFile('HeaderImageName1')) {
//
//                $file = $request->file('HeaderImageName1');
//                $fileName = rand(111, 999) . time();
//                $input['HeaderImageName1'] = FileSystem::storeImage($fileName, $file, 'uploads/pages/', 'uploads/pages/thumbnails/', 1800, 800);
////                BlogCategories::where('id', $id)->update(array("image" => $input['image']));
//                $HeaderImageName1 = $input["HeaderImageName1"];
//            }
//            if ($request->hasFile('HeaderImageName2')) {
//
//                $file = $request->file('HeaderImageName2');
//                $fileName = rand(111, 999) . time();
//                $input['HeaderImageName2'] = FileSystem::storeImage($fileName, $file, 'uploads/pages/', 'uploads/pages/thumbnails/', 1800, 800);
////                BlogCategories::where('id', $id)->update(array("image" => $input['image']));
//                $HeaderImageName2 = $input["HeaderImageName2"];
//            }


            $input["UpdatedDateTime"] = date("Y-m-d H:i:s");
            //d($input);          
//
//            if (!isset($input["Status"])) {
//                $input["Status"] = "Disabled";
//            }
//            $ImageName1 = $input["ImageName1"];
//            $ImageName2 = $input["ImageName2"];

            unset($input["_token"]);
            unset($input["faqs"]);
//            unset($input["SectionTitle1"]);
//            unset($input["Content1"]);
//            unset($input["HeaderImageName1"]);
//            unset($input["SectionTitle2"]);
//            unset($input["Content2"]);
//            unset($input["HeaderImageName2"]);
//            unset($input["PKPageAreaID"]);
//            unset($input["ImageName1"]);
//            unset($input["ImageName2"]);
            CMSPages::where('PKPageID', '=', $id)->update($input);
            if(count($faqs)>0){
                WebsiteFaqs::saveFaqs($this->action, $id, $faqs);
            }
            
//            PagesAreaSection::where('FKPageID', '=', $id)->delete();
//            AreaDetail::where('FKPageID', '=', $id)->delete();
//
//            if ($input['Template'] != "None") {
//
//                if (!($request->hasFile('HeaderImageName1')) && !($request->hasFile('HeaderImageName2'))) {
//                    $data = array("FKPageID" => $id, "Title" => $Section1Title, "Content" => $Content1, "ImageName" => $ImageName1);
//                    $data1 = array("FKPageID" => $id, "Title" => $SectionTitle2, "Content" => $Content2, "ImageName" => $ImageName2);
//                } else if (($request->hasFile('HeaderImageName1')) && !($request->hasFile('HeaderImageName2'))) {
//                    $data = array("FKPageID" => $id, "Title" => $Section1Title, "Content" => $Content1, "ImageName" => $HeaderImageName1);
//                    $data1 = array("FKPageID" => $id, "Title" => $SectionTitle2, "Content" => $Content2, "ImageName" => $ImageName2);
//                } else if (!($request->hasFile('HeaderImageName1')) && ($request->hasFile('HeaderImageName2'))) {
//                    $data = array("FKPageID" => $id, "Title" => $Section1Title, "Content" => $Content1, "ImageName" => $ImageName1);
//                    $data1 = array("FKPageID" => $id, "Title" => $SectionTitle2, "Content" => $Content2, "ImageName" => $HeaderImageName2);
//                } else if (($request->hasFile('HeaderImageName1')) && ($request->hasFile('HeaderImageName2'))) {
//                    $data = array("FKPageID" => $id, "Title" => $Section1Title, "Content" => $Content1, "ImageName" => $HeaderImageName1);
//                    $data1 = array("FKPageID" => $id, "Title" => $SectionTitle2, "Content" => $Content2, "ImageName" => $HeaderImageName2);
//                }
////                d($data);
////                d($data1);
//
//                PagesAreaSection::insertGetId($data1);
//
//                PagesAreaSection::insertGetId($data);
//
//                if ($input['Template'] == "Area") {
//                    foreach ($fkpageareaid as $row) {
//                        $data = array("FKPageID" => $id, "FKAreaDetailID" => $row);
//                        AreaDetail::insertGetId($data);
//                    }
//                }
//            }


            \Session::flash('success', 'Pages Updated successfully!');
            return redirect('admin/pages');
        }
    }

    public function delete($id) {

//        $q = new CMSPages();
//        $pages = $q->find($id);
        

        CMSPages::where('PKPageID', '=', $id)->delete();
        WebsiteFaqs::where('type_id',$id)->delete();
        
//        PagesAreaSection::where('FKPageID', '=', $id)->delete();
//        AreaDetail::where('FKPageID', '=', $id)->delete();

        \Session::flash('error', 'Page deleted successfully!');
        return redirect('admin/pages');
    }

    public function RemoveHeaderImage($id) {

        //  get image name from id 
        $q = new CMSPages();
        $pages = $q->find($id);

        //get path
        $imagepath = config('params.dir_upload_banners');
        //file exists
        foreach ($imagepath as $row) {
            $exist = Storage::disk('ftp')->exists($row . $pages->HeaderImageName);
            if ($exist == 1) {
                //delete from storage
                Storage::disk('ftp')->delete($row . $pages->HeaderImageName);
            }
        }
        //delete from db

        $input['HeaderImageName'] = null;
        CMSPages::where('PKPageID', '=', $id)->update($input);
        return $this->edit($id);
    }

    public function RemoveHeaderImage1($id) {
        $sections = PagesAreaSection::where("PKSectionID", $id)->first();
        $imagepath = config('params.dir_upload_banners');
        foreach ($imagepath as $row) {
            $exist = Storage::disk('ftp')->exists($row . $sections->ImageName);
            if ($exist == 1) {
                //delete from storage
                Storage::disk('ftp')->delete($row . $sections->ImageName);
            }
        }
        //delete from db

        $input['ImageName'] = null;
        PagesAreaSection::where("PKSectionID", $id)->update($input);
        $input['HeaderImageName1'] = null;

        return $this->edit($sections->FKPageID);
    }

    public function RemoveHeaderImage2($id) {
        $sections = PagesAreaSection::where("PKSectionID", $id)->first();
        $imagepath = config('params.dir_upload_banners');
        foreach ($imagepath as $row) {
            $exist = Storage::disk('ftp')->exists($row . $sections->ImageName);
            if ($exist == 1) {
                //delete from storage
                Storage::disk('ftp')->delete($row . $sections->ImageName);
            }
        }
        //delete from db

        $input['ImageName'] = null;
        PagesAreaSection::where("PKSectionID", $id)->update($input);
        $input['HeaderImageName2'] = null;

        return $this->edit($sections->FKPageID);
    }

}
