<?php

/**
 * Register Custom Post Type: Project
 */
function skill_register_project_post_type() {
    $labels = array(
        'name'                  => _x('پروژه ها', 'Post Type General Name', 'skill'),
        'singular_name'         => _x('پروژه', 'Post Type Singular Name', 'skill'),
        'menu_name'             => __('پروژه های من', 'skill'),
        'all_items'             => __('همه پروژه ها', 'skill'),
        'view_item'             => __('مشاهده پروژه', 'skill'),
        'add_new_item'          => __('افزودن پروژه جدید', 'skill'),
        'add_new'               => __('افزودن پروژه', 'skill'),
        'edit_item'             => __('ویرایش پروژه', 'skill'),
        'update_item'           => __('بروزرسانی پروژه', 'skill'),
        'search_items'          => __('جستجوی پروژه', 'skill'),
        'not_found'             => __('پروژه ای یافت نشد', 'skill'),
        'not_found_in_trash'    => __('پروژه ای در زباله دان یافت نشد', 'skill'),
    );

    $args = array(
        'label'                 => __('پروژه', 'skill'),
        'description'           => __('پروژه های انجام شده', 'skill'),
        'labels'                => $labels,
        'supports'              => array('title', 'editor', 'thumbnail', 'excerpt', 'comments'),
        'taxonomies'            => array('project_category'),
        'hierarchical'          => false,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'show_in_nav_menus'     => true,
        'show_in_admin_bar'     => true,
        'menu_position'         => 30,
        'menu_icon'             => 'dashicons-portfolio',
        'can_export'           => true,
        'has_archive'          => true,
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'capability_type'      => 'post',
        'show_in_rest'          => true,
    );

    register_post_type('project', $args);
}
add_action('init', 'skill_register_project_post_type', 0);

/**
 * Register Custom Taxonomy: Project Category
 */
function skill_register_project_taxonomy() {
    $labels = array(
        'name'                       => _x('دسته بندی پروژه ها', 'Taxonomy General Name', 'skill'),
        'singular_name'              => _x('دسته بندی پروژه', 'Taxonomy Singular Name', 'skill'),
        'menu_name'                  => __('دسته بندی پروژه', 'skill'),
        'all_items'                  => __('همه دسته بندی ها', 'skill'),
        'parent_item'                => __('دسته بندی مادر', 'skill'),
        'parent_item_colon'          => __('دسته بندی مادر:', 'skill'),
        'new_item_name'              => __('نام دسته بندی جدید', 'skill'),
        'add_new_item'               => __('افزودن دسته بندی جدید', 'skill'),
        'edit_item'                  => __('ویرایش دسته بندی', 'skill'),
        'update_item'                => __('بروزرسانی دسته بندی', 'skill'),
        'search_items'               => __('جستجوی دسته بندی', 'skill'),
        'add_or_remove_items'       => __('افزودن یا حذف دسته بندی', 'skill'),
        'choose_from_most_used'      => __('انتخاب از پرکاربردترین ها', 'skill'),
        'not_found'                  => __('دسته بندی یافت نشد', 'skill'),
    );

    $args = array(
        'labels'                     => $labels,
        'hierarchical'               => true,
        'public'                    => true,
        'show_ui'                    => true,
        'show_admin_column'          => true,
        'show_in_nav_menus'          => true,
        'show_tagcloud'             => true,
        'show_in_rest'               => true,
    );

    register_taxonomy('project_category', array('project'), $args);
}
add_action('init', 'skill_register_project_taxonomy', 0);

/**
 * Add Project Meta Boxes
 */
function skill_add_project_meta_boxes() {
    // Main project details
    add_meta_box(
        'project_details',
        __('جزئیات پروژه', 'skill'),
        'skill_project_meta_box_callback',
        'project',
        'normal',
        'high'
    );

    // Project gallery
    add_meta_box(
        'project_gallery',
        __('گالری تصاویر پروژه', 'skill'),
        'skill_project_gallery_callback',
        'project',
        'normal',
        'high'
    );

    // Project timeline
    add_meta_box(
        'project_timeline',
        __('زمانبندی پروژه', 'skill'),
        'skill_project_timeline_callback',
        'project',
        'normal',
        'default'
    );

    // Team members
    add_meta_box(
        'project_team',
        __('اعضای تیم', 'skill'),
        'skill_project_team_callback',
        'project',
        'normal',
        'default'
    );

    // Project links and resources
    add_meta_box(
        'project_links',
        __('لینک ها و منابع', 'skill'),
        'skill_project_links_callback',
        'project',
        'side',
        'default'
    );
}
add_action('add_meta_boxes', 'skill_add_project_meta_boxes');

/**
 * Remove legacy core Custom Fields metabox for project
 */
function skill_remove_project_custom_fields_metabox() {
    remove_meta_box('postcustom', 'project', 'normal');
}
add_action('add_meta_boxes', 'skill_remove_project_custom_fields_metabox', 99);

/**
 * Project Meta Box Callback - Main Details
 */
