<?php

namespace MtcPharmacy\QualifyingAnswers\Http\Controllers\Admin;

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

class ImportExportController extends \App\Http\Controllers\Controller
{
    public function download_templates()
    {
        $callback = function (): void {
            $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 $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;
    }
}
