<?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\Language;
use Carbon\Carbon;

class ImportListingsTexas extends Command
{

    protected $signature = 'import:listings_tx';
    protected $description = 'Import Listings from Texas';

	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/tx.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;
	    $state = (string) $record->state;
	    $website = (string) $record->website;
	    $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;

            // Print out the listing details
	    echo "Listing ID: $id" . PHP_EOL;
            echo "Full Name: <$full_name> $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";
		echo "Address: $address\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);
            }

	   $addressLines = explode("\n", $address);

	   if (count($addressLines) == 2) {
                   $streetAddress = trim($addressLines[0]);
		  $cityStateZip = trim($addressLines[1]);
	   } elseif (count($addressLines) == 3) {
	       	   $streetAddress = trim($addressLines[0]); // '701 5th Ave Ste 5100'
		   $streetAddress = $streetAddress . " " . $addressLines[1];
		   $cityStateZip = trim($addressLines[2]);
	   } elseif (count($addressLines) == 4) {
                   $streetAddress = trim($addressLines[0]); // '701 5th Ave Ste 5100'
		   $streetAddress = $streetAddress . " " . $addressLines[1] . " " . $addressLines[2];
                   $cityStateZip = trim($addressLines[3]); // 'Seattle, WA 98104-7036'
	   }
	   echo "Street Address: $streetAddress\n";
	   echo "Rest: $cityStateZip\n";
	   $parts = explode(',', $cityStateZip);
	   $city = trim($parts[0]); 
	   list($stateAbrv, $zip) = explode(' ', $parts[1], 2);


	   $address = Address::create([
		'listing_id'	=> $listing->id,
		'label'		=> 'Office',
		'full_address'	=> $streetAddress,
		'city'		=> $city,
		'county'	=> $county,
		'state' 	=> $state,
		'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 Texas',
		'since'		=> $year,
                'created_at'    => $createdAt,
           ]);

		}		
        }
        return Command::SUCCESS;
    }
}
