<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreExportMap;
use App\Http\Requests\UpdateExportMap;
use App\Http\Resources\ExportMapResource;
use App\Models\ExportMap;
use Illuminate\Http\Response;

class ExportMapController extends Controller
{
    public function index()
    {
        return ExportMap::query()->paginate();
    }

    public function store(StoreExportMap $request): ExportMapResource
    {
        return new ExportMapResource(ExportMap::query()
            ->create([
                'name' => $request->input('name'),
                'type' => $request->input('type'),
            ]));
    }

    public function show(ExportMap $exportMap): ExportMapResource
    {
        return new ExportMapResource($exportMap);
    }

    public function update(UpdateExportMap $request, ExportMap $exportMap): ExportMapResource
    {
        $exportMap->fill([
            'name' => $request->input('name'),
            'active' => $request->input('active'),
            'format' => $request->input('format'),
            'include_header_row' => $request->input('include_header_row'),
            'export_time' => $request->input('export_time'),
            'export_day_of_week' => $request->input('export_day_of_week'),
            'export_day_of_month' => $request->input('export_day_of_month'),
            'schedule' => $request->input('schedule'),
            'schedule_enabled' => $request->input('schedule_enabled'),
            'next_due_at' => $request->input('next_due_at'),
            'conditions' => $request->input('conditions', []),
            'columns' => $request->input('columns', []),
            'headers' => $request->input('headers', []),
            'mapping_rules' => $request->input('mapping_rules', []),
            'ftp_export_enabled' => $request->input('ftp_export_enabled'),
            'driver' => $request->input('driver'),
            'host' => $request->input('host'),
            'port' => $request->input('port'),
            'root' => $request->input('root'),
            'username' => $request->input('username'),
            'password' => $request->input('password'),
            'filename' => $request->input('filename'),
            'template_id' => $request->input('template_id'),
            'config' => $request->input('config', []),
        ]);

        $exportMap->setSchedule();

        $exportMap->save();

        return new ExportMapResource($exportMap);
    }

    public function destroy(ExportMap $exportMap)
    {
        $exportMap->delete();

        return response('ok');
    }

    public function getForModel(string $model): Response
    {
        return response([
            'types' => ExportMap::query()
                ->where('type', $model)
                ->active(1)
                ->select('id', 'name')
                ->get()
                ->prepend([
                    'id' => '',
                    'name' => 'Autonomy export file'
                ])
        ]);
    }
}
