<?php

namespace Modules\Seo\Controllers;

use Illuminate\Support\Facades\Input;
use Module;
use Modules\Seo\Models\MetaData;
use PHPExcel;
use PHPExcel_IOFactory;

class MetaDataController extends Controller
{
    public function __construct()
    {
        Module::onView("content", function() {
            return "This is content view from Seo Module HomeController";
        }, 5);
    }

    public function find () {
        $pageId = Input::get('pageId', 0);
        $pageSize = Input::get('pageSize', 20);

        $query = MetaData::query();
        if(Input::has('url')) {
            $query->where('url', 'LIKE', '%'.Input::get('url').'%');
        }

        $recordCount = clone $query;
        $pagesCount = $this->recordsCountToPagesCount($recordCount->count(), $pageSize);
        if (Input::get('export') === 'excel') {
            $items = $query->orderBy("id", "desc")->get();
            $this->exportExcel($items);
        } else {
            $items = $query->orderBy("id", "desc")->forPage($pageId + 1, $pageSize)->get();
        }

        $response = array(
            "status" => 'successful',
            "items" => $items,
            'pagesCount' => $pagesCount,
            'pageId' => $pageId
        );
        return response()->json($response);
    }

    private function exportExcel($datas = []) {
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setCreator(getOption('general.store_name', 'Printerval'))->setLastModifiedBy("System")
            ->setTitle("List Meta Data")->setSubject("Meta Data")->setDescription("Meta Data")->setKeywords("Template excel");
        $objPHPExcel->setActiveSheetIndex(0);
        $itemFormat = array('A1', 'B1', 'C1', 'D1', 'E1', 'F1', 'G1', 'H1', 'I1');
        $objPHPExcel->getDefaultStyle()->getFont()->setName('Times New Roman')->setSize(12);
        $objPHPExcel->getActiveSheet()->SetCellValue('A1', "STT");
        $objPHPExcel->getActiveSheet()->SetCellValue('B1', "Link");
        $objPHPExcel->getActiveSheet()->SetCellValue('C1', "Meta Title");
        $objPHPExcel->getActiveSheet()->SetCellValue('D1', "Meta Keywords");
        $objPHPExcel->getActiveSheet()->SetCellValue('E1', "Meta Description");
        $objPHPExcel->getActiveSheet()->SetCellValue('F1', "Content");
        $objPHPExcel->getActiveSheet()->SetCellValue('G1', "Content Footer");
        $objPHPExcel->getActiveSheet()->SetCellValue('H1', "Heading");
        $objPHPExcel->getActiveSheet()->SetCellValue('I1', "Canonical");
        $objPHPExcel->getActiveSheet()->SetCellValue('J1', "Ngày tạo");
        foreach ($itemFormat as $value) {
            $objPHPExcel->getActiveSheet()->getStyle($value)->getFont()->setSize(12)->setBold(true);
        }
        $i = 1;
        foreach ($datas as $index => $item) {
            $i++;
            $objPHPExcel->getActiveSheet()->SetCellValue('A' . $i, $index + 1);
            $objPHPExcel->getActiveSheet()->SetCellValue('B' . $i, $item->url);
            $objPHPExcel->getActiveSheet()->SetCellValue('C' . $i, $item->meta_title);
            $objPHPExcel->getActiveSheet()->SetCellValue('D' . $i, $item->meta_keywords);
            $objPHPExcel->getActiveSheet()->SetCellValue('E' . $i, $item->meta_description);
            $objPHPExcel->getActiveSheet()->SetCellValue('F' . $i, $item->content);
            $objPHPExcel->getActiveSheet()->SetCellValue('G' . $i, $item->content_footer);
            $objPHPExcel->getActiveSheet()->SetCellValue('H' . $i, $item->heading);
            $objPHPExcel->getActiveSheet()->SetCellValue('I' . $i, $item->canonical);
            $objPHPExcel->getActiveSheet()->SetCellValue('J' . $i, date("d/m/Y H:i", strtotime($item->created_at)));
        }
        $writer = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="List_Meta_Data_' . time() . '.xlsx"');
        header('Cache-Control: max-age=0');
        $writer->save('php://output');
        exit;
    }

