<?php
/**
 * Plugin Name: EarthPure Shop
 * Plugin URI:  https://shop.earthpure.net
 * Description: Volledige webshop functionaliteit voor EarthPure: producten, winkelwagen, PayPal checkout, gebruikersaccounts en contactformulier. Geen WooCommerce nodig.
 * Version:     1.0.0
 * Author:      EarthPure
 * Author URI:  https://earthpure.net
 * Text Domain: earthpure-shop
 * License:     GPL v2 or later
 */

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

define( 'EP_SHOP_VERSION', '1.0.0' );
define( 'EP_SHOP_DIR', plugin_dir_path( __FILE__ ) );
define( 'EP_SHOP_URL', plugin_dir_url( __FILE__ ) );

/* =============================================
   DATABASE: Maak tabellen aan bij activatie
   ============================================= */
register_activation_hook( __FILE__, 'ep_shop_activate' );
function ep_shop_activate() {
    global $wpdb;
    $charset = $wpdb->get_charset_collate();

    // Producten tabel
    $wpdb->query("CREATE TABLE IF NOT EXISTS {$wpdb->prefix}ep_products (
        id          BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        name        VARCHAR(255) NOT NULL,
        description TEXT,
        price       DECIMAL(10,2) NOT NULL DEFAULT 0,
        image_url   VARCHAR(500),
        stock       INT DEFAULT 100,
        created_at  DATETIME DEFAULT CURRENT_TIMESTAMP
    ) $charset");

    // Bestellingen tabel
    $wpdb->query("CREATE TABLE IF NOT EXISTS {$wpdb->prefix}ep_orders (
        id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        user_id         BIGINT UNSIGNED,
        paypal_order_id VARCHAR(100),
        status          VARCHAR(50) DEFAULT 'pending',
        total           DECIMAL(10,2),
        items           LONGTEXT,
        shipping_address TEXT,
        created_at      DATETIME DEFAULT CURRENT_TIMESTAMP
    ) $charset");

    // Voeg demo-producten toe als er nog geen zijn
    $count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}ep_products");
    if ( $count == 0 ) {
        $demo = [
            ['Magnetron', 'Energiezuinige magnetron met 5 vermogensniveaus en digitaal display. 800W vermogen.', 250.00, 'https://shop.earthpure.net/wp-content/uploads/2026/05/images.jpg'],
            ['Koelkast',  'Stille koelkast met vriesvak, A+++ energielabel. 180L inhoud.', 100.00, 'https://shop.earthpure.net/wp-content/uploads/2026/05/Fridge_Thumbnail__0016_DFF180E2SSDB.jpg'],
        ];
        foreach ( $demo as [$name, $desc, $price, $img] ) {
            $wpdb->insert( $wpdb->prefix . 'ep_products', compact('name','description','price','image_url') + ['description' => $desc, 'image_url' => $img] );
        }
    }

    // Sla versie op
    update_option( 'ep_shop_version', EP_SHOP_VERSION );
    // Flush rewrite rules
    flush_rewrite_rules();
}

register_deactivation_hook( __FILE__, 'flush_rewrite_rules' );

/* =============================================
   CUSTOM POST TYPE: EP Product
   ============================================= */
add_action( 'init', 'ep_register_post_types' );
function ep_register_post_types() {
    register_post_type( 'ep_product', [
        'labels' => [
            'name'          => 'EP Producten',
            'singular_name' => 'EP Product',
            'add_new_item'  => 'Nieuw Product Toevoegen',
            'edit_item'     => 'Product Bewerken',
        ],
        'public'       => true,
        'show_in_menu' => true,
        'menu_icon'    => 'dashicons-cart',
        'supports'     => ['title', 'editor', 'thumbnail', 'excerpt'],
        'has_archive'  => true,
        'rewrite'      => ['slug' => 'producten'],
        'show_in_rest' => true,
    ]);
}

/* =============================================
   META BOXES: Prijs & Voorraad
   ============================================= */