function skill_project_meta_box_callback($post) {
    wp_nonce_field('skill_project_meta_box', 'skill_project_meta_box_nonce');

    $client_name = get_post_meta($post->ID, '_client_name', true);
    $start_number = get_post_meta($post->ID, '_start_number', true);
    $end_number = get_post_meta($post->ID, '_end_number', true);
    $project_address = get_post_meta($post->ID, '_project_address', true);
    $technologies = get_post_meta($post->ID, '_technologies', true);
    $project_status = get_post_meta($post->ID, '_project_status', true);
    $project_budget = get_post_meta($post->ID, '_project_budget', true);
    $project_duration = get_post_meta($post->ID, '_project_duration', true);
    $project_scale = get_post_meta($post->ID, '_project_scale', true);
    $project_description_short = get_post_meta($post->ID, '_project_description_short', true);

    ?>
    <div class="project-meta-fields">
        <div class="meta-field">
            <label for="client_name"><?php _e('نام مشتری:', 'skill'); ?></label>
            <input type="text" id="client_name" name="client_name" value="<?php echo esc_attr($client_name); ?>" class="widefat">
        </div>

        <div class="meta-field">
            <label for="project_status"><?php _e('وضعیت پروژه:', 'skill'); ?></label>
            <select id="project_status" name="project_status" class="widefat">
                <option value=""><?php _e('انتخاب کنید', 'skill'); ?></option>
                <option value="completed" <?php selected($project_status, 'completed'); ?>><?php _e('تکمیل شده', 'skill'); ?></option>
                <option value="in_progress" <?php selected($project_status, 'in_progress'); ?>><?php _e('در حال انجام', 'skill'); ?></option>
                <option value="on_hold" <?php selected($project_status, 'on_hold'); ?>><?php _e('متوقف شده', 'skill'); ?></option>
                <option value="cancelled" <?php selected($project_status, 'cancelled'); ?>><?php _e('لغو شده', 'skill'); ?></option>
            </select>
        </div>

        <div class="meta-field">
            <label for="start_number"><?php _e('تاریخ شروع (مثال: 1402):', 'skill'); ?></label>
            <input type="number" id="start_number" name="start_number" value="<?php echo esc_attr($start_number); ?>" class="widefat">
        </div>

        <div class="meta-field">
            <label for="end_number"><?php _e('تاریخ پایان (مثال: 1403):', 'skill'); ?></label>
            <input type="number" id="end_number" name="end_number" value="<?php echo esc_attr($end_number); ?>" class="widefat">
        </div>

        <div class="meta-field">
            <label for="project_duration"><?php _e('مدت زمان پروژه (ماه):', 'skill'); ?></label>
            <input type="number" id="project_duration" name="project_duration" value="<?php echo esc_attr($project_duration); ?>" class="widefat">
        </div>

        <div class="meta-field">
            <label for="project_budget"><?php _e('بودجه پروژه (تومان):', 'skill'); ?></label>
            <input type="text" id="project_budget" name="project_budget" value="<?php echo esc_attr($project_budget); ?>" class="widefat">
        </div>

        <div class="meta-field">
            <label for="project_scale"><?php _e('مقیاس پروژه:', 'skill'); ?></label>
            <select id="project_scale" name="project_scale" class="widefat">
                <option value=""><?php _e('انتخاب کنید', 'skill'); ?></option>
                <option value="small" <?php selected($project_scale, 'small'); ?>><?php _e('کوچک', 'skill'); ?></option>
                <option value="medium" <?php selected($project_scale, 'medium'); ?>><?php _e('متوسط', 'skill'); ?></option>
                <option value="large" <?php selected($project_scale, 'large'); ?>><?php _e('بزرگ', 'skill'); ?></option>
                <option value="enterprise" <?php selected($project_scale, 'enterprise'); ?>><?php _e('سازمانی', 'skill'); ?></option>
            </select>
        </div>

        <div class="meta-field">
            <label for="project_address"><?php _e('آدرس پروژه:', 'skill'); ?></label>
            <input type="text" id="project_address" name="project_address" value="<?php echo esc_attr($project_address); ?>" class="widefat">
        </div>

        <div class="meta-field">
            <label for="technologies"><?php _e('تکنولوژی های استفاده شده (با کاما جدا کنید):', 'skill'); ?></label>
            <input type="text" id="technologies" name="technologies" value="<?php echo esc_attr($technologies); ?>" class="widefat">
            <p class="description"><?php _e('مثال: PHP, WordPress, JavaScript, CSS', 'skill'); ?></p>
        </div>

        <div class="meta-field">
            <label for="project_description_short"><?php _e('توضیحات کوتاه پروژه:', 'skill'); ?></label>
            <textarea id="project_description_short" name="project_description_short" class="widefat" rows="3"><?php echo esc_textarea($project_description_short); ?></textarea>
        </div>
    </div>
    <?php
}

/**
 * Project Gallery Meta Box Callback
 */
function skill_project_gallery_callback($post) {
    wp_nonce_field('skill_project_gallery', 'skill_project_gallery_nonce');
    
    $gallery_images = get_post_meta($post->ID, '_project_gallery', true);
    if (!is_array($gallery_images)) {
        $gallery_images = array();
    }
    ?>
    <div class="project-gallery-container">
        <div class="gallery-images" id="gallery-images">
            <?php foreach ($gallery_images as $image_id): ?>
                <div class="gallery-image-item">
                    <?php echo wp_get_attachment_image($image_id, 'thumbnail'); ?>
                    <input type="hidden" name="project_gallery[]" value="<?php echo esc_attr($image_id); ?>">
                    <button type="button" class="remove-image"><?php _e('حذف', 'skill'); ?></button>
                </div>
            <?php endforeach; ?>
        </div>
        <button type="button" id="add-gallery-image" class="button"><?php _e('افزودن تصویر', 'skill'); ?></button>
    </div>
    <script>
    jQuery(document).ready(function($) {
        $('#add-gallery-image').click(function(e) {
            e.preventDefault();
            var frame = wp.media({
                title: '<?php _e('انتخاب تصاویر گالری', 'skill'); ?>',
                multiple: true,
                library: {
                    type: 'image'
                }
            });

            frame.on('select', function() {
                var attachments = frame.state().get('selection').toJSON();
                attachments.forEach(function(attachment) {
                    var html = '<div class="gallery-image-item">' +
                        '<img src="' + attachment.sizes.thumbnail.url + '" alt="">' +
                        '<input type="hidden" name="project_gallery[]" value="' + attachment.id + '">' +
                        '<button type="button" class="remove-image"><?php _e('حذف', 'skill'); ?></button>' +
                        '</div>';
                    $('#gallery-images').append(html);
                });
            });

            frame.open();
        });

        $(document).on('click', '.remove-image', function() {
            $(this).parent().remove();
        });
    });
    </script>
    <style>
    .gallery-image-item {
        display: inline-block;
        margin: 5px;
        position: relative;
    }
    .gallery-image-item img {
        max-width: 150px;
        height: auto;
    }
    .remove-image {
        position: absolute;
        top: 5px;
        right: 5px;
        background: red;
        color: white;
        border: none;
        padding: 2px 5px;
        cursor: pointer;
    }
    </style>
    <?php
}

