<?php

namespace Aura\Export\Traits;

trait Exportable
{
    public function export()
    {
        $post = $this->toArray()['fields'];

        $filename = 'post_'.$this->id.'.csv';
        $filepath = storage_path('exports/'.$filename);

        if (! file_exists(dirname($filepath))) {
            mkdir(dirname($filepath), 0777, true);
        }

        $handle = fopen($filepath, 'w');

        fputcsv($handle, array_keys($post));
        fputcsv($handle, array_values($post));

        fclose($handle);

        return $filepath;
    }

    public function multipleExportSelected($posts)
    {
        // $this->export();

        // dd($posts);
        $filename = 'posts_'.date('YmdHis').'.csv';
        $filepath = storage_path('exports/'.$filename);

        if (! file_exists(dirname($filepath))) {
            mkdir(dirname($filepath), 0777, true);
        }

        $handle = fopen($filepath, 'w');

        foreach ($posts as $post) {
            $data = $post->toArray()['fields'];
            if (empty($header)) {
                $header = array_keys($data);
                fputcsv($handle, $header);
            }
            fputcsv($handle, array_values($data));
        }

        fclose($handle);

        // open a modal and return the filepath in it
        // emit openModal event
        $this->emit('openModal', [
            'name' => 'export::export-selected-modal',
            'data' => [
                'filepath' => $filepath,
            ],
        ]);

    }
}
