<?php

namespace App\Http\Controllers\Imports;

use App\Classes\Modules\Documents\DataTransferObjects\DocumentObject;
use App\Classes\Modules\Imports\Services\GenericImport;
use App\Classes\Modules\Segments\DataTransferObjects\SeasonalSegmentObject;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Models\Segment;
use App\Models\User;
use Carbon\Carbon;
use DateTime;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Classes\Modules\Segments\Services\CreatesSeasonalSegment;
use App\Classes\Modules\Companies\Processors\AssignSegmentProcessor;
use App\Models\Company;
use App\Models\SeasonalSegment;
use App\Models\Transaction;
use App\Models\TransactionMappingLog;
use App\Classes\ValueObjects\Response\ApiResponseObject;
use App\Classes\ValueObjects\Constants\HttpStatus;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class ImportStatementReceiptsController
{
    private $responseTitle;
    private $responseMessage;

    public function __construct() {
        $this->responseTitle = 'Import Receipt Mapping';
        $this->responseMessage = 'You have successfully imported receipt mapping';
    }

    /**
     * @param Request $request
     * @return array
     * @throws \App\Classes\Exceptions\MalformedRequestException
     */
    public function import(Request $request)
    {
        $importDate = date('Y-m-d H:i:s');
        $object = new DocumentObject('', $request->input('files'), '', ApprovalStatus::APPROVED, 'imports');
        $file = json_decode($object->getFiles()[0])->file_info->original->file;

        $import = new GenericImport();
        Excel::import($import, $file);
        $excelRows = $import->rows;
        $excelRows = $excelRows->toArray();

        $data = [];
        foreach ($excelRows as $row) {
            $row['mapped_result_reference'] = null;
            $row['mapped_status'] = 'failed';
            $row['date'] = $this->changeExcelDate($row['doc_date']);

            $returnReference = $this->mappingExchange($row);
            if ($returnReference) {
                $row['mapped_result_reference'] = $returnReference;
                $row['mapped_status'] = 'success';
            } 

            TransactionMappingLog::create([
                'imported_date'=>$importDate,
                'data'=>$row,
            ]);
            array_push($data, $row);
        }

        return $this->response(['data'=>$data,'importedDate'=>$importDate]);
    }

    public function response(?array $data = []) : JsonResponse {
        return (new ApiResponseObject($this->responseTitle,
            $this->responseMessage,
            HttpStatus::OK_WITH_MESSAGE, $data))->handler();
    }

    private function mappingExchange(Array $row) {
        $date = $row['date'];
        $transactions = Transaction::getReceiverWithJoinStatementTransactionAndOwner($row)->select('transactions.*')->where('statement_transactions.amount', $row['payment_amount'])->whereRaw("DATE(posting_date) = '$date'")->get();

        if ($transactions && $transactions->count() == 0) {
            $transactions = Transaction::getReceiverWithJoinStatementTransactionAndOwner($row)->select('transactions.*')->where(DB::raw('FLOOR(statement_transactions.amount)'), floor($row['payment_amount']))->whereRaw("DATE(posting_date) = '$date'")->get();
        }

        if ($transactions && $transactions->count() == 1) {
            foreach ($transactions as $key => $transaction) {
                return $this->updateTransactionOwnerReference($transaction, $row['doc_no']);
            }
        }
        return false;
    }

    public function updateTransactionOwnerReference($transaction, String $docNo) {
        $transactionOwner = $transaction->transaction_owner;
        if ($transactionOwner) {
            $transactionOwner->update(['receipt_reference'=>$docNo]);
            return $transactionOwner->owner_reference;
        }
        return false;
    }

    public function changeExcelDate($date)
    {
        $unixTime = (($date - 25569) * 86400);
        $date = new DateTime("@$unixTime");
        return $date->format('Y-m-d'); // Change the format to 'Y-m-d'
    }
}
