<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

use Facebook\WebDriver\WebDriverBy;
use Symfony\Component\Panther\Client;

require __DIR__.'/vendor/autoload.php'; // Composer's autoloader

$client = Client::createChromeClient();
// Or, if you care about the open web and prefer to use Firefox
//$client = Client::createFirefoxClient();

$client->request('GET', 'https://accounts.energysage.com/login?next=https%3A%2F%2Fwww.energysage.com'); // Yes, this website is 100% written in JavaScript

// Find the username input field and enter the username/email
$usernameField = $client->findElement(WebDriverBy::id('input-group-email'));
$usernameField->sendKeys('sales@nuwattenergy.com');

// Find the password input field and enter the password
$passwordField = $client->findElement(WebDriverBy::id('input-group-password'));
$passwordField->sendKeys('nuw999');

// Submit the login form
$passwordField->submit();

// Wait for the page to load after submitting the form (you can adjust the sleep time as needed)
sleep(5);

// Validate the login by checking for a specific element on the authenticated page
//$loggedInElement = $client->findElement(WebDriverBy::id('h1-login-success'));

//$client->waitFor('#home-main');

$redirectUrl = 'https://www.energysage.com/market/properties/new/'; // Replace with your desired redirect URL

// Navigate to the redirect URL
$client->get($redirectUrl);

$elements = $client->findElements(WebDriverBy::cssSelector('.mp-lead'));

$counter = 0;

foreach ($elements as $key => $value) {
 
    $client->get($redirectUrl); // Refresh the page to ensure the elements are still valid

    // Re-locate the elements by class name
    $newElements = $client->findElements(WebDriverBy::cssSelector('.mp-lead'));

    if (!empty($newElements)) {

        $stateInfo = $newElements[$counter]->findElements(WebDriverBy::cssSelector('.mp-lead__state'));
        
        if( $stateInfo[0]->getText() == "PA" ){
            $counter++;
            continue;
        }

        $clickToExpressInterest = $newElements[$counter]->findElements(WebDriverBy::cssSelector('.l-button-link'));

        $clickToExpressInterest[0]->click();

        // // Wait for the new page to load
        $client->waitFor('body');

        // // Do any necessary processing on the new page

        // // Go back to the original page
        $client->back();
    }
}

//$pageSource = $client->getWebDriver()->getPageSource();

//echo $pageSource;

