<?php
/**
 * Plugin Name: Calculette Irrigation BRL
 * Description: Calculette de programmation des irrigations avec comptes clients et sauvegarde des simulations. Shortcode: [calculette_irrigation]
 * Version: 2.0.0
 * Author: BRL Exploitation
 */
if (!defined('ABSPATH')) exit;

class BRL_Calculette_Irrigation {
    const OPT_LOGO = 'brl_calculette_logo_url';
    const META_SAVES = 'brl_calculette_irrigation_saves';

    public function __construct() {
        add_shortcode('calculette_irrigation', [$this, 'shortcode']);
        add_action('wp_enqueue_scripts', [$this, 'assets']);
        add_action('admin_menu', [$this, 'admin_menu']);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('wp_ajax_brl_calc_save', [$this, 'ajax_save']);
        add_action('wp_ajax_brl_calc_delete', [$this, 'ajax_delete']);
        add_action('wp_ajax_nopriv_brl_calc_register', [$this, 'ajax_register']);
        add_action('wp_ajax_nopriv_brl_calc_login', [$this, 'ajax_login']);
    }

    public function assets() {
        wp_register_style('brl-calculette', plugin_dir_url(__FILE__) . 'assets/calculette.css', [], '2.0.0');
        wp_register_script('brl-calculette', plugin_dir_url(__FILE__) . 'assets/calculette.js', [], '2.0.0', true);
    }

    public function admin_menu() {
        add_options_page('Calculette Irrigation', 'Calculette Irrigation', 'manage_options', 'brl-calculette-irrigation', [$this, 'settings_page']);
    }
    public function register_settings() { register_setting('brl_calculette_settings', self::OPT_LOGO, ['sanitize_callback' => 'esc_url_raw']); }
    public function settings_page() { ?>
        <div class="wrap"><h1>Calculette Irrigation</h1>
        <form method="post" action="options.php"><?php settings_fields('brl_calculette_settings'); ?>
        <table class="form-table"><tr><th scope="row">URL du logo</th><td><input type="url" name="<?php echo esc_attr(self::OPT_LOGO); ?>" value="<?php echo esc_attr(get_option(self::OPT_LOGO, '')); ?>" class="regular-text" placeholder="Laisser vide pour utiliser le logo BRL intégré"></td></tr></table>
        <?php submit_button(); ?></form></div><?php
    }

    private function logo_url() {
        $custom = trim((string)get_option(self::OPT_LOGO, ''));
        return $custom ? esc_url($custom) : esc_url(plugin_dir_url(__FILE__) . 'assets/logo.jpg');
    }