/**
 * Project Timeline Meta Box Callback
 */
function skill_project_timeline_callback($post) {
    wp_nonce_field('skill_project_timeline', 'skill_project_timeline_nonce');
    
    $timeline_events = get_post_meta($post->ID, '_project_timeline', true);
    if (!is_array($timeline_events)) {
        $timeline_events = array();
    }
    ?>
    <div class="project-timeline-container">
        <div id="timeline-events">
            <?php foreach ($timeline_events as $index => $event): ?>
                <div class="timeline-event">
                    <h4><?php _e('رویداد', 'skill'); ?> #<?php echo $index + 1; ?></h4>
                    <p>
                        <label><?php _e('عنوان:', 'skill'); ?></label>
                        <input type="text" name="timeline_title[]" value="<?php echo esc_attr($event['title']); ?>" class="widefat">
                    </p>
                    <p>
                        <label><?php _e('تاریخ (میلادی) وارد کنید به (جلالی) نمایش میدهد:', 'skill'); ?></label>
                        <input type="date" name="timeline_date[]" value="<?php echo esc_attr($event['date']); ?>" class="widefat">
                        <small class="description"><?php _e('تاریخ میلادی وارد کنید، در نمایش به جلالی تبدیل می‌شود', 'skill'); ?></small>
                    </p>
                    <p>
                        <label><?php _e('توضیحات:', 'skill'); ?></label>
                        <textarea name="timeline_description[]" class="widefat" rows="3"><?php echo esc_textarea($event['description']); ?></textarea>
                    </p>
                    <button type="button" class="remove-timeline-event button"><?php _e('حذف رویداد', 'skill'); ?></button>
                </div>
            <?php endforeach; ?>
        </div>
        <button type="button" id="add-timeline-event" class="button"><?php _e('افزودن رویداد', 'skill'); ?></button>
    </div>
    <script>
    jQuery(document).ready(function($) {
        var eventCounter = <?php echo count($timeline_events); ?>;
        
        $('#add-timeline-event').click(function() {
            eventCounter++;
            var html = '<div class="timeline-event">' +
                '<h4><?php _e('رویداد', 'skill'); ?> #' + eventCounter + '</h4>' +
                '<p><label><?php _e('عنوان:', 'skill'); ?></label>' +
                '<input type="text" name="timeline_title[]" class="widefat"></p>' +
                '<p><label><?php _e('تاریخ (میلادی):', 'skill'); ?></label>' +
                '<input type="date" name="timeline_date[]" class="widefat"></p>' +
                '<small class="description"><?php _e('تاریخ میلادی وارد کنید، در نمایش به جلالی تبدیل می‌شود', 'skill'); ?></small>' +
                '<p><label><?php _e('توضیحات:', 'skill'); ?></label>' +
                '<textarea name="timeline_description[]" class="widefat" rows="3"></textarea></p>' +
                '<button type="button" class="remove-timeline-event button"><?php _e('حذف رویداد', 'skill'); ?></button>' +
                '</div>';
            $('#timeline-events').append(html);
        });

        $(document).on('click', '.remove-timeline-event', function() {
            $(this).parent().remove();
        });
    });
    </script>
    <style>
    .timeline-event {
        border: 1px solid #ddd;
        padding: 15px;
        margin: 10px 0;
        background: #f9f9f9;
    }
    </style>
    <?php
}

/**
 * Project Team Meta Box Callback
 */
