<?php

namespace MtcPharmacy\QualifyingAnswers\Http\Controllers\Admin;

use Illuminate\Http\Request;
use MtcPharmacy\QualifyingAnswers\Classes\QualifyingAnswersHelper;
use Illuminate\Support\Facades\Response;
use MtcPharmacy\QualifyingAnswers\Classes\QualifyingAnswer;
use MtcPharmacy\QualifyingAnswers\Classes\QualifyingAnswersGroup;
use MtcPharmacy\QualifyingAnswers\Classes\QualifyingAnswersGroupsConfig;


class ImportExportController extends \App\Http\Controllers\Controller
{

    public function download_templates()
    {
        $callback = function () {
            $rows = QualifyingAnswersHelper::downloadTemplates();

            $file = fopen('php://output', 'w');

            foreach ($rows as $row) {
                fputcsv($file, $row);
            }

            fclose($file);
        };

        $headers = array(
            "Content-type"        => "text/csv",
            "Pragma"              => "no-cache",
            "Cache-Control"       => "must-revalidate, post-check=0, pre-check=0",
            "Expires"             => "0"
        );

        return response()->streamDownload($callback, 'qualifying_answers_template.csv', $headers);
    }


    public function upsert(Request $request)
    {
        $result = [
            'success' => false,
            'errors' => [],
        ];


        $answers = $request->input('answers');
        foreach ($answers as $question_id => $answer) {
            $temp_answer = QualifyingAnswer::find($answer['id']);

            if ($temp_answer) {
                if (is_array($answer['qualifying_answer'])) {
                    $qa = json_encode($answer['qualifying_answer']);
                } else {
                    $qa = (string)$answer['qualifying_answer'];
                }
                $temp_answer->qualifying_answer = $answer['qualifying_answer'];
                $temp_answer->group_id = (int)$answer['group_id'];
                $temp_answer->save();
            }
        }


        $groups = $request->input('groups');
        foreach ($groups as $group) {
            $temp_group = QualifyingAnswersGroup::find($group['id']);
            if ($temp_group) {
                $temp_group->logic = $group['logic'];
                $temp_group->save();
            }
        }


        $groups_config = $request->input('groups_config');
        $temp_groups_config = QualifyingAnswersGroupsConfig::find($groups_config['id']);
        if ($temp_groups_config) {
            $temp_groups_config->logic = $groups_config['logic'];
            $temp_groups_config->save();
        }


        $result['success'] = true;

        return $result;
    }

}
