<?php

namespace App\Classes\Modules\Imports\Services;

use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\Booking;

use App\Models\Transaction;
use Maatwebsite\Excel\Concerns\toCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithValidation;
use PhpOffice\PhpSpreadsheet\Shared\Date;

class ImportsBankRecord implements WithHeadingRow, WithBatchInserts, WithValidation
{
  public function __construct() {

  }

  public function collection($collection)
  {
      $date = Date::excelToDateTimeObject($collection['date']);
      $credit = (float) $collection['credit'];
      $systemReference = null;

      $transaction = Transaction::whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])
          ->where('type', TransactionType::PAYMENT)->where('owner_type', Booking::class)
          ->WhereDate('created_at', $date->format('Y-m-d'))
          ->where('amount', '>=', $credit)->where('amount', '<', ($credit + 0.01))
          ->get();

      if(count($transaction)) {
          $systemReference = $transaction->pluck('owner.marking')->flatten()->implode(', ');
      }

      $matches = $systemReference === $collection['remarkreferences'] ? 'Yes' : 'No';

      echo '<tr>
             <td>'.$date->format('d-m-Y').'</td>
             <td>'.$collection['description'].'</td>
             <td>'.$credit.'</td>
             <td>'.$systemReference.'</td>
             <td>'.$collection['remarkreferences'].'</td>
             <td>'.$matches.'</td>
          </tr>';

  }

  public function batchSize(): int
  {
    return 100;
  }

  public function rules(): array
  {
      return [

      ];
  }
}