add_action( 'add_meta_boxes', 'ep_add_product_meta_boxes' );
function ep_add_product_meta_boxes() {
    add_meta_box( 'ep_product_data', '💰 Product Details', 'ep_product_meta_box_cb', 'ep_product', 'side', 'high' );
}
function ep_product_meta_box_cb( $post ) {
    wp_nonce_field( 'ep_product_nonce', 'ep_nonce' );
    $price = get_post_meta( $post->ID, '_ep_price', true );
    $stock = get_post_meta( $post->ID, '_ep_stock', true );
    $sale  = get_post_meta( $post->ID, '_ep_sale_price', true );
    ?>
    <p>
        <label><strong>Prijs (€)</strong></label><br>
        <input type="number" name="ep_price" value="<?php echo esc_attr($price); ?>" step="0.01" min="0" style="width:100%">
    </p>
    <p>
        <label><strong>Sale prijs (€, optioneel)</strong></label><br>
        <input type="number" name="ep_sale_price" value="<?php echo esc_attr($sale); ?>" step="0.01" min="0" style="width:100%">
    </p>
    <p>
        <label><strong>Voorraad</strong></label><br>
        <input type="number" name="ep_stock" value="<?php echo esc_attr($stock ?: 100); ?>" min="0" style="width:100%">
    </p>
    <?php
}

add_action( 'save_post_ep_product', 'ep_save_product_meta' );
function ep_save_product_meta( $post_id ) {
    if ( ! isset($_POST['ep_nonce']) || ! wp_verify_nonce($_POST['ep_nonce'], 'ep_product_nonce') ) return;
    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return;
    if ( isset($_POST['ep_price']) )      update_post_meta( $post_id, '_ep_price',      floatval($_POST['ep_price']) );
    if ( isset($_POST['ep_sale_price']) ) update_post_meta( $post_id, '_ep_sale_price', floatval($_POST['ep_sale_price']) );
    if ( isset($_POST['ep_stock']) )      update_post_meta( $post_id, '_ep_stock',      intval($_POST['ep_stock']) );
}

/* =============================================
   SHORTCODES
   ============================================= */

// [ep_products] - Toont productenraster
add_shortcode( 'ep_products', 'ep_products_shortcode' );
function ep_products_shortcode( $atts ) {
    $atts = shortcode_atts(['limit' => 12, 'columns' => 3], $atts);
    $posts = get_posts([
        'post_type'      => 'ep_product',
        'posts_per_page' => intval($atts['limit']),
        'post_status'    => 'publish',
    ]);
    ob_start();
    echo '<div class="ep-products-grid" style="display:grid;grid-template-columns:repeat(' . intval($atts['columns']) . ',1fr);gap:24px;">';
    foreach ( $posts as $post ) {
        $price      = get_post_meta( $post->ID, '_ep_price', true );
        $sale_price = get_post_meta( $post->ID, '_ep_sale_price', true );
        $img        = get_the_post_thumbnail_url( $post->ID, 'medium' ) ?: EP_SHOP_URL . 'assets/placeholder.jpg';
        $display_price = $sale_price ? '<del>€' . number_format($price,2,',','.') . '</del> <strong style="color:#e53935">€' . number_format($sale_price,2,',','.') . '</strong>' : '€' . number_format($price,2,',','.');
        echo '<div class="ep-product-card" style="background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 4px 20px rgba(0,0,0,0.08);">';
        echo '<img src="' . esc_url($img) . '" alt="' . esc_attr($post->post_title) . '" style="width:100%;height:200px;object-fit:cover;">';
        echo '<div style="padding:16px;">';
        echo '<h3 style="margin:0 0 8px;font-size:1rem;">' . esc_html($post->post_title) . '</h3>';
        echo '<p style="font-size:0.88rem;color:#757575;margin-bottom:12px;">' . wp_trim_words($post->post_excerpt ?: $post->post_content, 15) . '</p>';
        echo '<div style="font-size:1.2rem;font-weight:800;color:#4CAF50;margin-bottom:14px;">' . $display_price . '</div>';
        echo '<button class="ep-add-to-cart btn btn-primary" data-id="' . $post->ID . '" data-name="' . esc_attr($post->post_title) . '" data-price="' . esc_attr($price ?: $sale_price) . '" data-img="' . esc_url($img) . '" style="width:100%;padding:10px;border-radius:50px;background:#4CAF50;color:#fff;border:none;cursor:pointer;font-weight:600;">🛒 In winkelwagen</button>';
        echo '</div></div>';
    }
    echo '</div>';
    return ob_get_clean();
}

