<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Packages;
use App\Categories;
use App\Http\Controllers\AdminController;
use App\Excesses;
use App\PackagePrices;
use App\Facilities;
use App\PackageFacilities;
use App\Aws\FileSystem;
use App\WebsiteFaqs;
use App\Media;

class PackagesController extends AdminController {

    private $action = "packages";
    private $folder = "packages";
    private $title = "Packages";
    private $heading = "Package";

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

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

    public function index() {

        $model = Packages::get();

        $data["pageHeader"] = false;
        $data["model"] = $model;
        $data["action"] = $this->action;
        $data["folder"] = $this->folder;
        $data["heading"] = $this->heading;
        $data["title"] = $this->title;

        $data["SubTitle"] = "List";
        $data['breadcrumbs'] = $this->breadcrumbs;
        return view('admin/' . $this->folder . '/index', $data);
    }

    public function create(Request $request) {

        $data["pageHeader"] = false;
        $data["model"] = new Packages();
        $data["title"] = $this->title;
        $data["subTitle"] = "Create";
        $data["faqs"] = array();
        $data["prices"] = array();
        $data["action"] = $this->action;
        $data["folder"] = $this->folder;
        $data["heading"] = $this->heading;

        $data["categories"] = Categories::pluck('title', 'id');
        $data["excesses"] = Excesses::where("status", 1)->orderBy("position", "asc")->get();

        $data["facilities"] = Facilities::where("status", 1)->orderBy("position", "asc")->get();
        $this->breadcrumbs[2]['link'] = "#_";
        $this->breadcrumbs[2]['name'] = "Create";

        $data["packageFacilities"] = array();


        $data['breadcrumbs'] = $this->breadcrumbs;
        return view('admin/' . $this->folder . '/create', $data);
    }

    public function save(Request $request) {

        $rules = [
            'title' => 'required|max:255',
                //'description' => 'required|max:200'
        ];

        $input = $request->all();

        $message = [];
        $validator = Validator::make($input, $rules, $message);
        $header = 200;
        $response = array();
        if ($validator->fails()) {
            $errors = $validator->errors();
            $response['errors'] = $errors;
            $response['error'] = true;
            $header = 402;
            //return redirect()->back()->withErrors($validator->errors())->withInput();
        } else {
            $prices = !empty($input["prices"]) ? $input["prices"] : array();
            $facilities = !empty($input["facilities"]) ? $input["facilities"] : array();
            $file = !empty($input["file"]) ? $input["file"] : null;
            $slugify = slugify($input["title"]);
            unset($input["_token"]);
            unset($input["prices"]);
            unset($input["facilities"]);

            if (!isset($input["popular"])) {
                $input["popular"] = 0;
            }

            if (empty($input["position"])) {
                $input["position"] = 0;
            }
            $input["code"] = $slugify;



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

            if (!empty($request->file) && $request->file != null) {
                $destination = "uploads/packages/downloads";
                $fileName = $input["code"];
                $fileName = FileSystem::storeFile($fileName, $request->file, $destination);
                $input["file"] = $fileName;
            }

            $model = new Packages();
            $input["created_at"] = date("Y-m-d H:i:s");
            $id = $model->insertGetId($input);

            //Packages::where("id", $id)->update(array("code" => $slugify));

            $this->insertPrices($id, $prices);

            $this->insertFacilities($id, $facilities);


            \Session::flash('success', $this->heading . ' added successfully!');

            //return redirect('admin/' . $this->action);
        }
        return response()->json($response, $header);
    }

    public function savefaqs(Request $request) {
        $input = $request->all();

        $rules = [
            'title' => 'required'
        ];

        $messages = [];

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

        if ($validator->fails()) {
            $errors = $validator->errors();
            $response['errors'] = $errors;
            $response['error'] = true;
            $header = 402;
        } else {
            unset($input["_token"]);

            $response['error'] = false;
            $header = 200;

            $response['input'] = $input;
        }

        return response()->json($response, $header);
    }

    public function insertPrices($id, $prices) {
        foreach ($prices as $type => $excesses) {

            foreach ($excesses as $excess_id => $excess) {
                $arr = array("package_id" => $id, "excess_id" => $excess_id, "type" => $type, "price" => $excess['price'], "vat" => $excess['vat']);
                PackagePrices::insertGetId($arr);
            }
        }
    }

