<?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 ImportListingsSouthCarolina extends Command
{

    protected $signature = 'import:listings_sc';
    protected $description = 'Import Listings from South Carolina';

	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/sc.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;
	    echo "- $address $city $county" . 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');

            $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'          => $firm->id,
                '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 (strpos($address, "DISBARRED") !== false || strpos($address, "PUBLICREP") !== false) {
		// Disbarred, no address
	   } else {
		   $addressLines = explode("\n", $address);
		   print_r($addressLines);
		   
		   if (count($addressLines) == 3) {
		       	   $streetAddress = trim($addressLines[0]); // '701 5th Ave Ste 5100'
			   $cityStateZip = trim($addressLines[1]); // 'Seattle, WA 98104-7036'
			   //$county = trim($addressLines[2]); // 'United States'
		   } elseif (count($addressLines) == 4) {
	                   $streetAddress = trim($addressLines[0]); // '701 5th Ave Ste 5100'
			   $streetAddress = $streetAddress . " " . $addressLines[1];
	                   $cityStateZip = trim($addressLines[2]); // 'Seattle, WA 98104-7036'
	                   //$county = trim($addressLines[3]); // 'United States'
		   }

		   $parts = explode(',', $cityStateZip);
		   $city = trim($parts[0]); 
		   $stateZip = trim($parts[1]);
		   list($state, $zip) = explode(' ', $stateZip, 2);
	
	   	$address = Address::create([
			'listing_id'	=> $listing->id,
			'label'		=> 'Office',
			'full_address'	=> $streetAddress,
			'city'		=> $city,
			'county'	=> $county,
			'state' 	=> 'South Carolina',
			'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 South Carolina',
		'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;
    }
}
