<?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\SeasonalSegment;

class ImportHoneyTrapController
{
    /**
     * @param Request $request
     * @return array
     * @throws \App\Classes\Exceptions\MalformedRequestException
     */
    public function import(Request $request)
    {
        $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();

        $returnArray    = [];
        // $segment_name   = 'honey trap campaign';
        // $segment        = Segment::where('name', $segment_name)->first();
        $input_segment_id     = $request->input('segment_id');
        if (!$input_segment_id) {
            $row['status']    = 'Failed';
            $row['message']   = 'segment_id cannot be empty';
            $returnArray[]    = $row;
            return response()->json($returnArray);
        }

        $segment        = Segment::where('id', $input_segment_id)->first();
        if (!$segment) {
            $row['status']    = 'Failed';
            $row['message']   = 'Segment not found';
            $returnArray[]    = $row;
            return response()->json($returnArray);
        }

        $segment_id = $segment->id;

        foreach ($excelRows as $row) {

            if (is_null($row['email']) || empty($row['email'])) {
                continue;
            }

            if (is_null($row['end_date']) || empty($row['end_date'])) {
                // use csv import must have an end_date
                $row['status']    = 'failed';
                $row['message']   = 'End Date is required';
                $returnArray[]    = $row;
                continue;
            }

            $row['end_date']   = $end_date = $this->changeExcelDate($row['end_date']);
            $start_date        = $row['start_date'] ? $this->changeExcelDate($row['start_date']) : Carbon::now();
            $row['start_date'] = $start_date;

            $end_date = Carbon::parse($end_date);
            // Check if the end_date is in the past
            if ($end_date->isPast()) {
                // end_date must be after today's date
                $row['status']    = 'failed';
                $row['message']   = "End Date must be after today's date";
                $returnArray[]    = $row;
                continue;
            }

            $user = User::where('email', $row['email'])->first();
            if (!$user) {
                // if user not found
                $row['status']    = 'failed';
                $row['message']   = 'Email not found';
                $returnArray[]    = $row;
                continue;
            }

            $company = $user->company->first();
            if (!$company) {
                // if company not found
                $row['status']    = 'failed';
                $row['message']   = 'Company not found';
                $returnArray[]    = $row;
                continue;
            }

            $company_seasonal_honey_trap_count = SeasonalSegment::where('company_id', $company->id)->where('segment_id', $segment_id)->get();
            if (count($company_seasonal_honey_trap_count)) {
                // seasonal segment already exists
                $row['status']    = 'failed';
                $row['message']   = 'Company is already in the Honey Trap Segment';
                $returnArray[]    = $row;
                continue;
            }

            $seasonalSegmentObject = new SeasonalSegmentObject($company->id, $segment_id, $start_date, $end_date ?? null);

            (App()->make(createsSeasonalSegment::class))->execute($seasonalSegmentObject);
            (App()->make(assignSegmentProcessor::class))->execute($company, $segment_id);

            // success added honey trap seasonal segment 
            $row['status']    = 'success';
            $row['message']   = '';
            $returnArray[]    = $row;
            continue;
        }

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

    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'
    }
}
