<?php
namespace Modules\PrintSuppliers\Controllers;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Modules\Pod\Helpers\DBConnect;
use Modules\PrintSuppliers\Models\Profile;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use DB;
use Modules\PrintSuppliers\Controllers\Services\ReportVerifierService;

class ReportController extends Controller
{

    const STATUS_SUCCESSFUL = 'successful';
    const STATUS_FAIL = 'fail';

    public function reportPrintProfiles(Request $request)
    {
        $type = $request->input('type', 'printify');
        $countPrintProfile = Profile::query()->where('type', $type)->count();

        $limit = 5000;
        $offset = 0;
        $pageCount = ceil($countPrintProfile / $limit);

        $reportRows = [];
        for ($i = 0; $i < $pageCount; $i ++) {
            $profiles = Profile::query()
                ->select([
                    'printing_profile.product_sku_id',
                    'printing_profile.blueprint_id',
                    'printing_profile.print_provider_id',
                    'printing_profile.variant_id',
                    'printing_profile.options',
                    'printing_profile.position',
                    'product_sku.product_id',
                    'product_info.variants'
                ])
                ->where('type', $type)
                ->join('product_sku', 'printing_profile.product_sku_id', '=', 'product_sku.id')
                ->join('product_info', 'product_info.product_sku_id', '=', 'product_sku.id')
                ->skip($offset)
                ->take($limit)
                ->get();

            $productIds = [];
            for ($j = 0; $j < count($profiles); $j++) {
                $productIds[$profiles[$j]->product_id] = $profiles[$j]->product_id;
            }
            $productIds = array_values($productIds);

            $productNCateogry = DB::table('product_n_category')
                ->whereIn('product_id', $productIds)
                ->get();

            $productCategories = [];
            foreach ($productNCateogry as $prodNCate) {
                if (!isset($productCategories[$prodNCate->product_id]))
                    $productCategories[$prodNCate->product_id] = [];

                $productCategories[$prodNCate->product_id][] = $prodNCate->category_id;
            }

            foreach ($profiles as $key => $value) {
                $row = [
                    'product_sku_id' => $value->product_sku_id,
                    'blueprint_id' => $value->blueprint_id,
                    'print_provider_id' => $value->print_provider_id,
                    'variant_id' => $value->variant_id
                ];
                $row = array_merge($row, $value->options);

                $variants = explode(', ', $value->variants);
                $variantsRow = [];
                foreach ($variants as $variant) {
                    $variantParts = explode(': ', $variant);
                    if (isset($variantParts[0]) && isset($variantParts[1])) {
                        $variantsRow = array_merge($variantsRow, [
                            $variantParts[0] => $variantParts[1]
                        ]);
                    }
                }

                $rVariant = [];
                foreach (['Type', 'Style', 'Color', 'Size'] as $k) {
                    if(isset($variantsRow[$k])) {
                        $rVariant[$k] = $variantsRow[$k];
                    } else {
                        $rVariant[$k] = ' ';
                    }
                }

                $row = array_merge($row, $rVariant);

                if (isset($productCategories[$value->product_id])) {
                    foreach ($productCategories[$value->product_id] as $index => $cateId) {
                        $row['CATEGORY_ID_' . ($index + 1)] = $cateId;
                    }
                }

                $reportRows[] = $row;
            }

            $offset += count($profiles);
        }

        header("Content-type: text/csv");
        header("Cache-Control: no-store, no-cache");
        header('Content-Disposition: attachment; filename="content.csv"');

        $out = fopen('php://output', 'w');
        foreach ($reportRows as $runer => $fields) {
            if ($runer == 0) {
                fputcsv($out, array_keys($fields));
            }

            $outRow = [];
            $fields = array_values($fields);
            for ($run1 = 0; $run1 < 20; $run1++) {
                if (isset($fields[$run1]) && $fields[$run1]) {
                    $outRow[] = $fields[$run1];
                } else $outRow[] = '';
            }
            fputcsv($out, $outRow);
        }
        fclose($out);
    }

    public function printifyReport(Request $request) {
        return view('print-suppliers::report.printify');
    }