function skill_project_team_callback($post) {
    wp_nonce_field('skill_project_team', 'skill_project_team_nonce');
    
    $team_members = get_post_meta($post->ID, '_project_team', true);
    if (!is_array($team_members)) {
        $team_members = array();
    }
    ?>
    <div class="project-team-container">
        <div id="team-members">
            <?php foreach ($team_members as $index => $member): ?>
                <div class="team-member">
                    <h4><?php _e('عضو تیم', 'skill'); ?> #<?php echo $index + 1; ?></h4>
                    <p>
                        <label><?php _e('نام:', 'skill'); ?></label>
                        <input type="text" name="team_name[]" value="<?php echo esc_attr($member['name']); ?>" class="widefat">
                    </p>
                    <p>
                        <label><?php _e('نقش:', 'skill'); ?></label>
                        <input type="text" name="team_role[]" value="<?php echo esc_attr($member['role']); ?>" class="widefat">
                    </p>
                    <p>
                        <label><?php _e('ایمیل:', 'skill'); ?></label>
                        <input type="email" name="team_email[]" value="<?php echo esc_attr($member['email']); ?>" class="widefat">
                    </p>
                    <p>
                        <label><?php _e('لینکدین:', 'skill'); ?></label>
                        <input type="url" name="team_linkedin[]" value="<?php echo esc_attr($member['linkedin']); ?>" class="widefat">
                    </p>
                     <p>
                         <label><?php _e('تلگرام:', 'skill'); ?></label>
                         <input type="text" name="team_telegram[]" value="<?php echo isset($member['telegram']) ? esc_attr($member['telegram']) : ''; ?>" class="widefat" placeholder="<?php echo esc_attr__('لینک یا نام کاربری (مثال: https://t.me/username یا username)', 'skill'); ?>">
                     </p>
                     <p>
                         <label><?php _e('اینستاگرام:', 'skill'); ?></label>
                         <input type="text" name="team_instagram[]" value="<?php echo isset($member['instagram']) ? esc_attr($member['instagram']) : ''; ?>" class="widefat" placeholder="<?php echo esc_attr__('لینک یا نام کاربری (مثال: https://instagram.com/username یا username)', 'skill'); ?>">
                     </p>
                    <button type="button" class="remove-team-member button"><?php _e('حذف عضو', 'skill'); ?></button>
                </div>
            <?php endforeach; ?>
        </div>
        <button type="button" id="add-team-member" class="button"><?php _e('افزودن عضو تیم', 'skill'); ?></button>
    </div>
    <script>
    jQuery(document).ready(function($) {
        var memberCounter = <?php echo count($team_members); ?>;
        
        $('#add-team-member').click(function() {
            memberCounter++;
            var html = '<div class="team-member">' +
                '<h4><?php _e('عضو تیم', 'skill'); ?> #' + memberCounter + '</h4>' +
                '<p><label><?php _e('نام:', 'skill'); ?></label>' +
                '<input type="text" name="team_name[]" class="widefat"></p>' +
                '<p><label><?php _e('نقش:', 'skill'); ?></label>' +
                '<input type="text" name="team_role[]" class="widefat"></p>' +
                '<p><label><?php _e('ایمیل:', 'skill'); ?></label>' +
                '<input type="email" name="team_email[]" class="widefat"></p>' +
                '<p><label><?php _e('لینکدین:', 'skill'); ?></label>' +
                '<input type="url" name="team_linkedin[]" class="widefat"></p>' +
                '<p><label><?php _e('تلگرام:', 'skill'); ?></label>' +
                '<input type="text" name="team_telegram[]" class="widefat" placeholder="<?php echo esc_attr__('لینک یا نام کاربری (مثال: https://t.me/username یا username)', 'skill'); ?>"></p>' +
                '<p><label><?php _e('اینستاگرام:', 'skill'); ?></label>' +
                '<input type="text" name="team_instagram[]" class="widefat" placeholder="<?php echo esc_attr__('لینک یا نام کاربری (مثال: https://instagram.com/username یا username)', 'skill'); ?>"></p>' +
                '<button type="button" class="remove-team-member button"><?php _e('حذف عضو', 'skill'); ?></button>' +
                '</div>';
            $('#team-members').append(html);
        });

        $(document).on('click', '.remove-team-member', function() {
            $(this).parent().remove();
        });

        // No image select handlers in original version
    });
    </script>
    <style>
    .team-member {
        border: 1px solid #ddd;
        padding: 15px;
        margin: 10px 0;
        background: #f9f9f9;
    }
    
    /* Original version had no image UI styles */
    </style>
    <?php
}

/**
 * Project Links Meta Box Callback
 */
function skill_project_links_callback($post) {
    wp_nonce_field('skill_project_links', 'skill_project_links_nonce');
    
    $live_url = get_post_meta($post->ID, '_project_live_url', true);
    $github_url = get_post_meta($post->ID, '_project_github_url', true);
    $demo_url = get_post_meta($post->ID, '_project_demo_url', true);
    $documentation_url = get_post_meta($post->ID, '_project_documentation_url', true);
    ?>
    <div class="project-links-container">
        <p>
            <label for="project_live_url"><?php _e('آدرس زنده پروژه:', 'skill'); ?></label>
            <input type="url" id="project_live_url" name="project_live_url" value="<?php echo esc_attr($live_url); ?>" class="widefat">
        </p>
        
        <p>
            <label for="project_github_url"><?php _e('آدرس GitHub:', 'skill'); ?></label>
            <input type="url" id="project_github_url" name="project_github_url" value="<?php echo esc_attr($github_url); ?>" class="widefat">
        </p>
        
        <p>
            <label for="project_demo_url"><?php _e('آدرس دمو:', 'skill'); ?></label>
            <input type="url" id="project_demo_url" name="project_demo_url" value="<?php echo esc_attr($demo_url); ?>" class="widefat">
        </p>
        
        <p>
            <label for="project_documentation_url"><?php _e('آدرس مستندات:', 'skill'); ?></label>
            <input type="url" id="project_documentation_url" name="project_documentation_url" value="<?php echo esc_attr($documentation_url); ?>" class="widefat">
        </p>
    </div>
    <?php
}

/**
 * Save Project Meta Data
 */
function skill_save_project_meta($post_id) {
    // Migrate legacy meta keys saved via core Custom Fields (no underscore)
    // Only run on project post type
    $post_type = get_post_type($post_id);
    if ($post_type === 'project') {
        $legacy_map = array(
            'project_live_url' => '_project_live_url',
            'project_github_url' => '_project_github_url',
            'project_demo_url' => '_project_demo_url',
            'project_documentation_url' => '_project_documentation_url',
            'project_date' => '_start_number',
            'project_duration' => '_project_duration',
            'project_technologies' => '_technologies',
        );

        foreach ($legacy_map as $old_key => $new_key) {
            $old_value = get_post_meta($post_id, $old_key, true);
            if ($old_value !== '' && get_post_meta($post_id, $new_key, true) === '') {
                $sanitized = in_array($old_key, array('project_live_url','project_github_url','project_demo_url','project_documentation_url'), true)
                    ? esc_url_raw($old_value)
                    : sanitize_text_field($old_value);
                update_post_meta($post_id, $new_key, $sanitized);
            }
        }
    }
    // Save main project details
    if (isset($_POST['skill_project_meta_box_nonce']) && wp_verify_nonce($_POST['skill_project_meta_box_nonce'], 'skill_project_meta_box')) {
        $fields = array(
            'client_name',
            'start_number',
            'end_number',
            'project_address',
            'technologies',
            'project_status',
            'project_budget',
            'project_duration',
            'project_scale',
            'project_description_short'
        );

        foreach ($fields as $field) {
            if (isset($_POST[$field])) {
                update_post_meta($post_id, '_' . $field, sanitize_text_field($_POST[$field]));
            }
        }
    }

    // Save gallery images
    if (isset($_POST['skill_project_gallery_nonce']) && wp_verify_nonce($_POST['skill_project_gallery_nonce'], 'skill_project_gallery')) {
        if (isset($_POST['project_gallery']) && is_array($_POST['project_gallery'])) {
            $gallery_images = array_map('intval', $_POST['project_gallery']);
            $gallery_images = array_filter($gallery_images);
            update_post_meta($post_id, '_project_gallery', $gallery_images);
        }
    }

    // Save timeline events
    if (isset($_POST['skill_project_timeline_nonce']) && wp_verify_nonce($_POST['skill_project_timeline_nonce'], 'skill_project_timeline')) {
        $timeline_events = array();
        if (isset($_POST['timeline_title']) && is_array($_POST['timeline_title'])) {
            for ($i = 0; $i < count($_POST['timeline_title']); $i++) {
                if (!empty($_POST['timeline_title'][$i])) {
                    $timeline_events[] = array(
                        'title' => sanitize_text_field($_POST['timeline_title'][$i]),
                        'date' => sanitize_text_field($_POST['timeline_date'][$i]),
                        'description' => sanitize_textarea_field($_POST['timeline_description'][$i])
                    );
                }
            }
        }
        update_post_meta($post_id, '_project_timeline', $timeline_events);
    }

    // Save team members (original fields only)
    if (isset($_POST['skill_project_team_nonce']) && wp_verify_nonce($_POST['skill_project_team_nonce'], 'skill_project_team')) {
        $team_members = array();
        if (isset($_POST['team_name']) && is_array($_POST['team_name'])) {
            $total = count($_POST['team_name']);
            for ($i = 0; $i < $total; $i++) {
                $name = isset($_POST['team_name'][$i]) ? trim($_POST['team_name'][$i]) : '';
                if ($name === '') {
                    continue;
                }
                $team_members[] = array(
                    'name' => sanitize_text_field($name),
                    'role' => isset($_POST['team_role'][$i]) ? sanitize_text_field($_POST['team_role'][$i]) : '',
                    'email' => isset($_POST['team_email'][$i]) ? sanitize_email($_POST['team_email'][$i]) : '',
                    'linkedin' => isset($_POST['team_linkedin'][$i]) ? esc_url_raw($_POST['team_linkedin'][$i]) : '',
                    'telegram' => isset($_POST['team_telegram'][$i]) ? sanitize_text_field($_POST['team_telegram'][$i]) : '',
                    'instagram' => isset($_POST['team_instagram'][$i]) ? sanitize_text_field($_POST['team_instagram'][$i]) : '',
                );
            }
        }
        update_post_meta($post_id, '_project_team', $team_members);
    }

    // Save project links
    if (isset($_POST['skill_project_links_nonce']) && wp_verify_nonce($_POST['skill_project_links_nonce'], 'skill_project_links')) {
        $link_fields = array(
            'project_live_url',
            'project_github_url',
            'project_demo_url',
            'project_documentation_url'
        );

        foreach ($link_fields as $field) {
            if (isset($_POST[$field])) {
                update_post_meta($post_id, '_' . $field, esc_url_raw($_POST[$field]));
            }
        }
    }
}
add_action('save_post', 'skill_save_project_meta');

/**
 * Add custom columns to project admin list
 */
function skill_add_project_admin_columns($columns) {
    $new_columns = array();
    foreach ($columns as $key => $value) {
        $new_columns[$key] = $value;
        if ($key === 'title') {
            $new_columns['client'] = __('مشتری', 'skill');
            $new_columns['status'] = __('وضعیت', 'skill');
            $new_columns['technologies'] = __('تکنولوژی ها', 'skill');
            $new_columns['timeline'] = __('زمانبندی', 'skill');
        }
    }
    return $new_columns;
}
add_filter('manage_project_posts_columns', 'skill_add_project_admin_columns');

/**
 * Display custom column content
 */
function skill_project_admin_column_content($column, $post_id) {
    switch ($column) {
        case 'client':
            $client = get_post_meta($post_id, '_client_name', true);
            echo esc_html($client);
            break;
        case 'status':
            $status = get_post_meta($post_id, '_project_status', true);
            $status_labels = array(
                'completed' => __('تکمیل شده', 'skill'),
                'in_progress' => __('در حال انجام', 'skill'),
                'on_hold' => __('متوقف شده', 'skill'),
                'cancelled' => __('لغو شده', 'skill')
            );
            echo isset($status_labels[$status]) ? $status_labels[$status] : $status;
            break;
        case 'technologies':
            $technologies = get_post_meta($post_id, '_technologies', true);
            echo esc_html($technologies);
            break;
        case 'timeline':
            $start = get_post_meta($post_id, '_start_number', true);
            $end = get_post_meta($post_id, '_end_number', true);
            if ($start && $end) {
                echo esc_html($start) . ' - ' . esc_html($end);
            }
            break;
    }
}
add_action('manage_project_posts_custom_column', 'skill_project_admin_column_content', 10, 2);

/**
 * Make custom columns sortable
 */
function skill_project_sortable_columns($columns) {
    $columns['client'] = 'client';
    $columns['status'] = 'status';
    return $columns;
}
add_filter('manage_edit-project_sortable_columns', 'skill_project_sortable_columns');

/**
 * Add Theme Customizer Options for Project Display
 */
function skill_project_customizer_options($wp_customize) {
    // Project Display Section
    $wp_customize->add_section('skill_project_display', array(
        'title' => __('تنظیمات نمایش پروژه', 'skill'),
        'priority' => 35,
    ));

    // Enhanced Project Info
    $wp_customize->add_setting('skill_project_show_enhanced_info', array(
        'default' => true,
        'sanitize_callback' => 'skill_sanitize_checkbox',
    ));

    $wp_customize->add_control('skill_project_show_enhanced_info', array(
        'label' => __('نمایش اطلاعات پیشرفته پروژه', 'skill'),
        'section' => 'skill_project_display',
        'type' => 'checkbox',
    ));

    // Project Gallery
    $wp_customize->add_setting('skill_project_show_gallery', array(
        'default' => true,
        'sanitize_callback' => 'skill_sanitize_checkbox',
    ));

    $wp_customize->add_control('skill_project_show_gallery', array(
        'label' => __('نمایش گالری تصاویر پروژه', 'skill'),
        'section' => 'skill_project_display',
        'type' => 'checkbox',
    ));

    // Project Timeline
    $wp_customize->add_setting('skill_project_show_timeline', array(
        'default' => true,
        'sanitize_callback' => 'skill_sanitize_checkbox',
    ));

    $wp_customize->add_control('skill_project_show_timeline', array(
        'label' => __('نمایش زمانبندی پروژه', 'skill'),
        'section' => 'skill_project_display',
        'type' => 'checkbox',
    ));

    // Project Team
    $wp_customize->add_setting('skill_project_show_team', array(
        'default' => true,
        'sanitize_callback' => 'skill_sanitize_checkbox',
    ));

    $wp_customize->add_control('skill_project_show_team', array(
        'label' => __('نمایش اعضای تیم', 'skill'),
        'section' => 'skill_project_display',
        'type' => 'checkbox',
    ));

    // Project Links
    $wp_customize->add_setting('skill_project_show_links', array(
        'default' => true,
        'sanitize_callback' => 'skill_sanitize_checkbox',
    ));

    $wp_customize->add_control('skill_project_show_links', array(
        'label' => __('نمایش لینک‌های پروژه', 'skill'),
        'section' => 'skill_project_display',
        'type' => 'checkbox',
    ));
}
add_action('customize_register', 'skill_project_customizer_options');

/**
 * Sanitize checkbox function
 */
function skill_sanitize_checkbox($checked) {
    return ((isset($checked) && true == $checked) ? true : false);
}

/**
 * FRONTEND DISPLAY FUNCTIONS
 * Functions to display project information in templates
 */

/**
 * Get project status with Persian label
 */
function skill_get_project_status_label($status) {
    $status_labels = array(
        'completed' => __('تکمیل شده', 'skill'),
        'in_progress' => __('در حال انجام', 'skill'),
        'on_hold' => __('متوقف شده', 'skill'),
        'cancelled' => __('لغو شده', 'skill')
    );
    return isset($status_labels[$status]) ? $status_labels[$status] : $status;
}

/**
 * Get project scale with Persian label
 */
function skill_get_project_scale_label($scale) {
    $scale_labels = array(
        'small' => __('کوچک', 'skill'),
        'medium' => __('متوسط', 'skill'),
        'large' => __('بزرگ', 'skill'),
        'enterprise' => __('سازمانی', 'skill')
    );
    return isset($scale_labels[$scale]) ? $scale_labels[$scale] : $scale;
}

/**
 * Display project basic information
 */
function skill_display_project_info($post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }
    
    $client_name = get_post_meta($post_id, '_client_name', true);
    $project_status = get_post_meta($post_id, '_project_status', true);
    $start_number = get_post_meta($post_id, '_start_number', true);
    $end_number = get_post_meta($post_id, '_end_number', true);
    $project_duration = get_post_meta($post_id, '_project_duration', true);
    $project_budget = get_post_meta($post_id, '_project_budget', true);
    $project_scale = get_post_meta($post_id, '_project_scale', true);
    $technologies = get_post_meta($post_id, '_technologies', true);
    $project_address = get_post_meta($post_id, '_project_address', true);
    
    if (!$client_name && !$project_status && !$start_number && !$end_number) {
        return false;
    }
    
    ?>
    <div class="project-info">
        <h3><?php _e('اطلاعات پروژه', 'skill'); ?></h3>
        <div class="project-info-grid">
            <?php if ($client_name): ?>
                <div class="info-item">
                    <span class="label"><?php _e('مشتری:', 'skill'); ?></span>
                    <span class="value"><?php echo esc_html($client_name); ?></span>
                </div>
            <?php endif; ?>
            
            <?php if ($project_status): ?>
                <div class="info-item">
                    <span class="label"><?php _e('وضعیت:', 'skill'); ?></span>
                    <span class="value status-<?php echo esc_attr($project_status); ?>">
                        <?php echo skill_get_project_status_label($project_status); ?>
                    </span>
                </div>
            <?php endif; ?>
            
            <?php if ($start_number && $end_number): ?>
                <div class="info-item">
                    <span class="label"><?php _e('دوره زمانی:', 'skill'); ?></span>
                    <span class="value"><?php echo esc_html($start_number); ?> - <?php echo esc_html($end_number); ?></span>
                </div>
            <?php endif; ?>
            
            <?php if ($project_duration): ?>
                <div class="info-item">
                    <span class="label"><?php _e('مدت زمان:', 'skill'); ?></span>
                    <span class="value"><?php echo esc_html($project_duration); ?> <?php _e('ماه', 'skill'); ?></span>
                </div>
            <?php endif; ?>
            
            <?php if ($project_budget): ?>
                <div class="info-item">
                    <span class="label"><?php _e('بودجه:', 'skill'); ?></span>
                    <span class="value"><?php echo esc_html($project_budget); ?> <?php _e('تومان', 'skill'); ?></span>
                </div>
            <?php endif; ?>
            
            <?php if ($project_scale): ?>
                <div class="info-item">
                    <span class="label"><?php _e('مقیاس:', 'skill'); ?></span>
                    <span class="value"><?php echo skill_get_project_scale_label($project_scale); ?></span>
                </div>
            <?php endif; ?>
            
            <?php if ($project_address): ?>
                <div class="info-item">
                    <span class="label"><?php _e('آدرس:', 'skill'); ?></span>
                    <span class="value"><?php echo esc_html($project_address); ?></span>
                </div>
            <?php endif; ?>
        </div>
        
        <?php if ($technologies): ?>
            <div class="technologies-section">
                <h4><?php _e('تکنولوژی های استفاده شده', 'skill'); ?></h4>
                <div class="technologies-list">
                    <?php 
                    $tech_array = array_map('trim', explode(',', $technologies));
                    foreach ($tech_array as $tech): ?>
                        <span class="tech-tag"><?php echo esc_html($tech); ?></span>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>
    </div>
    <?php
}

/**
 * Display project gallery
 */
function skill_display_project_gallery($post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }
    
    $gallery_images = get_post_meta($post_id, '_project_gallery', true);
    if (!is_array($gallery_images) || empty($gallery_images)) {
        return false;
    }
    
    ?>
    <div class="project-gallery">
        <h3><?php _e('گالری تصاویر پروژه', 'skill'); ?></h3>
        <div class="gallery-grid">
            <?php foreach ($gallery_images as $image_id): ?>
                <div class="gallery-item">
                    <a href="<?php echo wp_get_attachment_image_url($image_id, 'full'); ?>" class="gallery-link" data-lightbox="project-gallery">
                        <?php echo wp_get_attachment_image($image_id, 'medium'); ?>
                    </a>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php
}

