<?php

namespace Modules\PrintSuppliers\Controllers\Services;

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

class ReportVerifierService extends Controller
{
    public function getVerifierReport($filters)
    {
        $query = DB::table('order')
            ->join('order_item', 'order_item.order_id', 'order.id')
            ->join('users', 'order.verifier_id', 'users.id')
            ->where('order.payment_status', 'PAID')
            ->whereNotNull('order.verifier_id')
            ->whereBetween('order.created_at', [$filters['from'], $filters['to']])
            ->leftJoin('order_meta', function($join) {
                $join->on('order_meta.order_id', '=', 'order.id');
                $join->where('order_meta.key', '=', 'is_ticket');
            })
            ->select([
                'order.id',
                'order.code',
                'order.status',
                'order.payment_status',
                'order.verifier_id',
                'order_item.product_id',
                'users.email',
                'order.created_at',
                'order_meta.value as is_ticket'
            ]);

        if (isset($filters['verifier_email']) && strpos($filters['verifier_email'], '@')) {

            $verifierId = -1;
            $verifier = DB::table('users')->where('email', $filters['verifier_email'])->first();
            
            if ($verifier) {
                $verifierId = $verifier->id;
            }

            $query->where('verifier_id', $verifierId);
        }

        $orders = $query->get();

        return $orders;
    }
}