// [ep_cart] - Toont mini cart button
add_shortcode( 'ep_cart', 'ep_cart_shortcode' );
function ep_cart_shortcode() {
    return '<button id="ep-cart-btn" onclick="epOpenCart()" style="background:#4CAF50;color:#fff;border:none;padding:12px 24px;border-radius:50px;cursor:pointer;font-weight:700;font-size:1rem;">🛒 Winkelwagen (<span id="ep-cart-count">0</span>)</button>';
}

// [ep_contact_form] - Contactformulier
add_shortcode( 'ep_contact', 'ep_contact_shortcode' );
function ep_contact_shortcode() {
    ob_start(); ?>
    <form id="ep-contact-form" style="display:flex;flex-direction:column;gap:14px;max-width:600px;">
        <?php wp_nonce_field('ep_contact_nonce','ep_contact_nonce_field'); ?>
        <input type="text" name="name" placeholder="Naam *" required style="padding:14px;border:2px solid #e0e0e0;border-radius:10px;font-size:0.95rem;">
        <input type="email" name="email" placeholder="E-mail *" required style="padding:14px;border:2px solid #e0e0e0;border-radius:10px;font-size:0.95rem;">
        <input type="tel" name="phone" placeholder="Telefoon" style="padding:14px;border:2px solid #e0e0e0;border-radius:10px;font-size:0.95rem;">
        <textarea name="message" placeholder="Bericht *" required rows="5" style="padding:14px;border:2px solid #e0e0e0;border-radius:10px;font-size:0.95rem;resize:vertical;"></textarea>
        <button type="submit" style="padding:14px;background:#4CAF50;color:#fff;border:none;border-radius:50px;font-weight:700;cursor:pointer;font-size:1rem;">✉️ Verstuur bericht</button>
        <div id="ep-contact-response" style="display:none;padding:12px;border-radius:8px;"></div>
    </form>
    <?php return ob_get_clean();
}

/* =============================================
   AJAX: Winkelwagen (session-based)
   ============================================= */
add_action( 'init', function() { if ( ! session_id() ) session_start(); });

// Cart ophalen
add_action( 'wp_ajax_ep_get_cart',        'ep_get_cart_handler' );
add_action( 'wp_ajax_nopriv_ep_get_cart', 'ep_get_cart_handler' );
function ep_get_cart_handler() {
    wp_send_json_success( $_SESSION['ep_cart'] ?? [] );
}

// Toevoegen aan winkelwagen
add_action( 'wp_ajax_ep_add_to_cart',        'ep_add_to_cart_handler' );
add_action( 'wp_ajax_nopriv_ep_add_to_cart', 'ep_add_to_cart_handler' );
function ep_add_to_cart_handler() {
    check_ajax_referer( 'ep_shop_nonce', 'nonce' );
    $id    = intval( $_POST['product_id'] );
    $name  = sanitize_text_field( $_POST['name'] );
    $price = floatval( $_POST['price'] );
    $img   = esc_url_raw( $_POST['img'] );

    if ( ! isset($_SESSION['ep_cart']) ) $_SESSION['ep_cart'] = [];
    $cart = &$_SESSION['ep_cart'];

    if ( isset($cart[$id]) ) {
        $cart[$id]['qty']++;
    } else {
        $cart[$id] = ['id' => $id, 'name' => $name, 'price' => $price, 'img' => $img, 'qty' => 1];
    }
    $total = array_sum( array_map(fn($i) => $i['price'] * $i['qty'], $cart) );
    wp_send_json_success([ 'cart' => array_values($cart), 'count' => count($cart), 'total' => $total ]);
}