    public function insertFacilities($id, $facilities) {
        foreach ($facilities as $facility_id => $facility) {
            // && isset($facility["has_price"]) && !empty($facility["price"])
            if (isset($facility["available"])) {

                if (isset($facility["has_price"])) {
                    $hasPrice = 1;
                    $price = !empty($facility["price"]) ? $facility["price"] : 0;
                } else {
                    $hasPrice = 0;
                    $price = null;
                }

                $arr = array("package_id" => $id, "facility_id" => $facility_id, "hasPrice" => $hasPrice, "price" => $price);
                PackageFacilities::insertGetId($arr);
            }
        }
    }

    public function edit($id) {
        $model = Packages::find($id);

        $prices = array();
        $facilities = array();

        foreach ($model->prices as $price) {
            $prices[$price->type][$price->excess_id]["price"] = $price->price;
            $prices[$price->type][$price->excess_id]["vat"] = $price->vat;
        }


        foreach ($model->facilities as $facility) {
            $facilities[$facility->facility_id]["has_price"] = $facility->hasPrice;
            $facilities[$facility->facility_id]["price"] = $facility->price;
        }

        $data["faqs"] = WebsiteFaqs::where("type", $this->action)->where("type_id", $id)->get();
        $data["prices"] = $prices;
        $data["packageFacilities"] = $facilities;
        //$data["prices"] = isset($model->prices) ? $model->prices : array();
        $data["model"] = $model;
        $data["pageHeader"] = false;
        $data["action"] = $this->action;
        $data["folder"] = $this->folder;
        $data["heading"] = $this->heading;
        $data["subTitle"] = "Edit";
        $data["title"] = $this->title;
        $data["id"] = $id;
        $data["categories"] = Categories::pluck('title', 'id');
        $data["excesses"] = Excesses::where("status", 1)->orderBy("position", "asc")->get();
        $data["facilities"] = Facilities::where("status", 1)->orderBy("position", "asc")->get();
        $this->breadcrumbs[2]['link'] = "#_";
        $this->breadcrumbs[2]['name'] = "Edit";
        $data['breadcrumbs'] = $this->breadcrumbs;
        return view('admin/' . $this->folder . '/edit', $data);
    }

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

        $rules = [
            'title' => 'required|max:255',
            'file' => 'mimes:pdf|max:2048'
        ];

        $input = $request->all();

        $message = [];
        $validator = Validator::make($input, $rules, $message);
        $header = 200;
        $response = array();
        if ($validator->fails()) {
            $errors = $validator->errors();
            $response['errors'] = $errors;
            $response['error'] = true;
            $header = 402;
            //return redirect()->back()->withErrors($validator->errors())->withInput();
        } else {
            $prices = !empty($input["prices"]) ? $input["prices"] : array();
            $facilities = !empty($input["facilities"]) ? $input["facilities"] : array();
            $file = !empty($input["file"]) ? $input["file"] : null;
            $faqs = !empty($input["faqs"]) ? $input["faqs"] : null;
            WebsiteFaqs::saveFaqs("packages", $id, $faqs);
            unset($input["file"]);
            unset($input["faqs"]);
            unset($input["_token"]);
            unset($input["prices"]);
            unset($input["facilities"]);
            if (!isset($input["status"])) {
                $input["status"] = 0;
            }
            if (!isset($input["popular"])) {
                $input["popular"] = 0;
            }
            $slugify = slugify($input["title"]);
            $input["code"] = $slugify;
            $input["updated_at"] = date("Y-m-d H:i:s");
            if (!empty($request->image) && $request->image != null) {
                $media_id = Media::getMediaID($request->image);
                $input["image"] = $request->image;
                $input["image_media_id"] = $media_id;
            }
            if (!empty($request->file) && $request->file != null) {
                $destination = "uploads/packages/downloads";
                $fileName = $input["code"];
                $fileName = FileSystem::storeFile($fileName, $request->file, $destination);
                $input["file"] = $fileName;
            }           
            Packages::where('id', $id)->update($input);
            PackagePrices::where('package_id', $id)->delete();
            PackageFacilities::where('package_id', $id)->delete();
            $this->insertPrices($id, $prices);
            $this->insertFacilities($id, $facilities);

            \Session::flash('success', $this->heading . ' updated successfully!');
        }

        return response()->json($response, $header);
    }

    public function delete($id) {

        PackagePrices::where('package_id', $id)->delete();
        PackageFacilities::where('package_id', $id)->delete();
        Packages::where('id', $id)->delete();
        \Session::flash('error', $this->heading . ' deleted successfully!');
        return redirect('admin/' . $this->action);
    }

    public function show($id) {

        $q = new Packages();
        $data['model'] = $q->find($id);
        $data["title"] = $this->title;

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

        $data['breadcrumbs'] = $this->breadcrumbs;

        return view('admin/' . $this->folder . '/show', $data);
    }

}
