<?php

namespace App\Imports;

use App\Models\User;
use App\Models\SellerWithdrawal;
use Maatwebsite\Excel\Concerns\ToModel;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use Helper;

class SellerWalletImport implements ToCollection, WithHeadingRow, WithValidation
{
    /**
    * @param Collection $collection
    */
    public function collection(Collection $rows){
       $expectedColumns = ["id", "name", "phone_number", "current_balance", "amount"];

        if ($rows->isNotEmpty()) {
            $fileColumns = array_keys($rows->first()->toArray());

            if (array_diff($expectedColumns, $fileColumns)) {
                throw new \Exception("Excel column names do not match the expected database fields.");
            }
        }

        foreach ($rows as $row) {
            $userId = $row['id'];

            $userExists = User::where('id', $userId)->exists();

            if (!$userExists) {
                throw new \Exception("User with ID $userId does not exist in the database.");
            }

            $userData = User::where('id', $userId)->first();

            if($row['current_balance'] <= $userData->current_balance){
                if($row['amount'] <= $userData->current_balance){
                    SellerWithdrawal::create([
                        'user_id'         => $userId,
                        'name'            => $row['name'] ?? null,
                        'phone_number'    => $row['phone_number'] ?? null,
                        'amount' => $row['amount'] ?? 0,
                    ]);
                    $newUserData = User::find($userId);
                    $newUserData->current_balance = $newUserData->current_balance - $row['amount'];
                    $newUserData->save();

                    // $msg= 'Hello '.$newUserData->name.' '.$newUserData->last_name.', an amount of '.$row['amount'].' has been withdrawn by the admin. Your current balance is '.$newUserData->current_balance.', and your pending balance is '.$newUserData->pending_balance.'. Please review your account for details';

                    // pushNotification($newUserData->id,$msg);
                } else {
                    throw new \Exception("Amount is not greater than current balance.");
                }
            } else {
                throw new \Exception("current balance is not matched.");
            }
        }
    }

    public function rules(): array{
        return [
            '*.id' => 'required|integer|exists:users,id',
            '*.phone_number' => 'required',
            '*.current_balance' => 'nullable|numeric',
            '*.amount' => 'nullable|numeric',
        ];
    }
}
