<?php

namespace App\Imports;

use App\Models\Company;
use App\Models\Role;
use App\Models\StaffMember;
use App\Models\Location;
use App\Models\Department;
use App\Models\Designation;
use App\Models\Vendor;
use Examyou\RestAPI\Exceptions\ApiException;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\ToArray;

class UserImport implements ToArray, WithHeadingRow
{

    public function array(array $users)
    {
        DB::transaction(function () use ($users) {
            $userType = "staff_members";

            foreach ($users as $user) {
                $requiredFields = ['name', 'email', 'phone', 'allow_login', 'status', 'joining_date','annual_ctc', 'basic_percentage_on_ctc', 'location','department','designation'];
                foreach ($requiredFields as $field) {
                    if (!array_key_exists($field, $user)) {
                        throw new ApiException("Field '{$field}' missing from header.");
                    }
                }

                if (!isset($user['name']) || trim($user['name']) === '') {
                    continue;
                }

                $empNum = isset($user['employee_number']) ? trim($user['employee_number']) : null;

                $email = isset($user['email']) ? trim($user['email']) : null;
                $phone = isset($user['phone']) ? trim($user['phone']) : null;
                $name  = isset($user['name']) ? trim($user['name']) : null;

                $exists = StaffMember::withoutGlobalScope('type')
                    ->where('user_type', $userType)
                    ->where(function ($query) use ($empNum, $email, $phone) {
                        if ($empNum) {
                            $query->orWhere('employee_number', $empNum);
                        }
                        if ($email) {
                            $query->orWhere('email', $email);
                        }
                        if ($phone) {
                            $query->orWhere('phone', $phone);
                        }
                    })
                    ->exists();

                if ($exists) {
                    continue;
                }

                $annual_ctc = (isset($user['annual_ctc']) && trim($user['annual_ctc']) != '') ? floatval(trim($user['annual_ctc'])) : 0;
                $ctc_value = (isset($user['basic_percentage_on_ctc']) && trim($user['basic_percentage_on_ctc']) != '') ? floatval(trim($user['basic_percentage_on_ctc'])) : 50;

                if ($annual_ctc > 0 && $ctc_value > 0) {
                    $monthly_amount = $annual_ctc / 12;
                    $net_salary = ($monthly_amount * $ctc_value) / 100;
                    $basic_salary = $net_salary;
                    $special_allowances = $monthly_amount - $basic_salary;
                    $annual_amount = ($annual_ctc * $ctc_value) / 100;
                }

                // location_id
                $company_id = company()->id;
                $location = null;
                if (isset($user['location']) && trim($user['location']) != '') {
                    $locationName = trim($user['location']);
                    $location = Location::where('name', $locationName)->where('company_id', $company_id)->first();
                    if (!$location) {
                        $location = new Location(); 
                        $location->name = $locationName;
                        $location->company_id = $company_id;
                        $location->save();
                    }
                }
                $department = null;
                if (isset($user['department']) && trim($user['department']) != '') {
                    $departmentName = trim($user['department']);
                    $department = Department::where('name', $departmentName)->where('company_id', $company_id)->first();
                    if (!$department) {
                        $department = new Department(); 
                        $department->name = $departmentName;
                        $department->company_id = $company_id;
                        $department->save();
                    }
                }
                $designation = null;
                if (isset($user['designation']) && trim($user['designation']) != '') {
                    $designationName = trim($user['designation']);
                    $designation = Designation::where('name', $designationName)->where('company_id', $company_id)->first();
                    if (!$designation) {
                        $designation = new Designation(); 
                        $designation->name = $designationName;
                        $designation->company_id = $company_id;
                        $designation->save();
                    }
                }

                $vendor = null;
                if (isset($user['vendor']) && trim($user['vendor']) != '') {
                    $agency_code = trim($user['vendor']);
                    $vendor = Vendor::where('agency_code', $agency_code)->where('company_id', $company_id)->first();
                    if (!$vendor) {
                        /*$vendor = new Vendor(); 
                        $vendor->agency_code = $agency_code;
                        $vendor->agency_name = $agency_code;
                        $vendor->save();*/
                        throw new ApiException("$agency_code code Vendor not found please add.");
                    }
                }

                $status = (isset($user['status']) && trim($user['status']) != '') ? trim($user['status']) : 'active';
                $joining_date = (isset($user['joining_date']) && trim($user['joining_date']) != '')
                    ? date('Y-m-d', strtotime($user['joining_date']))
                    : null;
                $gender = (isset($user['gender']) && trim($user['gender']) != '') ? trim($user['gender']) : 'female';
                $allowLogin = isset($user['allow_login']) ? filter_var($user['allow_login'], FILTER_VALIDATE_BOOLEAN) : false;

                $password = null;

                if ($allowLogin) {
                    if (isset($user['password']) && trim($user['password']) !== '') {
                        $password = trim($user['password']);
                    } else {
                        $password = '12345678';
                    }
                }


                $userModel = new StaffMember();
                $userModel->user_type = $userType;
                $userModel->name = $name;
                $userModel->email = $email;
                $userModel->phone = $phone;
                $userModel->status = $status;
                $userModel->password = $password;
                $userModel->gender = $gender;
                $userModel->allow_login = $allowLogin;
                $userModel->joining_date = $joining_date;

                if ($location) {
                    $userModel->location_id = $location->id;
                }
                if ($department) {
                    $userModel->department_id = $department->id;
                }
                if ($designation) {
                    $userModel->designation_id = $designation->id;
                }
                if ($vendor) {
                    $userModel->vendor_id = $vendor->id;
                }
                $userModel->annual_ctc = $annual_ctc ?? 0;
                $userModel->ctc_value = $ctc_value ?? 0;
                $userModel->monthly_amount = $monthly_amount ?? 0;
                $userModel->net_salary = $net_salary ?? 0;
                $userModel->basic_salary = $basic_salary ?? 0;
                $userModel->special_allowances = $special_allowances ?? 0;
                $userModel->annual_amount = $annual_amount ?? 0;

                $employeeNumber = (isset($user['employee_number']) && trim($user['employee_number']) != '')
                    ? trim($user['employee_number'])
                    : null;
                $userModel->save();

                if ($employeeNumber) {
                    $userModel->employee_number = $employeeNumber;
                    $userModel->save();
                } else {
                    $company = Company::find($userModel->company_id);
                    $currentNumber = (int) $company->employee_id_start;
                    $generatedEmployeeNumber = $company->employee_id_prefix . '-' . str_pad($currentNumber, $company->employee_id_digits, '0', STR_PAD_LEFT);
                    $userModel->employee_number = $generatedEmployeeNumber;
                    $userModel->save();

                    $company->employee_id_start = $currentNumber + 1;
                    $company->save();
                }
            }
        });
    }
}
