<?php

namespace App\Imports;

use App\Models\Client;
use App\Models\Clientsinfo;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class ClientInfoImport implements ToCollection, WithHeadingRow
{
    protected $columnMapping;
    protected $errors = [];
    protected $successCount = 0;

    public function __construct($columnMapping)
    {
        $this->columnMapping = $columnMapping;
    }

    public function collection(Collection $rows)
    {
        foreach ($rows as $index => $row) {
            $rowNumber = $index + 2; // +2 because index starts at 0 and we skip header row

            try {
                // Get username from first column
                $username = isset($row['username']) ? trim($row['username']) : (isset($row[0]) ? trim($row[0]) : null);

                if (empty($username)) {
                    $this->errors[] = "Row {$rowNumber}: Username is required";
                    continue;
                }

                // Find client by username (userid)
                $client = Client::where('userid', $username)->first();

                if (!$client) {
                    $this->errors[] = "Row {$rowNumber}: Client with username '{$username}' not found";
                    continue;
                }

                // Get the value from second column (information column)
                $informationValue = isset($row[$this->columnMapping]) ? trim($row[$this->columnMapping]) : (isset($row[1]) ? trim($row[1]) : null);

                if (empty($informationValue)) {
                    $this->errors[] = "Row {$rowNumber}: {$this->columnMapping} value is required";
                    continue;
                }

                // Get the target column from mapping
                $targetColumn = $this->columnMapping;

                // Determine which table and update accordingly
                if ($this->isClientColumn($targetColumn)) {
                    // Update clients table
                    $client->update([
                        $targetColumn => $informationValue
                    ]);
                } elseif ($this->isClientsInfoColumn($targetColumn)) {
                    // Update clientsinfo table
                    $clientInfo = Clientsinfo::where('client_id', $client->id)->first();

                    if ($clientInfo) {
                        $clientInfo->update([
                            $targetColumn => $informationValue
                        ]);
                    } else {
                        $this->errors[] = "Row {$rowNumber}: Client info not found for username '{$username}'";
                        continue;
                    }
                } else {
                    $this->errors[] = "Row {$rowNumber}: Invalid column mapping '{$targetColumn}'";
                    continue;
                }

                $this->successCount++;

            } catch (\Exception $e) {
                $this->errors[] = "Row {$rowNumber}: " . $e->getMessage();
            }
        }
    }

    /**
     * Check if column belongs to clients table
     */
    protected function isClientColumn($column)
    {
        $clientColumns = [
            'pop_id', 'billing_cycle', 'package_id', 'mac', 'password',
            'ip_address', 'expire_date', 'required_cable', 'client_approval',
            'clients_status', 'marketed_by', 'sub_package_id', 'customer_code',
            'payment_dadeline', 'parmanent_discount'
        ];

        return in_array($column, $clientColumns);
    }

    /**
     * Check if column belongs to clientsinfo table
     */
    protected function isClientsInfoColumn($column)
    {
        $clientsInfoColumns = [
            'clients_name', 'father_name', 'mother_name', 'flat_no', 'building_name',
            'road_no', 'block_sector', 'area', 'district', 'thana', 'contact_no',
            'national_id', 'email', 'passport_no', 'owner_name', 'owner_number',
            'olt_pon', 'otc', 'building_no', 'remarks', 'dob', 'cable_type',
            'road_name', 'otc_due', 'other_contact', 'box', 'joinDate',
            'client_latitude', 'client_longitude', 'client_door', 'cat_type',
            'cat_length', 'olt_no', 'pon_port', 'onu_serial', 'cable_id',
            'customer_package_name', 'btrc_package_bandwidth', 'source_name'
        ];

        return in_array($column, $clientsInfoColumns);
    }

    public function getErrors()
    {
        return $this->errors;
    }

    public function getSuccessCount()
    {
        return $this->successCount;
    }
}
