<?php
/**
 * RentCar Pro Functions
 * 
 * @package RentCar_Pro
 */

// Configuración del tema
function rentcar_setup() {
    add_theme_support('title-tag');
    add_theme_support('post-thumbnails');
    add_theme_support('html5', array('search-form', 'comment-form', 'comment-list', 'gallery', 'caption'));
    add_theme_support('custom-logo', array(
        'height' => 100,
        'width' => 250,
        'flex-height' => true,
        'flex-width' => true,
    ));
    
    register_nav_menus(array(
        'primary' => __('Menú Principal', 'rentcar-pro'),
        'footer' => __('Menú Footer', 'rentcar-pro'),
    ));
    
    // Tamaños de imagen personalizados
    add_image_size('vehicle-thumbnail', 400, 300, true);
    add_image_size('vehicle-large', 800, 600, true);
}
add_action('after_setup_theme', 'rentcar_setup');

// Enqueue estilos y scripts
function rentcar_scripts() {
    wp_enqueue_style('rentcar-fonts', 'https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800&family=Poppins:wght@300;400;500;600;700&display=swap', array(), null);
    wp_enqueue_style('font-awesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css', array(), '6.4.0');
    wp_enqueue_style('animate-css', 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css', array(), '4.1.1');
    wp_enqueue_style('rentcar-style', get_stylesheet_uri(), array(), '1.0.0');
    wp_enqueue_style('rentcar-custom', get_template_directory_uri() . '/css/custom.css', array(), '1.0.0');
    wp_enqueue_style('rentcar-booking', get_template_directory_uri() . '/css/booking-form-styles.css', array(), '1.0.0');
    wp_enqueue_script('jquery');
    wp_enqueue_script('rentcar-main', get_template_directory_uri() . '/js/main.js', array('jquery'), '1.0.0', true);
    
    wp_localize_script('rentcar-main', 'rentcar_ajax', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('rentcar_nonce')
    ));
}
add_action('wp_enqueue_scripts', 'rentcar_scripts');

// Registrar widgets
function rentcar_widgets_init() {
    register_sidebar(array(
        'name' => __('Sidebar Principal', 'rentcar-pro'),
        'id' => 'sidebar-1',
        'before_widget' => '<div id="%1$s" class="widget %2$s">',
        'after_widget' => '</div>',
        'before_title' => '<h3 class="widget-title">',
        'after_title' => '</h3>',
    ));
    
    for ($i = 1; $i <= 3; $i++) {
        register_sidebar(array(
            'name' => sprintf(__('Footer %d', 'rentcar-pro'), $i),
            'id' => 'footer-' . $i,
            'before_widget' => '<div id="%1$s" class="widget %2$s">',
            'after_widget' => '</div>',
            'before_title' => '<h3 class="widget-title">',
            'after_title' => '</h3>',
        ));
    }
}
add_action('widgets_init', 'rentcar_widgets_init');

// Custom Post Type: Vehículos
function rentcar_register_vehicles_post_type() {
    $labels = array(
        'name' => __('Vehículos', 'rentcar-pro'),
        'singular_name' => __('Vehículo', 'rentcar-pro'),
        'add_new' => __('Agregar Nuevo', 'rentcar-pro'),
        'add_new_item' => __('Agregar Nuevo Vehículo', 'rentcar-pro'),
        'edit_item' => __('Editar Vehículo', 'rentcar-pro'),
        'new_item' => __('Nuevo Vehículo', 'rentcar-pro'),
        'view_item' => __('Ver Vehículo', 'rentcar-pro'),
        'search_items' => __('Buscar Vehículos', 'rentcar-pro'),
        'not_found' => __('No se encontraron vehículos', 'rentcar-pro'),
        'menu_name' => __('Vehículos', 'rentcar-pro'),
    );
    
    $args = array(
        'labels' => $labels,
        'public' => true,
        'has_archive' => true,
        'menu_icon' => 'dashicons-car',
        'supports' => array('title', 'editor', 'thumbnail', 'custom-fields'),
        'rewrite' => array('slug' => 'vehiculos'),
        'show_in_rest' => true,
    );
    
    register_post_type('vehicles', $args);
}
add_action('init', 'rentcar_register_vehicles_post_type');

// Taxonomía: Categorías de Vehículos
function rentcar_register_vehicle_taxonomy() {
    $labels = array(
        'name' => __('Categorías', 'rentcar-pro'),
        'singular_name' => __('Categoría', 'rentcar-pro'),
        'search_items' => __('Buscar Categorías', 'rentcar-pro'),
        'all_items' => __('Todas las Categorías', 'rentcar-pro'),
        'edit_item' => __('Editar Categoría', 'rentcar-pro'),
        'update_item' => __('Actualizar Categoría', 'rentcar-pro'),
        'add_new_item' => __('Agregar Nueva Categoría', 'rentcar-pro'),
        'new_item_name' => __('Nuevo Nombre de Categoría', 'rentcar-pro'),
        'menu_name' => __('Categorías', 'rentcar-pro'),
    );
    
    $args = array(
        'labels' => $labels,
        'hierarchical' => true,
        'show_ui' => true,
        'show_admin_column' => true,
        'query_var' => true,
        'rewrite' => array('slug' => 'categoria-vehiculo'),
        'show_in_rest' => true,
    );
    
    register_taxonomy('vehicle_category', array('vehicles'), $args);
}
add_action('init', 'rentcar_register_vehicle_taxonomy');

