<?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 App\Models\State;

use Carbon\Carbon;

class ImportListingsCalifornia extends Command
{

    protected $signature = 'import:listings_ca';
    protected $description = 'Import Listings from California';

	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/ca.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;
	    $date_admitted = (string) $record->date_admitted;
	    $practice_areas = (string) $record->practice_areas;
	    $state_abbreviation = (string) $record->state;
	    $languages = (string) $record->language;

            // 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";


	        if (isset($state_abbreviation)) {
	        	$state = State::where('abbreviation', $state_abbreviation)->first();
	        }

	    	$parts = explode(',', $address);
	    	echo "PARTS: " . count($parts) . PHP_EOL;

            if (count($parts) == 3) {
                    $streetAddress = $parts[0];
                    $city = $parts[1];

                   $stateZip = explode(' ', trim($parts[2]));

            } elseif (count($parts) == 4) {
                    $streetAddress = $parts[0] . ", " . $parts[1];
                    $city = $parts[2];

                   $stateZip = explode(' ', trim($parts[3]));

	    } elseif (count($parts) == 5) {
		    $firm = $parts[0];
		    $streetAddress = $parts[1] . ", " . $parts[2];
    		    $city = $parts[3];

	 	   $stateZip = explode(' ', trim($parts[4]));

	    }

            if (count($stateZip) == 2) {
                 $state = $stateZip[0];
                 $zip = $stateZip[1];
            }

            // Print out the listing details
	    echo "Listing ID: $id" . PHP_EOL;
            echo "Full Name: $full_name" . PHP_EOL;
	    echo "Address: $address" . PHP_EOL;
	    echo "City: $city" . PHP_EOL;
            echo "County: $county" . PHP_EOL;
            echo "Website: $website" . PHP_EOL;
            echo "Firm: $firm" . PHP_EOL;
            echo "Practice areas: $practice_areas" . PHP_EOL;
	    $createdAt = date('Y-m-d H:i:s');

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

		}		
        }
        return Command::SUCCESS;
    }
}
