<?php

use Mtc\Core\Models\SeoHeading;
use Mtc\Core\Models\SeoPage;
use Mtc\Shop\Brand;
use Mtc\Shop\Category;

/**
 * Seo csv class
 *
 * @author Lukas Giegerich | mtc.
 * @version 2014-01-20
 */
class SeoCSV extends Seo
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * echoes a csv of the given type (paths, brands or cats) to use for dl
     *
     * @param string $type
     */
    public static function csvPrint($type)
    {
        if ($type == 'paths') {
            $query = SeoPage::query()
                ->orderBy('path');
        } elseif ($type == 'brands') {
            $query = Brand::query()
                ->orderBy('id');
        } elseif ($type == 'categories') {
            $query = Category::query()
                ->select('id', 'name', 'seo_title', 'seo_description')
                ->orderBy('id');
        } elseif ($type == 'headings') {
            $query = SeoHeading::query()
                ->orderBy('id');
        } elseif ($type == 'redirects') {
            $query = SeoRedirect::query()
                ->orderBy('id');
        } else {
            return;
        }
        $records = $query->get()
            ->toArray();

        foreach ($records as $k => $data) {
            if (empty($k)) {
                $headers = array_keys($data);
                echo self::outPutCsv($headers);
            }
            echo self::outPutCsv($data);
        }
    }

    /**
     * The joy of fputcsv() returning a string
     *
     * @param array $array
     * @return string
     */
    private static function outPutCsv($array)
    {
        ob_start();
        $fp = fopen('php://output', 'w');
        fputcsv($fp, $array);
        fclose($fp);
        return ob_get_clean();
    }

    /**
     * Method to process csv file upload into respective SEO type
     *
     * @param string $type
     */
    public static function importCsv($type)
    {
        $lookup = array();
        if ($type === 'paths') {

            $lookup = [
                'id' => 'id',
                'title' => 'title',
                'description' => 'description',
            ];

        } elseif ($type === 'brands' || $type === 'categories') {
            $lookup = [
                'id' => 'id',
                'seo_title' => 'title',
                'seo_description' => 'description',
            ];
        } elseif ($type === "redirects") {
            $lookup = [
                'old_url' => 'old_url',
                'new_url' => 'new_url',
                'code' => 'code'
            ];
        }

        if (isset($_FILES['csv']) && $_FILES['csv']['size'] > 0) {

            if (($handle = fopen($_FILES['csv']['tmp_name'], 'r')) !== FALSE) {

                $first = true;
                $header_index = array();

                if ($type === 'redirects') {
                    SeoRedirect::query()->truncate();
                }

                while (($data = fgetcsv($handle, 0, ',')) !== FALSE) {
                    if ($first) {
                        $header_index = $data;
                        $first = false;
                        continue;
                    }

                    $params = array();
                    foreach ($data as $key => $value) {
                        if (isset($lookup[$header_index[$key]])) {
                            $params[':' . $lookup[$header_index[$key]]] = $value;
                        }
                    }

                    if ($type === 'paths') {

                        $page = SeoPage::query()
                            ->where('id', '=', $data[array_search('id', $header_index)])
                            ->orWhere('path', '=', $data[array_search('path', $header_index)])
                            ->first();

                        if (!empty($page) ) {

                            SeoPage::query()
                                ->where('id', '=', $page->id)
                                ->update([
                                    'title' => $data[array_search('title', $header_index)],
                                    'description' => $data[array_search('description', $header_index)]
                                ]);

                        } else {
                            SeoPage::query()
                                ->create([
                                    'title' => $data[array_search('title', $header_index)],
                                    'description' => $data[array_search('description', $header_index)],
                                    'path' => $data[array_search('path', $header_index)]
                                ]);
                        }

                    } elseif ($type === 'brands') {
                        Brand::query()
                            ->where('id', '=', $data[array_search('id', $header_index)])
                            ->update([
                                'seo_title' => $data[array_search('title', $header_index)],
                                'seo_description' => $data[array_search('description', $header_index)]
                            ]);

                    } elseif ($type === 'categories') {
                        Category::query()
                            ->where('id', '=', $data[array_search('id', $header_index)])
                            ->update([
                                'seo_title' => $data[array_search('title', $header_index)],
                                'seo_description' => $data[array_search('description', $header_index)]
                            ]);

                    } elseif ($type === 'redirects') {
                        $check_redirct = SeoRedirect::query()
                            ->where('old_url', '=', $data[array_search('old_url', $header_index)])
                            ->where('new_url', '=', $data[array_search('new_url', $header_index)])
                            ->count();

                        if ($check_redirct == 0) {
                            $params = [
                                'code' => $data[array_search('code', $header_index)],
                                'new_url' => $data[array_search('new_url', $header_index)],
                                'old_url' => $data[array_search('old_url', $header_index)]
                            ];

                            $redirect = new SeoRedirect();
                            $redirect->fill($params);
                            $redirect->save();
                        }
                    }
                }
                fclose($handle);
            }
        }

    }

}
