<?php

namespace App\Jobs;

use App\Exports\PhyronExport;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Mtc\MercuryDataModels\SalesChannelHistory;

class PhyronExportJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->onQueue('export');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            $fileName = strtolower(str_replace(' ', '_', tenant()->name)) . '.csv';
            $export = new PhyronExport();

            Excel::store(
                $export,
                $fileName,
                'phyron-export'
            );

            // With SFTP accounts we need to check for file existing as put will not throw an error,
            // but exists check will throw an error on failure
            Storage::disk('phyron-export')->exists($fileName);
            SalesChannelHistory::store('phyron', true, $export->collection()->count() . ' records exported');
        } catch (Exception $exception) {
            SalesChannelHistory::store('phyron', false, $exception->getMessage());
        }
    }
}