/**
 * Display project timeline
 */
function skill_display_project_timeline($post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }
    
    $timeline_events = get_post_meta($post_id, '_project_timeline', true);
    if (!is_array($timeline_events) || empty($timeline_events)) {
        return false;
    }
    
    ?>
    <div class="project-timeline">
        <h3><?php _e('مراحل پروژه', 'skill'); ?></h3>
        <p class="timeline-description"><?php _e('مراحل مختلف انجام پروژه از شروع تا پایان', 'skill'); ?></p>
        <div class="timeline-container">
            <?php foreach ($timeline_events as $index => $event): ?>
                <div class="timeline-event">
                    <div class="timeline-date">
                        <?php 
                        // Convert Gregorian date to Jalali
                        $gregorian_date = $event['date'];
                        if (!empty($gregorian_date)) {
                            $date_parts = explode('-', $gregorian_date);
                                                         if (count($date_parts) === 3) {
                                 $jalali_date = skill_gregorian_to_jalali($date_parts[0], $date_parts[1], $date_parts[2]);
                                 echo esc_html($jalali_date[0] . '/' . $jalali_date[1] . '/' . $jalali_date[2]);
                             } else {
                                echo esc_html($gregorian_date);
                            }
                        }
                        ?>
                    </div>
                    <div class="timeline-content">
                        <h4><?php echo esc_html($event['title']); ?></h4>
                        <p><?php echo esc_html($event['description']); ?></p>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php
}

