<?php

namespace Modules\PrintSuppliers\Controllers\Services;

use DB;
use Illuminate\Http\Request;
use Modules\PrintSuppliers\Controllers\Controller;

class PrintifyTemplateService extends Controller
{
    public function buildBlueprintDetail()
    {
        $directory = app_path('Modules/PrintSuppliers/scripts');
        $saveRoute = route('save-blueprint-detail');

        $blueprintIds = DB::table('printify_order_import_data')
            ->groupBy('blueprint_id')
            ->pluck('blueprint_id')
            ->toArray();

        chdir($directory);
        
        shell_exec('node get-printify-blueprint-detail.js ' . $saveRoute . ' ' . implode(' ', $blueprintIds) /* . ' > /dev/null 2>/dev/null &' */);
    
    }

    public function saveBlueprintDetail(Request $request)
    {
        $data = $request->input('blueprint');

        $data = [
            'blueprint_id' => $data['id'],
            'title' => $data['title'],
            'description' => $data['description'],
            'brand' => $data['brand'],
            'model' => $data['model'],
            'images' => json_encode($data['images']),
            'search' => $data['model'] . ' ' . $data['brand'] . ' ' . $data['title'] . ' ' . $data['id']
        ];

        $isEx = \DB::table('print_suppliers_printify_blueprint')->where('blueprint_id', $data['blueprint_id'])->first();

        if (!$isEx) {

            \DB::table('print_suppliers_printify_blueprint')->insert($data);
        }

        return [DB::table('print_suppliers_printify_blueprint')->where('blueprint_id', $data['blueprint_id'])->first()];

    }
}