// Custom Post Type: Seguros
function rentcar_register_insurance_post_type() {
    $labels = array(
        'name' => __('Seguros', 'rentcar-pro'),
        'singular_name' => __('Seguro', 'rentcar-pro'),
        'add_new' => __('Agregar Nuevo', 'rentcar-pro'),
        'add_new_item' => __('Agregar Nuevo Seguro', 'rentcar-pro'),
        'edit_item' => __('Editar Seguro', 'rentcar-pro'),
        'menu_name' => __('Seguros', 'rentcar-pro'),
    );
    
    $args = array(
        'labels' => $labels,
        'public' => true,
        'has_archive' => true,
        'menu_icon' => 'dashicons-shield',
        'supports' => array('title', 'editor', 'thumbnail'),
        'rewrite' => array('slug' => 'seguros'),
        'show_in_rest' => true,
    );
    
    register_post_type('insurance', $args);
}
add_action('init', 'rentcar_register_insurance_post_type');

// Meta boxes para vehículos
function rentcar_add_vehicle_meta_boxes() {
    add_meta_box(
        'vehicle_details',
        __('Detalles del Vehículo', 'rentcar-pro'),
        'rentcar_vehicle_details_callback',
        'vehicles',
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'rentcar_add_vehicle_meta_boxes');

function rentcar_vehicle_details_callback($post) {
    wp_nonce_field('rentcar_vehicle_details', 'rentcar_vehicle_details_nonce');
    
    $price = get_post_meta($post->ID, '_vehicle_price', true);
    $passengers = get_post_meta($post->ID, '_vehicle_passengers', true);
    $luggage = get_post_meta($post->ID, '_vehicle_luggage', true);
    $transmission = get_post_meta($post->ID, '_vehicle_transmission', true);
    $doors = get_post_meta($post->ID, '_vehicle_doors', true);
    ?>
    <table class="form-table">
        <tr>
            <th><label for="vehicle_price">Precio por Día ($)</label></th>
            <td><input type="number" id="vehicle_price" name="vehicle_price" value="<?php echo esc_attr($price); ?>" class="regular-text" step="0.01"></td>
        </tr>
        <tr>
            <th><label for="vehicle_passengers">Pasajeros</label></th>
            <td><input type="number" id="vehicle_passengers" name="vehicle_passengers" value="<?php echo esc_attr($passengers); ?>" class="small-text"></td>
        </tr>
        <tr>
            <th><label for="vehicle_luggage">Maletas</label></th>
            <td><input type="number" id="vehicle_luggage" name="vehicle_luggage" value="<?php echo esc_attr($luggage); ?>" class="small-text"></td>
        </tr>
        <tr>
            <th><label for="vehicle_doors">Puertas</label></th>
            <td><input type="number" id="vehicle_doors" name="vehicle_doors" value="<?php echo esc_attr($doors); ?>" class="small-text"></td>
        </tr>
        <tr>
            <th><label for="vehicle_transmission">Transmisión</label></th>
            <td>
                <select id="vehicle_transmission" name="vehicle_transmission">
                    <option value="Manual" <?php selected($transmission, 'Manual'); ?>>Manual</option>
                    <option value="Automático" <?php selected($transmission, 'Automático'); ?>>Automático</option>
                </select>
            </td>
        </tr>
    </table>
    <?php
}

function rentcar_save_vehicle_details($post_id) {
    if (!isset($_POST['rentcar_vehicle_details_nonce']) || 
        !wp_verify_nonce($_POST['rentcar_vehicle_details_nonce'], 'rentcar_vehicle_details')) {
        return;
    }
    
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    
    $fields = array('price', 'passengers', 'luggage', 'transmission', 'doors');
    
    foreach ($fields as $field) {
        if (isset($_POST['vehicle_' . $field])) {
            update_post_meta($post_id, '_vehicle_' . $field, sanitize_text_field($_POST['vehicle_' . $field]));
        }
    }
}
add_action('save_post_vehicles', 'rentcar_save_vehicle_details');

// Shortcode para formulario de contacto
function rentcar_contact_form_shortcode() {
    ob_start();
    ?>
    <div class="contact-form-wrapper">
        <form id="rentcar-contact-form" class="contact-form">
            <div class="form-row">
                <div class="form-group">
                    <input type="text" name="name" placeholder="Nombre completo *" required>
                </div>
                <div class="form-group">
                    <input type="email" name="email" placeholder="Correo electrónico *" required>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <input type="tel" name="phone" placeholder="Teléfono *" required>
                </div>
                <div class="form-group">
                    <input type="text" name="subject" placeholder="Asunto" required>
                </div>
            </div>
            <div class="form-group">
                <textarea name="message" rows="6" placeholder="Mensaje *" required></textarea>
            </div>
            <button type="submit" class="btn-primary">
                <i class="fas fa-paper-plane"></i> Enviar Mensaje
            </button>
            <div class="form-message"></div>
        </form>
    </div>
    <?php
    return ob_get_clean();
}
add_shortcode('rentcar_contact_form', 'rentcar_contact_form_shortcode');

// AJAX para formulario de contacto
function rentcar_handle_contact_form() {
    check_ajax_referer('rentcar_nonce', 'nonce');
    
    $name = sanitize_text_field($_POST['name']);
    $email = sanitize_email($_POST['email']);
    $phone = sanitize_text_field($_POST['phone']);
    $subject = sanitize_text_field($_POST['subject']);
    $message = sanitize_textarea_field($_POST['message']);
    
    $to = get_option('admin_email');
    $headers = array('Content-Type: text/html; charset=UTF-8', 'From: ' . $name . ' <' . $email . '>');
    
    $body = "<h2>Nuevo mensaje de contacto</h2>";
    $body .= "<p><strong>Nombre:</strong> $name</p>";
    $body .= "<p><strong>Email:</strong> $email</p>";
    $body .= "<p><strong>Teléfono:</strong> $phone</p>";
    $body .= "<p><strong>Mensaje:</strong><br>$message</p>";
    
    if (wp_mail($to, $subject, $body, $headers)) {
        wp_send_json_success('Mensaje enviado correctamente');
    } else {
        wp_send_json_error('Error al enviar el mensaje');
    }
}
add_action('wp_ajax_rentcar_contact', 'rentcar_handle_contact_form');
add_action('wp_ajax_nopriv_rentcar_contact', 'rentcar_handle_contact_form');



// Cambiar el slug del post type Insurance
function rentcar_modify_insurance_slug() {
    // Obtener las etiquetas originales
    $labels = array(
        'name' => __('Seguros', 'rentcar-pro'),
        'singular_name' => __('Seguro', 'rentcar-pro'),
        'add_new' => __('Agregar Nuevo', 'rentcar-pro'),
        'add_new_item' => __('Agregar Nuevo Seguro', 'rentcar-pro'),
        'edit_item' => __('Editar Seguro', 'rentcar-pro'),
        'menu_name' => __('Seguros', 'rentcar-pro'),
    );
    
    // Registrar nuevamente con el nuevo slug
    $args = array(
        'labels' => $labels,
        'public' => false,  // ← CAMBIO: false para que no aparezca públicamente
        'publicly_queryable' => false, // ← No se puede acceder por URL
        'show_ui' => true,  // ← Sí aparece en el admin
        'show_in_menu' => true,
        'has_archive' => false,  // ← SIN archivo público
        'menu_icon' => 'dashicons-shield',
        'supports' => array('title', 'editor', 'thumbnail'),
        'rewrite' => array('slug' => 'seguros-admin'), // ← Nueva URL (solo para admin)
        'show_in_rest' => true,
    );
    
    // Registrar el post type con la nueva configuración
    register_post_type('insurance', $args);
}
// Prioridad 999 para ejecutarse DESPUÉS del plugin
add_action('init', 'rentcar_modify_insurance_slug', 999);

// Regenerar permalinks (solo una vez)
function rentcar_flush_rules_once() {
    if (get_option('rentcar_insurance_flushed') != 'yes') {
        flush_rewrite_rules();
        update_option('rentcar_insurance_flushed', 'yes');
    }
}
add_action('init', 'rentcar_flush_rules_once', 9999);

// Agregar producto de alquiler al carrito
add_action('template_redirect', 'rentcar_add_rental_to_cart');
function rentcar_add_rental_to_cart() {
    if (isset($_POST['vehicle_id']) && isset($_POST['total_price'])) {
        
        // Crear producto temporal o usar uno existente
        $product_id = 123; // ID del producto "Alquiler de Vehículo" en WooCommerce
        
        $cart_item_data = array(
            'vehicle_id' => sanitize_text_field($_POST['vehicle_id']),
            'vehicle_name' => sanitize_text_field($_POST['vehicle_name']),
            'rental_days' => sanitize_text_field($_POST['rental_days']),
            'pickup_location' => sanitize_text_field($_POST['pickup_location']),
            'pickup_date' => sanitize_text_field($_POST['pickup_date']),
            'pickup_time' => sanitize_text_field($_POST['pickup_time']),
            'return_location' => sanitize_text_field($_POST['return_location']),
            'return_date' => sanitize_text_field($_POST['return_date']),
            'return_time' => sanitize_text_field($_POST['return_time']),
        );
        
        WC()->cart->add_to_cart($product_id, 1, 0, array(), $cart_item_data);
        
        // Redirigir al checkout
        wp_redirect(wc_get_checkout_url());
        exit;
    }
}

?>