/**
 * Convert Gregorian date to Jalali (Persian) date
 * Using existing function from jdf.php
 */
function skill_gregorian_to_jalali($gy, $gm, $gd) {
    $g_d_m = array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334);
    $gy2 = ($gm > 2) ? ($gy + 1) : $gy;
    $days = 355666 + (365 * $gy) + ((int)(($gy2 + 3) / 4)) - ((int)(($gy2 + 99) / 100)) + ((int)(($gy2 + 399) / 400)) + $gd + $g_d_m[$gm - 1];
    $jy = -1595 + (33 * ((int)($days / 12053)));
    $days %= 12053;
    $jy += 4 * ((int)($days / 1461));
    $days %= 1461;
    if ($days > 365) {
        $jy += (int)(($days - 1) / 365);
        $days = ($days - 1) % 365;
    }
    if ($days < 186) {
        $jm = 1 + (int)($days / 31);
        $jd = 1 + ($days % 31);
    } else {
        $jm = 7 + (int)(($days - 186) / 30);
        $jd = 1 + (($days - 186) % 30);
    }
    return array($jy, $jm, $jd);
}

/**
 * Display project team members
 */
function skill_display_project_team($post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }
    
    $team_members = get_post_meta($post_id, '_project_team', true);
    if (!is_array($team_members) || empty($team_members)) {
        return false;
    }
    
    ?>
    <div class="project-team">
        <h3><?php _e('اعضای تیم', 'skill'); ?></h3>
        <div class="team-grid">
            <?php foreach ($team_members as $member): ?>
                <div class="team-member">
                    <div class="member-info">
                        <h4><?php echo esc_html($member['name']); ?></h4>
                        <p class="member-role"><?php echo esc_html($member['role']); ?></p>
                        
                        <div class="member-social-links">
                            <?php if ($member['email']): ?>
                                <a href="mailto:<?php echo esc_attr($member['email']); ?>" class="social-link email" title="ایمیل">
                                    <i class="fas fa-envelope"></i>
                                </a>
                            <?php endif; ?>
                            
                            <?php if ($member['linkedin']): ?>
                                <a href="<?php echo esc_url($member['linkedin']); ?>" target="_blank" class="social-link linkedin" title="لینکدین">
                                    <i class="fab fa-linkedin"></i>
                                </a>
                            <?php endif; ?>

                             <?php 
                             // Build Telegram URL if username provided
                             $telegram_value = isset($member['telegram']) ? trim($member['telegram']) : '';
                             if ($telegram_value) {
                                 $telegram_url = preg_match('/^https?:\/\//i', $telegram_value) ? $telegram_value : ('https://t.me/' . ltrim($telegram_value, '@'));
                             ?>
                                 <a href="<?php echo esc_url($telegram_url); ?>" target="_blank" class="social-link telegram" title="تلگرام">
                                     <i class="fab fa-telegram-plane"></i>
                                 </a>
                             <?php } ?>

                             <?php 
                             // Build Instagram URL if username provided
                             $instagram_value = isset($member['instagram']) ? trim($member['instagram']) : '';
                             if ($instagram_value) {
                                 $instagram_url = preg_match('/^https?:\/\//i', $instagram_value) ? $instagram_value : ('https://instagram.com/' . ltrim($instagram_value, '@'));
                             ?>
                                 <a href="<?php echo esc_url($instagram_url); ?>" target="_blank" class="social-link instagram" title="اینستاگرام">
                                     <i class="fab fa-instagram"></i>
                                 </a>
                             <?php } ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    
    <style>
    .project-team {
        margin: 2rem 0;
    }
    
    .team-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 1.5rem;
        margin-top: 1rem;
    }
    
    .team-member {
        background: #ffffff;
        border-radius: 10px;
        padding: 1.5rem;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        transition: transform 0.3s ease, box-shadow 0.3s ease;
    }
    
    .team-member:hover {
        transform: translateY(-5px);
        box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
    }
    
    .member-info h4 {
        margin: 0 0 0.5rem 0;
        color: #333;
        font-size: 1.2rem;
        font-weight: 600;
    }
    
    .member-role {
        margin: 0 0 1rem 0;
        color: #666;
        font-size: 0.9rem;
    }
    
    .member-social-links {
        display: flex;
        gap: 0.8rem;
        margin-top: 1rem;
    }
    
    .social-link {
        width: 35px;
        height: 35px;
        border-radius: 50%;
        background: #f8f9fa;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #666;
        text-decoration: none;
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
    }
    
    .social-link::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
        transition: left 0.5s ease;
    }
    
    .social-link:hover::before {
        left: 100%;
    }
    
    .social-link:hover {
        transform: translateY(-3px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.2);
    }
    
    .social-link.linkedin:hover {
        background: #0077b5;
        color: #ffffff;
    }
    
    .social-link.email:hover {
        background: #ea4335;
        color: #ffffff;
    }
    
    .social-link.telegram:hover {
        background: #0088cc;
        color: #ffffff;
    }
    
    .social-link.instagram:hover {
        background: #E4405F;
        color: #ffffff;
    }
    
    .social-link i {
        font-size: 1rem;
        z-index: 1;
        position: relative;
    }
    
    @media (max-width: 768px) {
        .team-grid {
            grid-template-columns: 1fr;
        }
        
        .team-member {
            padding: 1rem;
        }
    }
    </style>
    <?php
}

