<?php
namespace Modules\Seo\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Seo\Models\Hreflang;
use PHPExcel_IOFactory;

class HreflangController extends Controller {

    public function find(Request $request) {
        $retVal = ['status' => 'successful', 'result' => []];
        $pageId = (int) $request->input("page_id", 0);
        $pageSize = (int) $request->input("page_size", 20);

        $query = Hreflang::query();
        if ($request->has('url')) {
            $query->where('url', '=', trim($request->input('url')));
        }
        $queryCount = clone $query;
        $recordsCount = DB::table(DB::raw("(" . $queryCount->toSql() . ") AS x"))
                            ->mergeBindings($queryCount->getQuery())
                            ->count();
        $pagesCount = $this->recordsCountToPagesCount($recordsCount, $pageSize);
        $retVal['meta'] = [
            'page_id' => $pageId,
            'page_size' => $pageSize,
            'total_count' => $recordsCount,
            'page_count' => $pagesCount
        ];
        $retVal['result'] = $query->forPage($pageId + 1, $pageSize)->orderBy("created_at", "DESC")->get();

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

    public function save(Request $request) {
        $retVal = ['status' => 'fail', 'message' => 'Error!'];
        if ($request->has('content')) {
            $currentLocale = env('APP_LOCALE');
            if (empty($currentLocale)) {
                $currentLocale = 'us';
            } 

            $locales = $request->input('content');
            $url = null;
            if (key_exists($currentLocale, $locales)) {
                $url = $locales[$currentLocale];
            }
            if (!empty($url)) {
                $hreflang = Hreflang::query()->where('url', '=', $url)->first();
                if (empty($hreflang)) {
                    $hreflang = new Hreflang;
                }
                $hreflang->url = $url;
                $hreflang->content = json_encode($locales);
                $status = $hreflang->save();
                if ($status) {
                    $retVal = [
                        'status' => 'successful', 
                        'result' => Hreflang::query()->find($hreflang->id) 
                    ];
                }
            } 
        }
        return response()->json($retVal);
    }

    public function delete(Request $request) {
        $retVal = ['status' => 'fail', 'message' => 'Error!'];
        if ($request->has('content')) {
            $currentLocale = env('APP_LOCALE');
            if (empty($currentLocale)) {
                $currentLocale = 'us';
            } 

            $locales = $request->input('content');
            $url = null;
            if (key_exists($currentLocale, $locales)) {
                $url = $locales[$currentLocale];
            }
            if (!empty($url)) {
                $hreflang = Hreflang::query()->where('url', '=', $url)->first();
                if (!empty($hreflang->id)) {
                    $status = $hreflang->delete();
                    if ($status) {
                        $retVal = ['status' => 'successful', 'result' => $hreflang];
                    }
                }
            }
        }
        return response()->json($retVal);
    }

    public function import(Request $request) {
        $retVal = ['status' => 'fail', 'message' => 'Error!'];
        
        if ($request->hasFile('excelFile')) {
            $retVal = [ 'status' => 'successful', 'affectedRows' => 0 ];
            $ignoreKey = ['index', ''];
            $currentLocale = env('APP_LOCALE');
            if (empty($currentLocale)) {
                $currentLocale = 'us';
            } 
            
            $objPHPExcel = PHPExcel_IOFactory::load($request->file('excelFile'));
            $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
            $headings = array_shift($sheetData);

            foreach ($sheetData as $row) {
                $items = array_combine($headings, $row);

                $content = [];
                $url = null;
                foreach ($items as $key => $value) {
                    if (in_array($key, $ignoreKey)) continue;

                    $path = $this->_buildHrefangUrl($value);
                    if ($key == $currentLocale) {
                        $url = $path;
                    } 
                    $content[$key] = $path;
                }

                if (!empty($url)) {
                    $status = Hreflang::updateOrCreate([ 'url' => $url ], [ 'content' => json_encode($content) ]);
                    if ($status) {
                        $retVal['affectedRows']++;
                    }
                }
            }
        }

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

    private function _buildHrefangUrl($url) {
        $parseResult = parse_url($url);
        $retVal = $parseResult['path'];
        if (!empty($parseResult['query'])) {
            $retVal .= '?' . $parseResult['query'];
        }

        return $retVal;
    }

}



?>