<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use SimpleXMLElement;
use App\Models\Firm;
use App\Models\PracticeArea;
use App\Models\Listing;
use App\Models\Address;
use App\Models\Jurisdiction;
use App\Models\Education;
use App\Models\Language;
use Carbon\Carbon;

class ImportListingsMichigan extends Command
{

    protected $signature = 'import:listings_mi';
    protected $description = 'Import Listings from Michigan';

	public function handle()
    	{
	//$state = $this->argument('state');
    	//$xml = "/home/bitnami/htdocs/legal.com/app/Console/Commands/imports/{$state}.xml";
	$xml = simplexml_load_file('/home/bitnami/htdocs/development.legal.com/app/Console/Commands/imports/mi.xml');
        // Iterate over each <record></record> element
	$i = 0;
        foreach ($xml as $record) {
	    $i++;
	    $id = $i;
            // Extract data from the XML element
            $full_name = (string) $record['full_name'];
            $first_name = (string) $record->first_name;
	    $last_name = (string) $record->last_name;
	    $middle_name = (string) $record->middle_name;
	    $email = (string) $record->email;
	    $phone = (string) $record->phone;
	    $address = (string) $record->address;
	    $city = (string) $record->city;
	    $county = (string) $record->county;
	    $website = (string) $record->website_url;
	    $firm = (string) $record->law_firm;
	    $jurisdiction = (string) $record->jurisdiction;
	    $date_admitted = (string) $record->date_admitted;
	    $practice_areas = (string) $record->practice_areas;
	    $languages = (string) $record->language;
	    $law_school = (string) $record->law_school;

            // Print out the listing details
	    echo "Listing ID: $id" . PHP_EOL;
	    echo "- $first_name $middle_name $last_name" . PHP_EOL;

            if (!isset($practice_areas) || ($practice_areas == '')) {
                echo "$full_name has no practice area, skipping.\n";
            } else {
                echo "Practice areas: $practice_areas \n";

		$createdAt = date('Y-m-d H:i:s');

	    	if (isset($firm) && ($firm != "None")) {
	            $firm = Firm::firstOrCreate([
	                'name' => $firm,
	            ]);
	    	}

            // Create a new Listing
            $listing = Listing::create([
                'picture'          => null,
                'first_name'       => $first_name,
                'middle_name'      => $middle_name,
                'last_name'        => $last_name,
                'firm_id'          => isset($firm->id) ? $firm->id : null,
                'phone'            => $phone,
                'email'            => $email,
                'user_id'          => '1',
                'url' => $website,
		'created_at'	   => $createdAt,
                //'address_id'       => (string) $record->address_id,
                //'description'      => (string) $record->description,
            ]);

           if (!is_null($practice_areas) && $practice_areas !== '') {
                $practiceAreaList = explode(',', $practice_areas);

                foreach ($practiceAreaList as $practiceAreaName) {
                    $practiceAreaName = trim($practiceAreaName); // Remove whitespace

                    if (!empty($practiceAreaName)) {
                        // Check if the practice area exists, create if not
                        $practiceArea = PracticeArea::firstOrCreate([
                            'name' => $practiceAreaName
                        ]);
			$listing->practiceAreas()->attach($practiceArea->id);
                    }
                }
            }
           if (!is_null($languages) && $languages !== '') {
                $languagesList = explode(',', $languages);

                foreach ($languagesList as $lang) {
                    $languageName = trim($lang);

                    if (!empty($languageName)) {
                        $language = Language::firstOrCreate([
                            'name' => $languageName
                        ]);
			$listing->language()->attach($language);
                    }
                }
            } else {
		$language = Language::firstOrCreate([
                	'name' => 'English',
                ]);

		$listing->language()->attach($language);
            }
	
	   if (isset($address) && ($address != '')) {
		   $addressLines = explode("\n", $address);
		   print_r($addressLines);
		   
$parts = explode("\n", $address);

$streetAddress = $parts[0] ?? '';
$city = $state = $zipCode = $country = '';

if (count($parts) === 4) {
    // Format: Street, City, State + ZIP, Country
    $city = trim($parts[1]);
    $stateZip = explode(' ', trim($parts[2]));
    $country = trim($parts[3]);
} elseif (count($parts) === 3) {
    // Format: Street, City + State + ZIP, Country
    $cityStateZip = preg_split('/,?\s+(?=[A-Z]{2}\s+\d)/', trim($parts[1]));
    if (count($cityStateZip) === 2) {
        $city = trim($cityStateZip[0]);
        $stateZip = explode(' ', trim($cityStateZip[1]));
    }
    $country = trim($parts[2]);
}

// Further split the State and ZIP Code if available
if (!empty($stateZip)) {
    $state = $stateZip[0] ?? '';
    $zip = $stateZip[1] ?? '';
}
	
	   	$address = Address::create([
			'listing_id'	=> $listing->id,
			'label'		=> 'Office',
			'full_address'	=> $streetAddress,
			'city'		=> $city,
			'county'	=> $county,
			'state' 	=> 'Michigan',
			'country'	=> 'United States of America',
			'zipcode'	=> $zip,
			'primary' 	=> 1,
			'created_at'	=> $createdAt,
		    ]);
	   }

	   if (isset($date_admitted) && ($date_admitted != '')) {
		$year = Carbon::createFromFormat('m/d/Y', $date_admitted)->year;
	   } else {
		$year = null;
	   }
	   $jurisdiction = Jurisdiction::create([
	        'listing_id'    => $listing->id,
		'name'		=> 'State of Michigan',
		'since'		=> $year,
                'created_at'    => $createdAt,
           ]);


	   if (isset($law_school) && ($law_school != '')) {
		$education = Education::create([
                	'listing_id'    => $listing->id,
                	'institution'   => $law_school,
                	'created_at'    => $createdAt,
		]);

		}
	   }		
        }
        return Command::SUCCESS;
    }
}