// Verwijderen uit winkelwagen
add_action( 'wp_ajax_ep_remove_from_cart',        'ep_remove_from_cart_handler' );
add_action( 'wp_ajax_nopriv_ep_remove_from_cart', 'ep_remove_from_cart_handler' );
function ep_remove_from_cart_handler() {
    check_ajax_referer( 'ep_shop_nonce', 'nonce' );
    $id = intval( $_POST['product_id'] );
    if ( isset($_SESSION['ep_cart'][$id]) ) unset($_SESSION['ep_cart'][$id]);
    $cart  = $_SESSION['ep_cart'] ?? [];
    $total = array_sum( array_map(fn($i) => $i['price'] * $i['qty'], $cart) );
    wp_send_json_success([ 'cart' => array_values($cart), 'count' => count($cart), 'total' => $total ]);
}

/* =============================================
   AJAX: Contactformulier
   ============================================= */
add_action( 'wp_ajax_ep_contact_submit',        'ep_contact_submit_handler' );
add_action( 'wp_ajax_nopriv_ep_contact_submit', 'ep_contact_submit_handler' );
function ep_contact_submit_handler() {
    check_ajax_referer( 'ep_contact_nonce', 'nonce' );
    $name    = sanitize_text_field( $_POST['name'] ?? '' );
    $email   = sanitize_email( $_POST['email'] ?? '' );
    $phone   = sanitize_text_field( $_POST['phone'] ?? '' );
    $message = sanitize_textarea_field( $_POST['message'] ?? '' );
    if ( empty($name) || empty($email) || empty($message) ) {
        wp_send_json_error(['msg' => 'Vul alle verplichte velden in.']);
    }
    $to      = get_option('admin_email');
    $subject = 'Nieuw bericht van ' . $name;
    $body    = "Naam: $name\nEmail: $email\nTelefoon: $phone\n\nBericht:\n$message";
    wp_mail( $to, $subject, $body, ["Reply-To: $email"] );
    wp_send_json_success(['msg' => 'Bericht verstuurd! We nemen snel contact op.']);
}

/* =============================================
   AJAX: Bestelling aanmaken
   ============================================= */
add_action( 'wp_ajax_ep_create_order',        'ep_create_order_handler' );
add_action( 'wp_ajax_nopriv_ep_create_order', 'ep_create_order_handler' );
function ep_create_order_handler() {
    check_ajax_referer( 'ep_shop_nonce', 'nonce' );
    global $wpdb;
    $cart     = $_SESSION['ep_cart'] ?? [];
    $address  = sanitize_textarea_field( $_POST['address'] ?? '' );
    $user_id  = get_current_user_id();
    $total    = array_sum( array_map(fn($i) => $i['price'] * $i['qty'], $cart) );

    $wpdb->insert( $wpdb->prefix . 'ep_orders', [
        'user_id'         => $user_id ?: null,
        'status'          => 'pending_payment',
        'total'           => $total,
        'items'           => json_encode($cart),
        'shipping_address'=> $address,
    ]);
    $order_id = $wpdb->insert_id;
    $_SESSION['ep_pending_order'] = $order_id;

    wp_send_json_success([ 'order_id' => $order_id, 'total' => $total ]);
}

// Bestelling voltooien na PayPal
add_action( 'wp_ajax_ep_complete_order',        'ep_complete_order_handler' );
add_action( 'wp_ajax_nopriv_ep_complete_order', 'ep_complete_order_handler' );
function ep_complete_order_handler() {
    check_ajax_referer( 'ep_shop_nonce', 'nonce' );
    global $wpdb;
    $order_id       = intval( $_POST['order_id'] );
    $paypal_order_id = sanitize_text_field( $_POST['paypal_order_id'] );
    $wpdb->update( $wpdb->prefix . 'ep_orders',
        ['status' => 'completed', 'paypal_order_id' => $paypal_order_id],
        ['id' => $order_id]
    );
    $_SESSION['ep_cart'] = [];
    wp_send_json_success(['msg' => 'Bestelling voltooid! Bedankt voor je aankoop.']);
}

/* =============================================
   ENQUEUE: Stijlen & scripts
   ============================================= */
