<?php

namespace App\Traits;


trait RecordInfoTrait
{

    public static function saveForItem(int $record_id)
    {
        $existing_info_records = self::query()
            ->where(self::RECORD_ID_FIELD_NAME, $record_id)
            ->get()
        ;

        $info_records = (array)($_REQUEST['info_record'] ?? []);
        $info_sort_order = 1;
        foreach ($info_records as $info_record_id => $info_record) {
            if ($info_record['type'] == 'existing') {
                $pi_line = self::find($info_record_id);
            } else {
                $pi_line = new self();
                $pi_line->{self::RECORD_ID_FIELD_NAME} = $record_id;
            }

            if ($pi_line) {
                $pi_line->title = $info_record['title'];
                $pi_line->is_content_itemised = isset($info_record['is_content_itemised']);
                $pi_line->content = $info_record['content'];
                $pi_line->order = $info_sort_order;
                $pi_line->save();

                $item_index_to_forget = $existing_info_records->search(function($line) use ($pi_line) {
                    return $line->id == $pi_line->id;
                });
                $existing_info_records->forget($item_index_to_forget);
            }
            $info_sort_order++;
        }

        foreach ($existing_info_records as $info_record) {
            $info_record->delete();
        }
    }


    public static function renderInfoRecordsForm(int $record_id)
    {
        $info_records = self::query()
            ->where(self::RECORD_ID_FIELD_NAME, $record_id)
            ->orderBy('order')
            ->get()
        ;

        $info_records_counter = 0;

        return app('twig')->render('shop/admin/info_records.twig', [
            'info_records' => $info_records,
        ]);
    }


    public static function getDisplayReadyData(int $record_id) : array
    {
        $data = [];

        $info_records = self::query()
            ->where(self::RECORD_ID_FIELD_NAME, $record_id)
            ->orderBy('order')
            ->get()
        ;

        foreach ($info_records as $info_record) {
            if (! $info_record->title) continue;

            $itemised_content = [];
            if ($info_record->is_content_itemised) {
                $itemised_content = explode(PHP_EOL, ($info_record->content));
            }

            $data[] = [
                'title'   => $info_record->title,
                'content' => $info_record->content,
                'content_itemised' => $itemised_content,
            ];
        }

        return $data;
    }
}