    public function shortcode($atts) {
        wp_enqueue_style('brl-calculette'); wp_enqueue_script('brl-calculette');
        $saves = [];
        if (is_user_logged_in()) {
            $saved = get_user_meta(get_current_user_id(), self::META_SAVES, true);
            $saves = is_array($saved) ? array_values($saved) : [];
        }
        wp_localize_script('brl-calculette', 'BRLCalc', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('brl_calc_nonce'),
            'isLoggedIn' => is_user_logged_in(),
            'userName' => is_user_logged_in() ? wp_get_current_user()->display_name : '',
            'saved' => $saves,
        ]);
        ob_start(); ?>
        <div class="brlcalc" data-brlcalc>
            <div class="brlcalc-header">
                <img class="brlcalc-logo" src="<?php echo $this->logo_url(); ?>" alt="BRL Exploitation">
                <div><h2>Calculette programmation irrigations</h2><p>Transformez une dose à apporter en temps d'irrigation ou en volume, et inversement.</p></div>
            </div>
            <div class="brlcalc-auth" data-auth-box>
                <?php if (is_user_logged_in()): ?>
                    <strong>Compte connecté :</strong> <?php echo esc_html(wp_get_current_user()->display_name); ?>. Vos postes et recherches peuvent être sauvegardés.
                <?php else: ?>
                    <details><summary>Créer un compte ou se connecter pour sauvegarder</summary>
                        <div class="brlcalc-grid brlcalc-grid-2">
                            <form data-register-form><h3>Créer un compte</h3><input name="email" type="email" placeholder="Email" required><input name="password" type="password" placeholder="Mot de passe" required><button type="submit">Créer mon compte</button><p data-register-msg></p></form>
                            <form data-login-form><h3>Connexion</h3><input name="login" type="text" placeholder="Email ou identifiant" required><input name="password" type="password" placeholder="Mot de passe" required><button type="submit">Me connecter</button><p data-login-msg></p></form>
                        </div>
                    </details>
                <?php endif; ?>
            </div>
            <section class="brlcalc-card"><h3>1. Personnalisation de votre poste</h3>
                <div class="brlcalc-grid">
                    <label>Nom du poste <input data-field="poste" type="text" placeholder="Ex. Syrah Haut P1"></label>
                    <label>Distance entre émetteurs sur le rang (m) <input data-field="distRang" type="number" min="0" step="0.01" value="1"></label>
                    <label>Distance entre rangs / plantation (m) <input data-field="distEntreRangs" type="number" min="0" step="0.01" value="2.5"></label>
                    <label>Nombre de rampes d'irrigation <input data-field="rampes" type="number" min="0.01" step="0.01" value="2"></label>
                    <label>Débit d'un émetteur (l/h) <input data-field="debitEmetteur" type="number" min="0" step="0.01" value="1.6"></label>
                    <label>Surface du poste (m²) <input data-field="surface" type="number" min="0" step="1" value="500"></label>
                </div>
            </section>
            <section class="brlcalc-card"><h3>2. Calculs issus des caractéristiques</h3>
                <div class="brlcalc-results"><div><span>Maille</span><strong data-out="maille">-</strong><small>m²</small></div><div><span>Pluviométrie horaire</span><strong data-out="pluvio">-</strong><small>mm/h</small></div><div><span>Débit du poste</span><strong data-out="debitPoste">-</strong><small>m³/h</small></div></div>
            </section>
            <section class="brlcalc-card"><h3>3. Utilisation de la calculette</h3>
                <div class="brlcalc-grid brlcalc-grid-3">
                    <div><h4>Saisie dose</h4><label>Dose (mm)<input data-field="dose" type="number" min="0" step="0.01" value="22"></label><p>Temps : <strong data-out="tempsDose">-</strong></p><p>Volume : <strong data-out="volumeDose">-</strong> m³</p></div>
                    <div><h4>Saisie temps</h4><label>Heures<input data-field="heures" type="number" min="0" step="1" value="22"></label><label>Minutes<input data-field="minutes" type="number" min="0" max="59" step="1" value="0"></label><p>Dose : <strong data-out="doseTemps">-</strong> mm</p><p>Volume : <strong data-out="volumeTemps">-</strong> m³</p></div>
                    <div><h4>Saisie volume</h4><label>Volume (m³)<input data-field="volume" type="number" min="0" step="0.01" value="10"></label><p>Dose : <strong data-out="doseVolume">-</strong> mm</p><p>Temps : <strong data-out="tempsVolume">-</strong></p></div>
                </div>
                <button class="brlcalc-save" data-save> Sauvegarder cette recherche </button><span data-save-msg></span>
            </section>
            <section class="brlcalc-card"><h3>Mes recherches sauvegardées</h3><div data-saved-list></div></section>
        </div>
        <?php return ob_get_clean();
    }

    private function check_nonce() { if (!check_ajax_referer('brl_calc_nonce', 'nonce', false)) wp_send_json_error(['message'=>'Session expirée.'], 403); }
    public function ajax_register() {
        $this->check_nonce();
        $email = sanitize_email($_POST['email'] ?? ''); $password = (string)($_POST['password'] ?? '');
        if (!is_email($email) || strlen($password) < 6) wp_send_json_error(['message'=>'Email invalide ou mot de passe trop court.']);
        if (email_exists($email)) wp_send_json_error(['message'=>'Un compte existe déjà avec cet email.']);
        $uid = wp_create_user($email, $password, $email); if (is_wp_error($uid)) wp_send_json_error(['message'=>$uid->get_error_message()]);
        wp_set_current_user($uid); wp_set_auth_cookie($uid, true); wp_send_json_success(['message'=>'Compte créé. Rechargement...', 'reload'=>true]);
    }
    public function ajax_login() {
        $this->check_nonce();
        $user = wp_signon(['user_login'=>sanitize_text_field($_POST['login'] ?? ''), 'user_password'=>(string)($_POST['password'] ?? ''), 'remember'=>true], is_ssl());
        if (is_wp_error($user)) wp_send_json_error(['message'=>'Identifiants incorrects.']);
        wp_send_json_success(['message'=>'Connexion réussie. Rechargement...', 'reload'=>true]);
    }
    public function ajax_save() {
        $this->check_nonce(); if (!is_user_logged_in()) wp_send_json_error(['message'=>'Connectez-vous pour sauvegarder.'], 401);
        $payload = json_decode(stripslashes($_POST['payload'] ?? ''), true); if (!is_array($payload)) wp_send_json_error(['message'=>'Données invalides.']);
        $payload['id'] = uniqid('brl_', true); $payload['date'] = current_time('mysql');
        $saves = get_user_meta(get_current_user_id(), self::META_SAVES, true); if (!is_array($saves)) $saves = [];
        array_unshift($saves, $payload); $saves = array_slice($saves, 0, 50); update_user_meta(get_current_user_id(), self::META_SAVES, $saves);
        wp_send_json_success(['message'=>'Recherche sauvegardée.', 'saved'=>$saves]);
    }
    public function ajax_delete() {
        $this->check_nonce(); if (!is_user_logged_in()) wp_send_json_error(['message'=>'Non connecté.'], 401);
        $id = sanitize_text_field($_POST['id'] ?? ''); $saves = get_user_meta(get_current_user_id(), self::META_SAVES, true); if (!is_array($saves)) $saves = [];
        $saves = array_values(array_filter($saves, fn($x) => ($x['id'] ?? '') !== $id)); update_user_meta(get_current_user_id(), self::META_SAVES, $saves);
        wp_send_json_success(['saved'=>$saves]);
    }
}
new BRL_Calculette_Irrigation();
