<?php
/**
 * Develop Sri Lanka Theme Functions
 *
 * @package DevelopSriLanka
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Theme Setup
 */
function develop_srilanka_setup() {
    // Add theme support
    add_theme_support('title-tag');
    add_theme_support('post-thumbnails');
    add_theme_support('custom-logo');
    add_theme_support('html5', array(
        'search-form',
        'comment-form',
        'comment-list',
        'gallery',
        'caption',
    ));
    
    // Register navigation menus
    register_nav_menus(array(
        'primary' => __('Primary Menu', 'develop-srilanka'),
        'footer' => __('Footer Menu', 'develop-srilanka'),
    ));
    
    // Add featured image sizes
    add_image_size('hero-large', 1920, 1080, true);
    add_image_size('destination-thumb', 400, 300, true);
    add_image_size('experience-thumb', 600, 400, true);
}
add_action('after_setup_theme', 'develop_srilanka_setup');

/**
 * Enqueue scripts and styles
 */
function develop_srilanka_scripts() {
    // Enqueue main stylesheet
    wp_enqueue_style('develop-srilanka-style', get_stylesheet_uri(), array(), '1.0.0');
    
    // Enqueue custom JavaScript
    wp_enqueue_script('develop-srilanka-main', get_template_directory_uri() . '/js/main.js', array('jquery'), '1.0.0', true);
    
    // Localize script for AJAX
    wp_localize_script('develop-srilanka-main', 'srilankaAjax', array(
        'ajaxurl' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('srilanka_nonce')
    ));
}
add_action('wp_enqueue_scripts', 'develop_srilanka_scripts');

/**
 * Register widget areas
 */
function develop_srilanka_widgets_init() {
    register_sidebar(array(
        'name' => __('Footer Widget 1', 'develop-srilanka'),
        'id' => 'footer-1',
        'description' => __('Add widgets for footer column 1', 'develop-srilanka'),
        'before_widget' => '<div class="footer-widget">',
        'after_widget' => '</div>',
        'before_title' => '<h3 class="widget-title">',
        'after_title' => '</h3>',
    ));
    
    register_sidebar(array(
        'name' => __('Footer Widget 2', 'develop-srilanka'),
        'id' => 'footer-2',
        'description' => __('Add widgets for footer column 2', 'develop-srilanka'),
        'before_widget' => '<div class="footer-widget">',
        'after_widget' => '</div>',
        'before_title' => '<h3 class="widget-title">',
        'after_title' => '</h3>',
    ));
    
    register_sidebar(array(
        'name' => __('Footer Widget 3', 'develop-srilanka'),
        'id' => 'footer-3',
        'description' => __('Add widgets for footer column 3', 'develop-srilanka'),
        'before_widget' => '<div class="footer-widget">',
        'after_widget' => '</div>',
        'before_title' => '<h3 class="widget-title">',
        'after_title' => '</h3>',
    ));
}
add_action('widgets_init', 'develop_srilanka_widgets_init');

/**
 * Custom Post Type: Hero Slider
 */
function register_hero_slider_post_type() {
    $labels = array(
        'name' => __('Hero Slider', 'develop-srilanka'),
        'singular_name' => __('Slide', 'develop-srilanka'),
        'add_new' => __('Add New Slide', 'develop-srilanka'),
        'add_new_item' => __('Add New Slide', 'develop-srilanka'),
        'edit_item' => __('Edit Slide', 'develop-srilanka'),
        'new_item' => __('New Slide', 'develop-srilanka'),
        'view_item' => __('View Slide', 'develop-srilanka'),
        'search_items' => __('Search Slides', 'develop-srilanka'),
        'not_found' => __('No slides found', 'develop-srilanka'),
        'not_found_in_trash' => __('No slides found in trash', 'develop-srilanka'),
    );
    
    $args = array(
        'labels' => $labels,
        'public' => false,
        'show_ui' => true,
        'show_in_menu' => true,
        'menu_icon' => 'dashicons-images-alt2',
        'supports' => array('title', 'thumbnail'),
        'rewrite' => false,
        'publicly_queryable' => false,
    );
    
    register_post_type('hero_slider', $args);
}
add_action('init', 'register_hero_slider_post_type');

/**
 * Add meta boxes for hero slider
 */