/**
 * Display project links
 */
function skill_display_project_links($post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }
    
    $live_url = get_post_meta($post_id, '_project_live_url', true);
    $github_url = get_post_meta($post_id, '_project_github_url', true);
    $demo_url = get_post_meta($post_id, '_project_demo_url', true);
    $documentation_url = get_post_meta($post_id, '_project_documentation_url', true);
    
    if (!$live_url && !$github_url && !$demo_url && !$documentation_url) {
        return false;
    }
    
    ?>
    <div class="project-links">
        <h3><?php _e('لینک ها و منابع', 'skill'); ?></h3>
        <div class="links-grid">
            <?php if ($live_url): ?>
                <a href="<?php echo esc_url($live_url); ?>" class="project-link live-link" target="_blank">
                    <i class="fas fa-external-link-alt"></i>
                    <?php _e('مشاهده پروژه زنده', 'skill'); ?>
                </a>
            <?php endif; ?>
            
            <?php if ($github_url): ?>
                <a href="<?php echo esc_url($github_url); ?>" class="project-link github-link" target="_blank">
                    <i class="fab fa-github"></i>
                    <?php _e('مشاهده کد در GitHub', 'skill'); ?>
                </a>
            <?php endif; ?>
            
            <?php if ($demo_url): ?>
                <a href="<?php echo esc_url($demo_url); ?>" class="project-link demo-link" target="_blank">
                    <i class="fas fa-play"></i>
                    <?php _e('مشاهده دمو', 'skill'); ?>
                </a>
            <?php endif; ?>
            
            <?php if ($documentation_url): ?>
                <a href="<?php echo esc_url($documentation_url); ?>" class="project-link docs-link" target="_blank">
                    <i class="fas fa-book"></i>
                    <?php _e('مشاهده مستندات', 'skill'); ?>
                </a>
            <?php endif; ?>
        </div>
    </div>
    <?php
}