    public function save () {
        $response = array('status' => 'fail');
        $id = Input::get('id');
        if(!empty($id)) {
            $data = MetaData::findOrFail($id);
        } else {
            $data = new MetaData;
        }
        $checkQuery = MetaData::where('url', '=', Input::get('url'));
        if ($id) {
            $checkQuery->where('id', '!=', $id);
        }
        if(
            $data->url != Input::get('url') && $checkQuery->exists()
        ) {
            $response['message'] = 'Đã tồn tại đường dẫn này. Vui lòng kiểm tra lại...';
            return response()->json($response);
        } else {
            $data->url = Input::get('url');
        }

        if(Input::has('metaTitle')) {
            $data->meta_title = Input::get('metaTitle');
        }

        if(Input::has('metaKeywords')) {
            $data->meta_keywords = Input::get('metaKeywords');
        }

        if(Input::has('metaDescription')) {
            $data->meta_description = Input::get('metaDescription');
        }

        if(Input::has('content')) {
            $data->content = Input::get('content');
        }
        if(Input::has('content_footer')) {
            $data->content_footer = Input::get('content_footer');
        }

        if(Input::has('heading')) {
            $data->heading = Input::get('heading');
        }
        if(Input::has('canonical')) {
            $data->canonical = Input::get('canonical');
        }

        if(Input::has('is_generate_content_footer')) {
            $data->is_generate_content_footer = Input::get('is_generate_content_footer');
        }

        $status = $data->save();
        if($status) {
            $response = array(
                'status' => 'successful',
                'result' => $data,
                'message' => 'successful'
            );
        }
        return response()->json($response);
    }

    public function delete() {
        $id = Input::get('id');
        $response = array('status' => 'fail');
        if(!empty($id)) {
            $url = MetaData::findOrFail($id);
            $url->delete();
            $response = array('status' => 'successful', 'message' => 'successful');
        }
        return response()->json($response);
    }

    public function import() {
        $response = array('status' => 'fail');
        if (Input::hasFile('excelFile')) {
            $data = PHPExcel_IOFactory::load(Input::file('excelFile'));
            $sheetData = $data->getActiveSheet()->toArray(null, true, true, true);
            if (isset($sheetData[1])) {
                unset($sheetData[1]);
            }
            if (!empty($sheetData)) {
                $response = array('status' => 'successful', 'message' => 'successful');
                $dataInsert = []; 
                $affectedRow = 0;
                $currentLocale = env('APP_LOCALE');
                if (empty($currentLocale)) {
                    $currentLocale = 'us';
                }
                foreach ($sheetData as $key => $item) {
                    if ($item['B'] != $currentLocale) {
                        continue;
                    }

                    if (empty($item['C'])) continue;
                    $url = $item['C'];
                    $canonical = $item['I'] ? $item['I'] : null;

                    $existMetaData = MetaData::where('url', '=', $url)->first();
                    if (!$existMetaData) {
                        array_push($dataInsert, [
                            'url' => $url,
                            'meta_title' => (!empty($item['D'])) ? $item['D'] : NULL,
                            'meta_keywords' => (!empty($item['E'])) ? $item['E'] : NULL,
                            'meta_description' => (!empty($item['F'])) ? $item['F'] : NULL,
                            'content' => (!empty($item['G'])) ? $item['G'] : NULL,
                            'heading' => (!empty($item['H'])) ? $item['H'] : NULL,
                            'canonical' => $canonical,
                            'created_at' => date('Y-m-d H:i:s'),
                            'updated_at' => date('Y-m-d H:i:s'),
                            'content_footer' => (!empty($item['J'])) ? $item['J'] : NULL,
                            'is_generate_content_footer' => (!empty($item['K'])) ? $item['K'] : NULL,
                        ]);
                    } else {
                        $existMetaData->meta_title = (!empty($item['D'])) ? $item['D'] : NULL;
                        $existMetaData->meta_keywords = (!empty($item['E'])) ? $item['E'] : NULL;
                        $existMetaData->meta_description = (!empty($item['F'])) ? $item['F'] : NULL;
                        $existMetaData->content = (!empty($item['G'])) ? $item['G'] : NULL;
                        $existMetaData->content_footer = (!empty($item['J'])) ? $item['J'] : NULL;
                        $existMetaData->heading = (!empty($item['H'])) ? $item['H'] : NULL;
                        $existMetaData->canonical = $canonical;
                        $existMetaData->is_generate_content_footer = (!empty($item['K'])) ? $item['K'] : NULL;
                        $status = $existMetaData->save();
                        if ($status) $affectedRow++;
                    }
                }
                if (!empty($dataInsert)) {
                    MetaData::insert($dataInsert);
                    $affectedRow += count($dataInsert);
                }
                $response['affectedRow'] = $affectedRow;
            }
        }

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

    public function dialogFaq()
    {
        return view('seo::admin.meta-data.dialog-faq');
    }

}