add_action( 'wp_enqueue_scripts', 'ep_shop_enqueue' );
function ep_shop_enqueue() {
    wp_enqueue_style( 'ep-shop-style', EP_SHOP_URL . 'assets/shop.css', [], EP_SHOP_VERSION );
    wp_enqueue_script( 'ep-shop-script', EP_SHOP_URL . 'assets/shop.js', ['jquery'], EP_SHOP_VERSION, true );
    wp_localize_script( 'ep-shop-script', 'epShop', [
        'ajaxUrl'     => admin_url('admin-ajax.php'),
        'nonce'       => wp_create_nonce('ep_shop_nonce'),
        'contactNonce'=> wp_create_nonce('ep_contact_nonce'),
        'paypalId'    => get_option('ep_paypal_client_id', ''),
        'currency'    => get_option('ep_currency', 'USD'),
    ]);
}

/* =============================================
   ADMIN: Bestellingen overzicht
   ============================================= */
add_action( 'admin_menu', 'ep_shop_admin_menu' );
function ep_shop_admin_menu() {
    add_menu_page( 'EarthPure Shop', 'EP Bestellingen', 'manage_options', 'ep-orders', 'ep_orders_page', 'dashicons-cart', 56 );
    add_submenu_page( 'ep-orders', 'Instellingen', 'Instellingen', 'manage_options', 'ep-settings', 'ep_settings_page' );
}

function ep_orders_page() {
    global $wpdb;
    $orders = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}ep_orders ORDER BY created_at DESC LIMIT 50");
    echo '<div class="wrap"><h1>📦 EarthPure Bestellingen</h1>';
    echo '<table class="wp-list-table widefat fixed striped"><thead><tr><th>#</th><th>Datum</th><th>Status</th><th>Totaal</th><th>Producten</th><th>PayPal ID</th></tr></thead><tbody>';
    foreach ( $orders as $o ) {
        $items = json_decode($o->items, true);
        $names = implode(', ', array_column($items ?? [], 'name'));
        $status_colors = ['completed' => '#2e7d32', 'pending' => '#f57c00', 'pending_payment' => '#1565c0'];
        $color = $status_colors[$o->status] ?? '#333';
        echo "<tr><td>{$o->id}</td><td>{$o->created_at}</td><td style='color:{$color};font-weight:600'>{$o->status}</td><td>€{$o->total}</td><td>{$names}</td><td>{$o->paypal_order_id}</td></tr>";
    }
    echo '</tbody></table></div>';
}

function ep_settings_page() {
    if ( isset($_POST['ep_save_settings']) ) {
        check_admin_referer('ep_settings_nonce');
        update_option('ep_paypal_client_id', sanitize_text_field($_POST['ep_paypal_client_id']));
        update_option('ep_currency', sanitize_text_field($_POST['ep_currency']));
        update_option('ep_shop_email', sanitize_email($_POST['ep_shop_email']));
        echo '<div class="notice notice-success"><p>✅ Instellingen opgeslagen!</p></div>';
    }
    $client_id = get_option('ep_paypal_client_id', '');
    $currency  = get_option('ep_currency', 'USD');
    $shop_email= get_option('ep_shop_email', get_option('admin_email'));
    ?>
    <div class="wrap">
        <h1>⚙️ EarthPure Shop Instellingen</h1>
        <form method="post">
            <?php wp_nonce_field('ep_settings_nonce'); ?>
            <table class="form-table">
                <tr>
                    <th>PayPal Client ID</th>
                    <td>
                        <input type="text" name="ep_paypal_client_id" value="<?php echo esc_attr($client_id); ?>" class="regular-text">
                        <p class="description">Haal je Client ID op via <a href="https://developer.paypal.com" target="_blank">developer.paypal.com</a></p>
                    </td>
                </tr>
                <tr>
                    <th>Valuta</th>
                    <td>
                        <select name="ep_currency">
                            <?php foreach (['USD'=>'USD ($)', 'EUR'=>'EUR (€)', 'GBP'=>'GBP (£)', 'SRD'=>'SRD (Sr$)'] as $k=>$v) : ?>
                                <option value="<?php echo $k; ?>" <?php selected($currency, $k); ?>><?php echo $v; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th>Winkel e-mailadres</th>
                    <td><input type="email" name="ep_shop_email" value="<?php echo esc_attr($shop_email); ?>" class="regular-text"></td>
                </tr>
            </table>
            <p><input type="submit" name="ep_save_settings" class="button-primary" value="Instellingen Opslaan"></p>
        </form>
    </div>
    <?php
}
