<?php

namespace Modules\PrintSuppliers\Controllers;

use Illuminate\Http\Request;
use Modules\PrintSuppliers\Controllers\Controller;
use Modules\PrintSuppliers\Models\Order;
use Illuminate\Support\Facades\Config;

class CronController extends Controller
{
    public function webhook(Request $request) {
        set_time_limit(3600);
        ini_set('memory_limit', '1024M');
        $retVal = ['status' => 'successful', 'affectedRows' => 0];
        if ($request->has('printing_code')) {
            $printingCode = $request->input('printing_code');
            $items = Order::query()
                        ->join('order_item', 'order_item.order_id', '=', 'order.id')
                        ->whereIn('order.status', ['PROCESSING', 'PENDING'])
                        ->whereNotNull('order_item.resource_id')
                        ->whereNotNull('order_item.store_id')
                        ->where('order_item.printing_code', $printingCode)
                        ->where('order.created_at', '>=', date('Y-m-d H:i:s', strtotime('-10 day')))
                        ->select(['order.id', 'order_item.resource_id', 'order_item.store_id'])
                        ->distinct()
                        ->get();
            
            if ($printingCode == 'printify') {
                // $shopIds = array_keys(Config::get('print-suppliers::connection.printify.accounts'));
 
                foreach ($items as $item) {
                    $sampleData = [
                        "id" => "cron-webhook-" . time(),
                        "type" => "order:updated",
                        "created_at" => date('c'),
                        "resource" => [
                            "id" => $item->resource_id,
                            "type" => "order",
                            "data" => [
                                "shop_id" => $item->store_id,
                                "status" => "fulfilled"
                            ]
                        ]
                    ];
                    $this->triggerAsyncRequest(route('print-suppliers::webhook::printify'), $sampleData, 'POST');
                    $retVal['affectedRows']++;  
                }
            }
        }

        return response()->json($retVal); 
    }
}