    public function printifyPaymentTransaction(Request $request) {
        $retVal = [ 'status' => 'fail' ];
        $token = $request->input('token', null);
        $endPoint = "https://printify.com/api/v1/payment_transactions";
        $limit = $request->input('limit', -1);
        $firstPage = 1;
        $lastPage = 0;
        $transactions = [];

        do {
            $params = http_build_query([
                'page' => $firstPage,
                'limit' => 200,
                'sort' => '-created_at',
                'type' => 'all'
            ]);
            $response = $this->triggerSyncRequest("$endPoint?$params", 'GET', [], [
                'Authorization: Bearer ' . $token
            ]);
            if (isset($response['error'])) {
                return response()->json(array_merge($retVal, $response));
            }
            if (!empty($response['data']) && is_array($response['data'])) {
                $transactions = array_merge($transactions, $response['data']);
            }
            if ($limit > 0 && count($transactions) > $limit) {
                break;
            }
            if (!empty($response['last_page'])) {
                $lastPage = $response['last_page'];
            }
            $firstPage = $firstPage + 1;
        } while ($firstPage <= $lastPage);

        $spreadsheet = new Spreadsheet();
        $spreadsheet->getDefaultStyle()->getFont()->setName('Times New Roman')->setSize(12);
        $headers = [
            'A1' => 'Index',
            'B1' => 'OrderID',
            'C1' => 'Order/Type',
            'D1' => 'Order Cost',
            'E1' => 'Order Cost Shipping',
            'F1' => 'Order Cost Tax',
            'G1' => 'Date',
            'H1' => 'Method',
            'I1' => 'Amount, USD',
            'J1' => 'Balance After, USD',
        ];
        $styleArray = [
            'font' => [
                'bold' => true,
            ],
        ];
        foreach ($headers as $cell => $content) {
            $spreadsheet->getActiveSheet()->setCellValue($cell, $content);
            $spreadsheet->getActiveSheet()->getStyle($cell)->applyFromArray($styleArray);
        }

        $startRow = 1;
        foreach ($transactions as $index => $transaction) {
            $startRow++;
            $spreadsheet->getActiveSheet()->setCellValue("A$startRow", $index + 1);
            if (isset($transaction['metadata'])) {
                if (isset($transaction['metadata']['order_id'])) {
                    $spreadsheet->getActiveSheet()->setCellValue("B$startRow", $transaction['metadata']['order_id']);
                }
                if (isset($transaction['metadata']['user_order_id'])) {
                    $spreadsheet->getActiveSheet()->setCellValue("C$startRow", '#' . $transaction['metadata']['user_order_id']);
                } else if (isset($transaction['type'])) {
                    $spreadsheet->getActiveSheet()->setCellValue("C$startRow", $transaction['type']);
                }
                if (isset($transaction['metadata']['amount_cost_production'])) {
                    $spreadsheet->getActiveSheet()->setCellValue("D$startRow", $transaction['metadata']['amount_cost_production'] / 100);
                }
                if (isset($transaction['metadata']['amount_cost_shipping'])) {
                    $spreadsheet->getActiveSheet()->setCellValue("E$startRow", $transaction['metadata']['amount_cost_shipping'] / 100);
                }
                if (isset($transaction['metadata']['amount_cost_tax'])) {
                    $spreadsheet->getActiveSheet()->setCellValue("F$startRow", $transaction['metadata']['amount_cost_tax'] / 100);
                }
            }
            $spreadsheet->getActiveSheet()->setCellValue("G$startRow", $transaction['created_at']);
            $spreadsheet->getActiveSheet()->setCellValue("H$startRow", $transaction['method']);
            $spreadsheet->getActiveSheet()->setCellValue("I$startRow", $transaction['amount'] / 100);
            $spreadsheet->getActiveSheet()->setCellValue("J$startRow", $transaction['after'] / 100);
        }
        ob_end_clean();
        $fileName = "Printify_Payment_Transaction_".time().'.xlsx';
        header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
        header("Pragma: no-cache");
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$fileName.'"');
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        exit;

    }

    public function gelatoReport(Request $request) {
        return view('print-suppliers::report.gelato');
    }

    public function gelatoPaymentTransaction(Request $request) {
        set_time_limit(-1);
        $retVal = [ 'status' => 'fail' ];
        $wallet = $request->input('wallet', 'a1737f53-db23-4986-91cc-0e74474bf732');
        if ($request->has('token') && $request->has('createdAtBefore') && $request->has('createdAtAfter')) {
            $endPoint = "https://dashboard.gelato.com/api/payments/v1/wallets/$wallet/transactions:search";

            $createdAtAfter = $request->input('createdAtAfter') . date("\TH:i:s.000\Z");
            $createdAtBefore = $request->input('createdAtBefore') . date("\TH:i:s.000\Z");

            $limit = 200;
            $offset = 0;
            $transactions = [];
            $total = 0;
            do {
                $response = $this->triggerSyncRequest($endPoint, 'POST', [
                    'createdAtBefore' => $createdAtBefore,
                    'createdAtAfter' => $createdAtAfter,
                    'offset' => $offset,
                    'limit' => $limit
                ], [
                    'Authorization: ' . trim($request->input('token')),
                    'Content-Type: application/json'
                ]);
                $offset = $offset + $limit;

                if (!empty($response['code']) && $response['code'] == 'access_invalid') {
                    $retVal = $response;
                    break;
                } else if (!empty($response['transactions'])) {
                    $transactions = array_merge($transactions, $response['transactions']);
                }
                if (!empty($response['total'])) {
                    $total = $response['total'];
                }
            } while (count($transactions) < $total);

            // echo '<p>' . $total . '</p>';
            // echo '<pre>'; print_r($transactions); echo '</pre>'; exit;

            if (!empty($transactions)) {
                $spreadsheet = new Spreadsheet();
                $spreadsheet->getDefaultStyle()->getFont()->setName('Times New Roman')->setSize(12);
                $headers = [
                    'A1' => 'Index',
                    'B1' => 'Transaction ID',
                    'C1' => 'Order Reference ID',
                    'D1' => 'Type',
                    'E1' => 'Amount',
                    'F1' => 'Balance at the time',
                    'G1' => 'Date',
                    'H1' => 'Balance Before',
                    'I1' => 'Balance After',
                    'J1' => 'Currency',
                ];
                $styleArray = [
                    'font' => [
                        'bold' => true,
                    ],
                ];
                foreach ($headers as $cell => $content) {
                    $spreadsheet->getActiveSheet()->setCellValue($cell, $content);
                    $spreadsheet->getActiveSheet()->getStyle($cell)->applyFromArray($styleArray);
                }

                $startRow = 1;
                $currentRatio = 100;
                foreach ($transactions as $index => $transaction) {
                    if ($transaction['currencyIsoCode'] == 'JPY') {
                        $currentRatio = 1;
                    }
                    $createTime = new \DateTime($transaction['createdAt'], new \DateTimeZone('UTC'));
                    $createTime->setTimezone(new \DateTimeZone('Asia/Ho_Chi_Minh'));

                    $startRow++;
                    $spreadsheet->getActiveSheet()->setCellValue("A$startRow", $index + 1);
                    $spreadsheet->getActiveSheet()->setCellValue("B$startRow", $transaction['walletTransactionUid']);
                    $spreadsheet->getActiveSheet()->setCellValue("C$startRow", $transaction['orderReference']);
                    $spreadsheet->getActiveSheet()->setCellValue("D$startRow", $transaction['type']);
                    $spreadsheet->getActiveSheet()->setCellValue("E$startRow", $transaction['amountInMinorUnits'] / $currentRatio);
                    $spreadsheet->getActiveSheet()->setCellValue("F$startRow", $transaction['walletBalanceAfter'] / $currentRatio);
                    $spreadsheet->getActiveSheet()->setCellValue("G$startRow", $createTime->format('Y-m-d H:i:s'));
                    $spreadsheet->getActiveSheet()->setCellValue("H$startRow", $transaction['walletBalanceBefore'] / $currentRatio);
                    $spreadsheet->getActiveSheet()->setCellValue("I$startRow", $transaction['walletBalanceAfter'] / $currentRatio);
                    $spreadsheet->getActiveSheet()->setCellValue("J$startRow", $transaction['currencyIsoCode']);
                }
                ob_end_clean();
                $fileName = "Gelato_Payment_Transaction_".time().'.xlsx';
                header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
                header("Pragma: no-cache");
                header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
                header('Content-Disposition: attachment;filename="'.$fileName.'"');
                $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
                $writer->save('php://output');
                exit;
            }
            
            
        } else {
            $retVal['message'] = 'token, createdAtBefore, createdAtBefore params required.';
        }
        return response()->json($retVal);
    }

    public function reportStuckOrders(Request $request)
    {
        $markets = $this->getActiveMarkets();
        $stuckOrders = [];
        $stopDate = $request->input('stop_date', null);
        $autoFulfillOnly = $request->input('auto_fulfill_only');

        foreach ($markets as $market => $value) {
            if ($autoFulfillOnly) {
                $stuckOrders[$market] = $this->getStuckAutoFulfillOrderByMarket($market, $stopDate);
            } else {
                $stuckOrders[$market] = $this->getStuckOrderByMarket($market, $stopDate);
            }
        }

        return [
            'result' => $stuckOrders
        ];
    }

    private function getStuckAutoFulfillOrderByMarket($market, $stopDate = null)
    {
        $connection = DBConnect::connect($market);
        $orders = [];

        $reportDays = 5; // +1
        $date = new Carbon();
        $date = $date->now()->subDays($reportDays);

        if ($stopDate) {
            $date = Carbon::createFromFormat('Y-m-d', $stopDate)->subDays($reportDays);
        }

        for ($i = $reportDays; $i >= 0; $i--) {
            $reportDateStart = clone $date;
            $reportDateEnd = clone $date;

            $reportDateStart->startOfDay();
            $reportDateEnd->endOfDay();
            if ($i == 0) {
                $reportDateEnd->hour(17);
                $reportDateEnd->minute(0);
                $reportDateEnd->second(0);
            }

            $orderQ = $connection->table('order')
                ->where('order.status', 'PROCESSING')
                ->where('order.payment_status', 'paid')
                ->where('order.verifier_id', 1)
                ->join('order_meta', 'order_meta.order_id', 'order.id')
                ->where('order_meta.key', 'is_auto_fulfill')
                ->whereIn('order_meta.value', [1, 5])
                ->whereBetween('order.created_at', [$reportDateStart, $reportDateEnd]);

            $orderIds = $orderQ->pluck('order.id')->toArray();

            // get order ticket
            $orderTicketOpening = DBConnect::connect('central')->table('ticket_n_order')
                ->select(['ticket_n_order.order_id'])
                ->whereIn('ticket_n_order.order_id', $orderIds)
                ->join('ticket', 'ticket.id', '=', 'ticket_n_order.ticket_id')
                ->where('ticket.locate', $market)
                ->whereIn('ticket.status', ['open', 'waiting_customer'])
                ->pluck('ticket_n_order.order_id')
                ->toArray();

            $dateOrders = $orderQ
                ->select(['order.id'])
                ->whereNotIn('order.id', $orderTicketOpening)
                ->groupBy('order.id')
                ->get();

            $orderIds = [];
            for ($j = 0; $j < count($dateOrders); $j++) {
                $orderIds[] = $dateOrders[$j]->id;
            }

            $orderItems = $connection->table('order_item')->whereIn('order_id', $orderIds)
                ->select(['order_id', 'quantity'])
                ->get();

            $orderItemsCount = [];
            foreach ($orderItems as $item) {
                if (!isset($orderItemsCount[$item->order_id])) {
                    $orderItemsCount[$item->order_id] = 0;
                }
                $orderItemsCount[$item->order_id] += $item->quantity;
            }

            foreach ($dateOrders as &$order) {
                $order->countProd = 0;
                if (isset($orderItemsCount[$order->id])) {
                    $order->countProd = $orderItemsCount[$order->id];
                }
            }

            $orders[$reportDateEnd->toDateString()] = $dateOrders;

            $date->addHour(24);
        }

        return $orders;
    }

    private function getStuckOrderByMarket($market, $stopDate = null)
    {
        $connection = DBConnect::connect($market);
        $orders = [];

        $reportDays = 5; // +1
        $date = new Carbon();
        $date = $date->now()->subDays($reportDays);

        if ($stopDate) {
            $date = Carbon::createFromFormat('Y-m-d', $stopDate)->subDays($reportDays);
        }

        for ($i = $reportDays; $i >= 0; $i--) {
            $reportDateStart = clone $date;
            $reportDateEnd = clone $date;

            $reportDateStart->startOfDay();
            $reportDateEnd->endOfDay();
            if ($i == 0) {
                $reportDateEnd->hour(17);
                $reportDateEnd->minute(0);
                $reportDateEnd->second(0);
            }

            $orderQ = $connection->table('order')
                ->where('order.status', 'PROCESSING')
                ->where('order.payment_status', 'paid')
                ->whereBetween('order.created_at', [$reportDateStart, $reportDateEnd]);

            $orderIds = $orderQ->pluck('order.id')->toArray();

            $orderMetas = $connection->table('order_meta')
                ->whereIn('order_id', $orderIds)
                ->get();

            $ignoreIds = [];
            for ($j = 0; $j < count($orderMetas); $j++) {
                if ($orderMetas[$j]->key == 'is_auto_fulfill' && !in_array($orderMetas[$j]->value, [0, 2])) {
                    $ignoreIds[] = $orderMetas[$j]->order_id;
                }
            }
            $ignoreIds = array_unique($ignoreIds);

            // get order ticket
            $orderTicketOpening = DBConnect::connect('central')->table('ticket_n_order')
                ->select(['ticket_n_order.order_id'])
                ->whereIn('ticket_n_order.order_id', $orderIds)
                ->join('ticket', 'ticket.id', '=', 'ticket_n_order.ticket_id')
                ->where('ticket.locate', $market)
                ->whereIn('ticket.status', ['open', 'waiting_customer'])
                ->pluck('ticket_n_order.order_id')
                ->toArray();

            $dateOrders = $orderQ
                ->select(['order.id'])
                ->whereNotIn('order.id', array_merge($ignoreIds, $orderTicketOpening))
                ->groupBy('order.id')
                ->get();

            $orderIds = [];
            for ($j = 0; $j < count($dateOrders); $j++) {
                $orderIds[] = $dateOrders[$j]->id;
            }

            $orderItems = $connection->table('order_item')->whereIn('order_id', $orderIds)
                ->select(['order_id', 'quantity'])
                ->get();

            $orderItemsCount = [];
            foreach ($orderItems as $item) {
                if (!isset($orderItemsCount[$item->order_id])) {
                    $orderItemsCount[$item->order_id] = 0;
                }
                $orderItemsCount[$item->order_id] += $item->quantity;
            }

            foreach ($dateOrders as &$order) {
                $order->countProd = 0;
                if (isset($orderItemsCount[$order->id])) {
                    $order->countProd = $orderItemsCount[$order->id];
                }
            }

            $orders[$reportDateEnd->toDateString()] = $dateOrders;

            $date->addHour(24);
        }

        return $orders;
    }

    public function indexFeedbackIssue(Request $request)
    {
        return view('print-suppliers::report.feedback-issues');
    }

    public function reportOrderItemFeedbackIssues(Request $request)
    {
        $dateFrom = date('Y-m-d 00:00:00', $request->input('dateFrom'));
        $dateTo = date('Y-m-d 23:59:59', $request->input('dateTo'));
    
        $retVal = ['status' => 'successful', 'data' => []];

        list($reportData, $reportDataByCategory) = $this->getFeedbackItems($dateFrom, $dateTo);

        $flatReportDataByCategory = [];
        foreach ($reportDataByCategory as $category => $feedbacks) {
            $index = 0;
            $countFeedback = count($feedbacks);
            foreach ($feedbacks as $feedbackName => $value) {
                $flatReportDataByCategory[] = [
                    'index' => $index,
                    'count_fb' => $countFeedback,
                    'category' => $category,
                    'feedback' => $feedbackName,
                    'value' => $value
                ];
                $index++;
            }
        }

        $flatReportData = [];
        foreach ($reportData as $printProvider => $printProviderData) {
            $index = 0;
            $countIssueType = count($printProviderData['issues']);
            $countOrders = count($printProviderData['order_ids']);
            foreach ($printProviderData['issues'] as $issueName => $value) {
                $flatReportData[] = [
                    'index' =>  $index,
                    'print_provider_name' => $printProvider,
                    'total_item' => $printProviderData['total_item'],
                    'total_order' => $countOrders,
                    'issue_name' => $issueName,
                    'issue_product_count' => $value['count'],
                    'percent' => $value['percent'],
                    'avg_issue_percent' => $printProviderData['avg_issue_percent'],
                    'count_issue_type' => $countIssueType
                ];
                $index++;
            }
        }

        return [
            'report_data' => $flatReportData,
            'report_data_category' => $flatReportDataByCategory,
        ];
    }

    private function getFeedbackItems($dateFrom, $dateTo)
    {
        $orderItems = DB::table('order_item')
            ->join('product_n_category', 'product_n_category.product_id', 'order_item.product_id')
            ->join('order', 'order.id', 'order_item.order_id')
            ->join('category', 'product_n_category.category_id', '=', 'category.id')
            ->where('product_n_category.is_parent', '=', 0)
            ->where('order.payment_status', 'PAID')
            ->whereBetween('order.created_at', [$dateFrom, $dateTo])
            ->select([
                'order_item.id', 
                'order_item.order_id', 
                'order_item.product_id', 
                'order_item.print_provider',
                'order_item.feedback_issue',
                'category.name as category_name',
                'product_n_category.category_id'
            ])
            ->groupBy('order_item.id')
            ->get();

        $printProviderIssue = [];
        $issueByCategory = [];

        $countAllIssues = 0;
        foreach ($orderItems as $orderItem) {

            $printProvider = $orderItem->print_provider;
           /*  if (substr($printProvider, 0, 8) === "PRINTIFY") {
                $printProvider = 'PRINTIFY';
            } */

            if (!$printProvider) {
                $printProvider = 'UNKNOWN';
            }

            if (!isset($printProviderIssue[$printProvider])) {
                $printProviderIssue[$printProvider] = [
                    'total_item' => 0,
                    'total_issue' => 0,
                    'avg_issue_percent' => 0,
                    'order_ids' => [],
                    'issues' => [],
                ];
            }

            if (!isset($issueByCategory[$orderItem->category_name])) {
                $issueByCategory[$orderItem->category_name] = [];
            }

            if (!isset($issueByCategory[$orderItem->category_name][$printProvider])) {
                $issueByCategory[$orderItem->category_name][$printProvider] = [
                    'issue' => 0,
                    'total' => 0,
                    'percent' => 0
                ];
            }

            $printProviderIssue[$printProvider]['total_item'] ++;
            $issueByCategory[$orderItem->category_name][$printProvider]['total'] ++;
            
            if (!in_array($orderItem->order_id, $printProviderIssue[$printProvider]['order_ids'])) {
                $printProviderIssue[$printProvider]['order_ids'][] = $orderItem->order_id;
            }

            if ($orderItem->feedback_issue) 
            {
                $countAllIssues++;
                $printProviderIssue[$printProvider]['total_issue'] ++;

                $dataIssues = $printProviderIssue[$printProvider]['issues'];

                if (!isset($dataIssues[$orderItem->feedback_issue])) {
                    $dataIssues[$orderItem->feedback_issue] = [
                        'count' => 0,
                        'percent' => 0
                    ];
                }

                $dataIssues[$orderItem->feedback_issue]['count'] ++;

                $printProviderIssue[$printProvider]['issues'] = $dataIssues;

                $issueByCategory[$orderItem->category_name][$printProvider]['issue'] ++;
                $issueByCategory[$orderItem->category_name][$printProvider]['percent'] = $issueByCategory[$orderItem->category_name][$printProvider]['issue'] / $issueByCategory[$orderItem->category_name][$printProvider]['total'] * 100;
                
                $issueByCategory[$orderItem->category_name][$printProvider]['percent'] = round($issueByCategory[$orderItem->category_name][$printProvider]['percent']);
            }
        }

        foreach ($printProviderIssue as $printProvider => &$value) {
            
            $issues = $value['issues'];
            $sumIssuePercent = 0;

            foreach ($issues as &$valueIssue) {
                $valueIssue['percent'] = round($valueIssue['count'] / $value['total_issue'] * 100);
                $sumIssuePercent += $valueIssue['percent'];
            }

            $value['issues'] = $issues;
            if($issues) {
                // $value['avg_issue_percent'] = $sumIssuePercent / count($issues); 
                $value['avg_issue_percent'] =  round($value['total_issue'] / $countAllIssues * 100); 
            }
            
        }

        return [$printProviderIssue, $issueByCategory];

    }

    public function viewReportOrderVerifiers()
    {
        return view('print-suppliers::report.order-verifiers');
    }

    public function viewReportProductVerifiers()
    {
        return view('print-suppliers::report.product-verifiers');
    }

    public function reportOrderVerifiers(Request $request)
    {
        $dateFrom = date('Y-m-d 00:00:00', $request->input('dateFrom'));
        $dateTo = date('Y-m-d 23:59:59', $request->input('dateTo'));
        $verifierEmail = $request->input('verifier_email');
    
        $reportVerifierService = new ReportVerifierService();

        $data = $reportVerifierService->getVerifierReport([
            'from' => $dateFrom,
            'to' => $dateTo,
            'verifier_email' => $verifierEmail
        ]);

        $verifiers = [];

        foreach ($data as $row)
        {
            if (!isset($verifiers[$row->email])) {
                $verifiers[$row->email] = [
                    'PROCESSING' => 0,
                    'PENDING' => 0,
                    'ISSUED' => 0, // In production
                    'READY_TO_SHIP' => 0,
                    'CANCELED' => 0,
                    'DELIVERING' => 0,
                    'FINISHED' => 0,
                    'REQUEST_RETURN' => 0,
                    'RETURNED' => 0,
                    'IS_TICKET' => 0,
                ];
            }

            $status = $row->status;

            if ($row->is_ticket == '1' && $status == 'PROCESSING') {
                $verifiers[$row->email]['IS_TICKET'] ++;
            }

            $verifiers[$row->email][$status] ++;
        }

        return $verifiers;
    }
}
