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

    protected $signature = 'import:listings_ga';
    protected $description = 'Import Listings from Georgia';

	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/ga.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;
	    $fax = (string) $record->fax;
	    $address = (string) $record->address;
	    $city = (string) $record->city;
	    $county = (string) $record->county;
	    $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;

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

            // Print out the listing details
            echo "Listing ID: $id" . PHP_EOL;
            echo "Full Name: $full_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";

	        $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);
            }
	   //print_r($address);
	   //print_r($record);

	   	if (isset($address) && ($address != "")) {
		 	$addressLines = explode("\n", $address);
		 
			if (count($addressLines) >= 3) {
			        $firm = trim($addressLines[0]);
			        $streetAddress = trim($addressLines[1]);
	  		} else {
       				$streetAddress = trim($addressLines[0]);
    	    		}

	    	    	if (preg_match('/(.*),\s*(\w+)\s*(\d+(-\d+)?),\s*(.*)/', trim(end($addressLines)), $matches)) {
    	    			$city = $matches[1];
    	    			$state = $matches[2];
    	    			$zip = $matches[3];
    	    			$country = $matches[5];
	    	   	}
	
		   $address = Address::create([
			'listing_id'	=> $listing->id,
			'label'		=> 'Office',
			'full_address'	=> $streetAddress,
			'city'		=> $city,
			'county'	=> $county,
			'state' 	=> 'Georgia',
			'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 Georgia',
		'since'		=> $year,
                'created_at'    => $createdAt,
           ]);

		}		
        }
        return Command::SUCCESS;
    }
}