function hero_slider_meta_boxes() {
    add_meta_box(
        'hero_slider_details',
        __('Slide Details', 'develop-srilanka'),
        'hero_slider_meta_box_callback',
        'hero_slider',
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'hero_slider_meta_boxes');

/**
 * Hero slider meta box callback
 */
function hero_slider_meta_box_callback($post) {
    wp_nonce_field('hero_slider_meta_box', 'hero_slider_meta_box_nonce');
    
    $subtitle = get_post_meta($post->ID, '_slide_subtitle', true);
    $button_text = get_post_meta($post->ID, '_slide_button_text', true);
    $button_link = get_post_meta($post->ID, '_slide_button_link', true);
    $order = get_post_meta($post->ID, '_slide_order', true);
    ?>
    <p>
        <label for="slide_subtitle"><?php _e('Subtitle/Description:', 'develop-srilanka'); ?></label><br>
        <input type="text" id="slide_subtitle" name="slide_subtitle" value="<?php echo esc_attr($subtitle); ?>" style="width: 100%;" placeholder="The Pearl of the Indian Ocean">
    </p>
    <p>
        <label for="slide_button_text"><?php _e('Button Text:', 'develop-srilanka'); ?></label><br>
        <input type="text" id="slide_button_text" name="slide_button_text" value="<?php echo esc_attr($button_text); ?>" style="width: 100%;" placeholder="Explore Sri Lanka">
    </p>
    <p>
        <label for="slide_button_link"><?php _e('Button Link:', 'develop-srilanka'); ?></label><br>
        <input type="text" id="slide_button_link" name="slide_button_link" value="<?php echo esc_attr($button_link); ?>" style="width: 100%;" placeholder="#featured">
    </p>
    <p>
        <label for="slide_order"><?php _e('Display Order:', 'develop-srilanka'); ?></label><br>
        <input type="number" id="slide_order" name="slide_order" value="<?php echo esc_attr($order ? $order : 0); ?>" style="width: 100px;" min="0">
        <small>Lower numbers appear first</small>
    </p>
    <p>
        <strong><?php _e('Featured Image:', 'develop-srilanka'); ?></strong><br>
        <small>Set the featured image for this slide (recommended size: 1920x1080)</small>
    </p>
    <?php
}

/**
 * Save hero slider meta box data
 */
function save_hero_slider_meta_box($post_id) {
    if (!isset($_POST['hero_slider_meta_box_nonce']) || !wp_verify_nonce($_POST['hero_slider_meta_box_nonce'], 'hero_slider_meta_box')) {
        return;
    }
    
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    
    if (isset($_POST['slide_subtitle'])) {
        update_post_meta($post_id, '_slide_subtitle', sanitize_text_field($_POST['slide_subtitle']));
    }
    
    if (isset($_POST['slide_button_text'])) {
        update_post_meta($post_id, '_slide_button_text', sanitize_text_field($_POST['slide_button_text']));
    }
    
    if (isset($_POST['slide_button_link'])) {
        update_post_meta($post_id, '_slide_button_link', esc_url_raw($_POST['slide_button_link']));
    }
    
    if (isset($_POST['slide_order'])) {
        update_post_meta($post_id, '_slide_order', intval($_POST['slide_order']));
    }
}
add_action('save_post_hero_slider', 'save_hero_slider_meta_box');

/**
 * Custom Post Type: Experiences
 */
function register_experience_post_type() {
    $labels = array(
        'name' => __('Experiences', 'develop-srilanka'),
        'singular_name' => __('Experience', 'develop-srilanka'),
        'add_new' => __('Add New', 'develop-srilanka'),
        'add_new_item' => __('Add New Experience', 'develop-srilanka'),
        'edit_item' => __('Edit Experience', 'develop-srilanka'),
        'new_item' => __('New Experience', 'develop-srilanka'),
        'view_item' => __('View Experience', 'develop-srilanka'),
        'search_items' => __('Search Experiences', 'develop-srilanka'),
        'not_found' => __('No experiences found', 'develop-srilanka'),
        'not_found_in_trash' => __('No experiences found in trash', 'develop-srilanka'),
    );
    
    $args = array(
        'labels' => $labels,
        'public' => true,
        'has_archive' => true,
        'show_in_rest' => true,
        'menu_icon' => 'dashicons-heart',
        'supports' => array('title', 'editor', 'thumbnail', 'excerpt', 'comments'),
        'rewrite' => array('slug' => 'experiences'),
    );
    
    register_post_type('experience', $args);
}
add_action('init', 'register_experience_post_type');

/**
 * Add custom meta boxes for experiences
 */
function experience_meta_boxes() {
    add_meta_box(
        'experience_details',
        __('Experience Details', 'develop-srilanka'),
        'experience_meta_box_callback',
        'experience',
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'experience_meta_boxes');

/**
 * Meta box callback function
 */
function experience_meta_box_callback($post) {
    wp_nonce_field('experience_meta_box', 'experience_meta_box_nonce');
    
    $contributor_name = get_post_meta($post->ID, '_contributor_name', true);
    $contributor_email = get_post_meta($post->ID, '_contributor_email', true);
    $contributor_phone = get_post_meta($post->ID, '_contributor_phone', true);
    $contributor_company = get_post_meta($post->ID, '_contributor_company', true);
    $contributor_country = get_post_meta($post->ID, '_contributor_country', true);
    $approved = get_post_meta($post->ID, '_experience_approved', true);
    ?>
    <p>
        <label for="contributor_name"><?php _e('Contributor Name:', 'develop-srilanka'); ?></label><br>
        <input type="text" id="contributor_name" name="contributor_name" value="<?php echo esc_attr($contributor_name); ?>" style="width: 100%;">
    </p>
    <p>
        <label for="contributor_email"><?php _e('Contributor Email:', 'develop-srilanka'); ?></label><br>
        <input type="email" id="contributor_email" name="contributor_email" value="<?php echo esc_attr($contributor_email); ?>" style="width: 100%;">
    </p>
    <p>
        <label for="contributor_phone"><?php _e('Contributor Phone:', 'develop-srilanka'); ?></label><br>
        <input type="tel" id="contributor_phone" name="contributor_phone" value="<?php echo esc_attr($contributor_phone); ?>" style="width: 100%;">
    </p>
    <p>
        <label for="contributor_company"><?php _e('Guide/Driver/Company:', 'develop-srilanka'); ?></label><br>
        <input type="text" id="contributor_company" name="contributor_company" value="<?php echo esc_attr($contributor_company); ?>" style="width: 100%;">
    </p>
    <p>
        <label for="contributor_country"><?php _e('Contributor Country:', 'develop-srilanka'); ?></label><br>
        <input type="text" id="contributor_country" name="contributor_country" value="<?php echo esc_attr($contributor_country); ?>" style="width: 100%;">
    </p>
    <p>
        <label>
            <input type="checkbox" name="experience_approved" value="1" <?php checked($approved, '1'); ?>>
            <?php _e('Approved for Display', 'develop-srilanka'); ?>
        </label>
    </p>
    <?php
}

/**
 * Save meta box data
 */
function save_experience_meta_box($post_id) {
    if (!isset($_POST['experience_meta_box_nonce']) || !wp_verify_nonce($_POST['experience_meta_box_nonce'], 'experience_meta_box')) {
        return;
    }
    
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    
    if (isset($_POST['contributor_name'])) {
        update_post_meta($post_id, '_contributor_name', sanitize_text_field($_POST['contributor_name']));
    }
    
    if (isset($_POST['contributor_email'])) {
        update_post_meta($post_id, '_contributor_email', sanitize_email($_POST['contributor_email']));
    }
    
    if (isset($_POST['contributor_phone'])) {
        update_post_meta($post_id, '_contributor_phone', sanitize_text_field($_POST['contributor_phone']));
    }
    
    if (isset($_POST['contributor_company'])) {
        update_post_meta($post_id, '_contributor_company', sanitize_text_field($_POST['contributor_company']));
    }
    
    if (isset($_POST['contributor_country'])) {
        update_post_meta($post_id, '_contributor_country', sanitize_text_field($_POST['contributor_country']));
    }
    
    $approved = isset($_POST['experience_approved']) ? '1' : '0';
    update_post_meta($post_id, '_experience_approved', $approved);
}
add_action('save_post_experience', 'save_experience_meta_box');

/**
 * Handle experience submission form
 */
function handle_experience_submission() {
    check_ajax_referer('srilanka_nonce', 'nonce');
    
    // Validate and sanitize input
    $name = isset($_POST['name']) ? sanitize_text_field($_POST['name']) : 'Anonymous';
    $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
    $phone = isset($_POST['phone']) ? sanitize_text_field($_POST['phone']) : '';
    $company = isset($_POST['company']) ? sanitize_text_field($_POST['company']) : '';
    $country = isset($_POST['country']) ? sanitize_text_field($_POST['country']) : '';
    $title = isset($_POST['title']) ? sanitize_text_field($_POST['title']) : '';
    $story = isset($_POST['story']) ? wp_kses_post($_POST['story']) : '';
    
    // Validate required fields
    if (empty($title) || empty($story)) {
        wp_send_json_error(array('message' => 'Title and story are required.'));
        return;
    }
    
    // Create the post
    $post_data = array(
        'post_title' => $title,
        'post_content' => $story,
        'post_status' => 'pending',
        'post_type' => 'experience',
    );
    
    $post_id = wp_insert_post($post_data);
    
    if (is_wp_error($post_id)) {
        wp_send_json_error(array('message' => 'Error creating experience. Please try again.'));
        return;
    }
    
    // Save meta data
    update_post_meta($post_id, '_contributor_name', $name);
    update_post_meta($post_id, '_contributor_email', $email);
    update_post_meta($post_id, '_contributor_phone', $phone);
    update_post_meta($post_id, '_contributor_company', $company);
    update_post_meta($post_id, '_contributor_country', $country);
    update_post_meta($post_id, '_experience_approved', '0');
    
    // Handle image upload
    if (!empty($_FILES['images']) && is_array($_FILES['images']['name'])) {
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        
        $uploaded_images = array();
        
        // Limit to maximum 4 images
        $max_images = 4;
        $total_files = count($_FILES['images']['name']);
        $files_to_process = min($total_files, $max_images);
        
        // WordPress upload overrides
        $upload_overrides = array('test_form' => false);
        
        for ($i = 0; $i < $files_to_process; $i++) {
            if (!empty($_FILES['images']['name'][$i]) && $_FILES['images']['error'][$i] === 0) {
                
                // Create individual file array
                $file = array(
                    'name'     => $_FILES['images']['name'][$i],
                    'type'     => $_FILES['images']['type'][$i],
                    'tmp_name' => $_FILES['images']['tmp_name'][$i],
                    'error'    => $_FILES['images']['error'][$i],
                    'size'     => $_FILES['images']['size'][$i]
                );
                
                // Upload the file
                $uploaded_file = wp_handle_upload($file, $upload_overrides);
                
                if (!isset($uploaded_file['error'])) {
                    // File uploaded successfully, create attachment
                    $attachment = array(
                        'post_mime_type' => $uploaded_file['type'],
                        'post_title'     => sanitize_file_name(pathinfo($file['name'], PATHINFO_FILENAME)),
                        'post_content'   => '',
                        'post_status'    => 'inherit'
                    );
                    
                    // Insert the attachment
                    $attachment_id = wp_insert_attachment($attachment, $uploaded_file['file'], $post_id);
                    
                    if (!is_wp_error($attachment_id)) {
                        // Generate attachment metadata
                        $attachment_data = wp_generate_attachment_metadata($attachment_id, $uploaded_file['file']);
                        wp_update_attachment_metadata($attachment_id, $attachment_data);
                        
                        $uploaded_images[] = $attachment_id;
                        
                        // Set first image as featured image
                        if (count($uploaded_images) === 1) {
                            set_post_thumbnail($post_id, $attachment_id);
                        }
                    }
                }
            }
        }
        
        if (!empty($uploaded_images)) {
            update_post_meta($post_id, '_experience_images', $uploaded_images);
        }
    }
    
    // Send notification email to admin
    $admin_email = get_option('admin_email');
    $subject = 'New Experience Submission: ' . $title;
    $message = "A new experience has been submitted:\n\n";
    $message .= "Title: " . $title . "\n";
    $message .= "Contributor: " . $name . " (" . $country . ")\n";
    $message .= "Email: " . $email . "\n\n";
    $message .= "Please review and approve at: " . admin_url('post.php?post=' . $post_id . '&action=edit');
    
    wp_mail($admin_email, $subject, $message);
    
    wp_send_json_success(array('message' => 'Thank you! Your experience has been submitted and is pending approval.'));
}
add_action('wp_ajax_submit_experience', 'handle_experience_submission');
add_action('wp_ajax_nopriv_submit_experience', 'handle_experience_submission');

/**
 * Modify experience query to only show approved experiences
 */
function filter_experience_query($query) {
    if (!is_admin() && $query->is_main_query() && is_post_type_archive('experience')) {
        $meta_query = array(
            array(
                'key' => '_experience_approved',
                'value' => '1',
                'compare' => '='
            )
        );
        $query->set('meta_query', $meta_query);
    }
}
add_action('pre_get_posts', 'filter_experience_query');

/**
 * Add admin column for approval status
 */
function experience_admin_columns($columns) {
    $columns['approved'] = __('Approved', 'develop-srilanka');
    $columns['contributor'] = __('Contributor', 'develop-srilanka');
    return $columns;
}
add_filter('manage_experience_posts_columns', 'experience_admin_columns');

/**
 * Display admin column content
 */
function experience_admin_column_content($column, $post_id) {
    if ($column === 'approved') {
        $approved = get_post_meta($post_id, '_experience_approved', true);
        echo $approved == '1' ? '✓ Yes' : '✗ No';
    }
    
    if ($column === 'contributor') {
        $name = get_post_meta($post_id, '_contributor_name', true);
        $country = get_post_meta($post_id, '_contributor_country', true);
        echo esc_html($name) . ' (' . esc_html($country) . ')';
    }
}
add_action('manage_experience_posts_custom_column', 'experience_admin_column_content', 10, 2);

/**
 * Custom excerpt length
 */
function custom_excerpt_length($length) {
    return 30;
}
add_filter('excerpt_length', 'custom_excerpt_length');

/**
 * Custom excerpt more
 */
function custom_excerpt_more($more) {
    return '...';
}
add_filter('excerpt_more', 'custom_excerpt_more');

/**
 * Automatically generate a sitemap page for quick access from the admin.
 */
function develop_srilanka_create_sitemap_page() {
    $slug = 'sitemap';
    if (get_page_by_path($slug)) {
        return;
    }

    $page_data = array(
        'post_title'   => 'Sitemap',
        'post_name'    => $slug,
        'post_content' => 'This page lists the site structure for quick reference. Add or remove content via the dashboard if needed.',
        'post_status'  => 'publish',
        'post_type'    => 'page',
    );

    $page_id = wp_insert_post($page_data);
    if (!is_wp_error($page_id)) {
        update_post_meta($page_id, '_wp_page_template', 'page-sitemap.php');
    }
}
add_action('after_switch_theme', 'develop_srilanka_create_sitemap_page');

/**
 * Provide a custom robots.txt output that links to the sitemap.
 */
function develop_srilanka_custom_robots_txt($output, $public) {
    $lines = array(
        'User-agent: *',
        'Disallow: /wp-admin/',
        'Allow: /wp-admin/admin-ajax.php',
        'Sitemap: ' . home_url('/wp-sitemap.xml'),
    );

    return implode("\n", $lines) . "\n";
}
add_filter('robots_txt', 'develop_srilanka_custom_robots_txt', 10, 2);

/**
 * Ensure a Terms & Conditions page exists so it can be linked from the footer and managed in the admin.
 */
function develop_srilanka_create_terms_page() {
    $slug = 'terms-and-conditions';
    if (get_page_by_path($slug)) {
        return;
    }

    $page_data = array(
        'post_title'   => 'Terms & Conditions',
        'post_name'    => $slug,
        'post_status'  => 'publish',
        'post_type'    => 'page',
        'post_content' => 'Please edit this page from the WordPress dashboard to add your site-specific Terms & Conditions.',
        'post_author'  => get_current_user_id() ? get_current_user_id() : 1,
    );

    wp_insert_post($page_data);
}
add_action('after_switch_theme', 'develop_srilanka_create_terms_page');

/**
 * Retrieve the Terms & Conditions page link for use in the footer.
 */
function develop_srilanka_get_terms_page_link() {
    $page = get_page_by_path('terms-and-conditions');
    if ($page) {
        return get_permalink($page);
    }

    return home_url('/terms-and-conditions/');
}

/**
 * Output the Google tag script inside the document head.
 */
function develop_srilanka_output_gtag() {
    ?>
    <!-- Google tag (gtag.js) -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-B425E5Z8PQ"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-B425E5Z8PQ');
    </script>
    <?php
}
add_action('wp_head', 'develop_srilanka_output_gtag');