/**
 * Display all project information (complete project display)
 */
function skill_display_full_project($post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }
    
    ?>
    <div class="project-full-display">
        <?php skill_display_project_info($post_id); ?>
        <?php skill_display_project_gallery($post_id); ?>
        <?php skill_display_project_timeline($post_id); ?>
        <?php skill_display_project_team($post_id); ?>
        <?php skill_display_project_links($post_id); ?>
    </div>
    <?php
}

/**
 * Get project meta data as array (for custom templates)
 */
function skill_get_project_meta($post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }
    
    return array(
        'client_name' => get_post_meta($post_id, '_client_name', true),
        'project_status' => get_post_meta($post_id, '_project_status', true),
        'start_number' => get_post_meta($post_id, '_start_number', true),
        'end_number' => get_post_meta($post_id, '_end_number', true),
        'project_duration' => get_post_meta($post_id, '_project_duration', true),
        'project_budget' => get_post_meta($post_id, '_project_budget', true),
        'project_scale' => get_post_meta($post_id, '_project_scale', true),
        'technologies' => get_post_meta($post_id, '_technologies', true),
        'project_address' => get_post_meta($post_id, '_project_address', true),
        'project_description_short' => get_post_meta($post_id, '_project_description_short', true),
        'gallery_images' => get_post_meta($post_id, '_project_gallery', true),
        'timeline_events' => get_post_meta($post_id, '_project_timeline', true),
        'team_members' => get_post_meta($post_id, '_project_team', true),
        'live_url' => get_post_meta($post_id, '_project_live_url', true),
        'github_url' => get_post_meta($post_id, '_project_github_url', true),
        'demo_url' => get_post_meta($post_id, '_project_demo_url', true),
        'documentation_url' => get_post_meta($post_id, '_project_documentation_url', true),
    );
}