<?php
/*
Plugin Name: EPC Search Pro
Description: Search UK EPCs by postcode or address.
Version: 2.0
Author: Bilal Ghanchi
*/

if (!defined('ABSPATH')) exit;

/* ======================================================
   LOAD ASSETS (JS + CSS)
====================================================== */

add_action('wp_enqueue_scripts', function () {

    wp_enqueue_style(
        'epc-style',
        plugin_dir_url(__FILE__) . 'assets/epc-style.css',
        [],
        filemtime(plugin_dir_path(__FILE__) . 'assets/epc-style.css')
    );

    wp_enqueue_script(
        'epc-script',
        plugin_dir_url(__FILE__) . 'assets/epc-script.js',
        ['jquery'],
        filemtime(plugin_dir_path(__FILE__) . 'assets/epc-script.js'),
        true
    );

    wp_localize_script('epc-script', 'epc_ajax', [
        'ajaxurl' => admin_url('admin-ajax.php'),
        'nonce'   => wp_create_nonce('epc_nonce')
    ]);
});

/* ======================================================
   API AUTH (Single Source)
====================================================== */

function epc_api_request($url) {

    $email = trim(get_option('epc_api_email'));
    $key   = trim(get_option('epc_api_key'));

    if (!$email || !$key) {
        return new WP_Error('missing', 'API credentials missing');
    }

    $response = wp_remote_get($url, [
        'headers' => [
            'Authorization' => 'Basic ' . base64_encode($email . ':' . $key),
            'Accept'        => 'application/json'
        ],
        'timeout' => 20
    ]);

    if (is_wp_error($response)) return $response;

    return json_decode(wp_remote_retrieve_body($response), true);
}

/* ======================================================
   SEARCH SHORTCODE
====================================================== */

add_shortcode('epc_search', function () {
ob_start(); ?>

<form id="epc-form" class="epc-form">
    <div class="epc-type-select">
        <label><input type="radio" name="epc_type" value="domestic" checked><span>Domestic</span></label>
        <label><input type="radio" name="epc_type" value="commercial"><span>Commercial</span></label>
        <label><input type="radio" name="epc_type" value="display"><span>Display</span></label>
    </div>

    <div class="epc-search-box">
        <input type="text" name="epc_query" placeholder="Enter postcode or address" required>
        <button type="submit">Search EPC</button>
    </div>
</form>

<div id="epc-results"></div>

<?php return ob_get_clean();
});

/* ======================================================
   AJAX SEARCH
====================================================== */

add_action('wp_ajax_epc_search','epc_ajax_search');
add_action('wp_ajax_nopriv_epc_search','epc_ajax_search');

function epc_ajax_search() {

    check_ajax_referer('epc_nonce','nonce');

    $query = sanitize_text_field($_POST['query']);
    $type  = sanitize_text_field($_POST['type']);

    $dataset = match($type){
        'commercial'=>'non-domestic',
        'display'=>'display',
        default=>'domestic'
    };

    $param = preg_match('/[A-Z]{1,2}\d/i',$query) ? 'postcode' : 'address';

    $url = add_query_arg([
        $param=>$query,
        'size'=>50
    ],"https://epc.opendatacommunities.org/api/v1/{$dataset}/search");

    $data = epc_api_request($url);

    if (empty($data['rows'])) {
        echo '<p>No EPC records found.</p>';
        wp_die();
    }

    echo '<table class="epc-table"><tbody>';

    foreach($data['rows'] as $r){

        $lodged = strtotime($r['lodgement-date']);
        $expired = time() > strtotime('+10 years',$lodged);

        echo '<tr>
            <td>'.$r['address'].'</td>
            <td class="'.($expired?'epc-expired':'epc-valid').'">'.
                ($expired?'Expired':'Valid').
            '</td>
        </tr>';
    }

    echo '</tbody></table>';

    wp_die();
}