<?php
/**
 * @package Divine_Agreement_System
 * @author Aditya Singh
 */

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

class Divine_Post_Types {
    
    
    public static function init() {
        add_action('init', array(__CLASS__, 'divine_register_post_types'));
        add_action('add_meta_boxes', array(__CLASS__, 'divine_add_meta_boxes'));
        add_action('save_post', array(__CLASS__, 'divine_save_agreement_meta'));
        add_filter('manage_divine_agreement_posts_columns', array(__CLASS__, 'divine_agreement_columns'));
        add_action('manage_divine_agreement_posts_custom_column', array(__CLASS__, 'divine_agreement_column_content'), 10, 2);
    }
    
    
    public static function divine_register_post_types() {
        
        register_post_type('divine_template', array(
            'labels' => array(
                'name' => __('Agreement Templates', 'divine-agreement-system'),
                'singular_name' => __('Agreement Template', 'divine-agreement-system'),
                'add_new' => __('Add New Template', 'divine-agreement-system'),
                'add_new_item' => __('Add New Agreement Template', 'divine-agreement-system'),
                'edit_item' => __('Edit Agreement Template', 'divine-agreement-system'),
                'new_item' => __('New Agreement Template', 'divine-agreement-system'),
                'view_item' => __('View Agreement Template', 'divine-agreement-system'),
                'search_items' => __('Search Templates', 'divine-agreement-system'),
                'not_found' => __('No templates found', 'divine-agreement-system'),
                'not_found_in_trash' => __('No templates found in trash', 'divine-agreement-system')
            ),
            'public' => false,
            'show_ui' => true,
            'show_in_menu' => true,
            'menu_icon' => 'dashicons-media-document',
            'menu_position' => 25,
            'supports' => array('title', 'editor'),
            'has_archive' => false,
            'rewrite' => false,
            'capability_type' => 'post',
            'show_in_rest' => true
        ));
        
        
        register_post_type('divine_agreement', array(
            'labels' => array(
                'name' => __('Agreements', 'divine-agreement-system'),
                'singular_name' => __('Agreement', 'divine-agreement-system'),
                'add_new' => __('Add New Agreement', 'divine-agreement-system'),
                'add_new_item' => __('Add New Agreement', 'divine-agreement-system'),
                'edit_item' => __('Edit Agreement', 'divine-agreement-system'),
                'new_item' => __('New Agreement', 'divine-agreement-system'),
                'view_item' => __('View Agreement', 'divine-agreement-system'),
                'search_items' => __('Search Agreements', 'divine-agreement-system'),
                'not_found' => __('No agreements found', 'divine-agreement-system'),
                'not_found_in_trash' => __('No agreements found in trash', 'divine-agreement-system')
            ),
            'public' => false,
            'show_ui' => true,
            'show_in_menu' => true,
            'menu_icon' => 'dashicons-clipboard',
            'menu_position' => 26,
            'supports' => array('title'),
            'has_archive' => false,
            'rewrite' => false,
            'capability_type' => 'post',
            'show_in_rest' => false
        ));
    }
    
    
    public static function divine_add_meta_boxes() {
        
        add_meta_box(
            'divine_template_info',
            __('Template Information', 'divine-agreement-system'),
            array(__CLASS__, 'divine_template_meta_box'),
            'divine_template',
            'side',
            'default'
        );
        
        
        add_meta_box(
            'divine_agreement_details',
            __('Agreement Details', 'divine-agreement-system'),
            array(__CLASS__, 'divine_agreement_details_meta_box'),
            'divine_agreement',
            'normal',
            'high'
        );
        
        
        add_meta_box(
            'divine_agreement_status',
            __('Agreement Status', 'divine-agreement-system'),
            array(__CLASS__, 'divine_agreement_status_meta_box'),
            'divine_agreement',
            'side',
            'high'
        );
        
        
        add_meta_box(
            'divine_signing_link',
            __('Signing Link', 'divine-agreement-system'),
            array(__CLASS__, 'divine_signing_link_meta_box'),
            'divine_agreement',
            'side',
            'default'
        );
    }
    
    
    public static function divine_template_meta_box($post) {
        ?>
        <div class="divine-template-info">
            <p><strong><?php esc_html_e('Available Placeholders:', 'divine-agreement-system'); ?></strong></p>
            <ul style="list-style: disc; padding-left: 20px;">
                <li><code>[COLLABORATOR_NAME]</code></li>
                <li><code>[COLLABORATOR_EMAIL]</code></li>
                <li><code>[COLLABORATOR_ADDRESS]</code></li>
                <li><code>[COMPENSATION_DETAILS]</code></li>
                <li><code>[DATE]</code></li>
                <li><code>[CURRENT_DATE]</code></li>
            </ul>
            <p class="description">
                <?php esc_html_e('Use these placeholders in your template content. They will be replaced with actual values when the agreement is created.', 'divine-agreement-system'); ?>
            </p>
        </div>
        <?php
    }
    
    
    public static function divine_agreement_details_meta_box($post) {
        wp_nonce_field('divine_agreement_meta_nonce', 'divine_agreement_nonce');
        
        $template_id = get_post_meta($post->ID, '_divine_template_id', true);
        $collaborator_name = get_post_meta($post->ID, '_divine_collaborator_name', true);
        $collaborator_email = get_post_meta($post->ID, '_divine_collaborator_email', true);
        $collaborator_address = get_post_meta($post->ID, '_divine_collaborator_address', true);
        $compensation = get_post_meta($post->ID, '_divine_compensation', true);
        
        
        $templates = get_posts(array(
            'post_type' => 'divine_template',
            'posts_per_page' => -1,
            'post_status' => 'publish'
        ));
        ?>
        <table class="form-table">
            <tr>
                <th><label for="divine_template_id"><?php esc_html_e('Agreement Template', 'divine-agreement-system'); ?></label></th>
                <td>
                    <select name="divine_template_id" id="divine_template_id" class="regular-text" required>
                        <option value=""><?php esc_html_e('Select Template', 'divine-agreement-system'); ?></option>
                        <?php foreach ($templates as $template) : ?>
                            <option value="<?php echo esc_attr($template->ID); ?>" <?php selected($template_id, $template->ID); ?>>
                                <?php echo esc_html($template->post_title); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </td>
            </tr>
            <tr>
                <th><label for="divine_collaborator_name"><?php esc_html_e('Collaborator Name', 'divine-agreement-system'); ?></label></th>
                <td>
                    <input type="text" name="divine_collaborator_name" id="divine_collaborator_name" 
                           class="regular-text" value="<?php echo esc_attr($collaborator_name); ?>" required>
                </td>
            </tr>
            <tr>
                <th><label for="divine_collaborator_email"><?php esc_html_e('Collaborator Email', 'divine-agreement-system'); ?></label></th>
                <td>
                    <input type="email" name="divine_collaborator_email" id="divine_collaborator_email" 
                           class="regular-text" value="<?php echo esc_attr($collaborator_email); ?>" required>
                </td>
            </tr>
            <tr>
                <th><label for="divine_collaborator_address"><?php esc_html_e('Collaborator Address', 'divine-agreement-system'); ?></label></th>
                <td>
                    <textarea name="divine_collaborator_address" id="divine_collaborator_address" 
                              class="large-text" rows="3"><?php echo esc_textarea($collaborator_address); ?></textarea>
                </td>
            </tr>
            <tr>
                <th><label for="divine_compensation"><?php esc_html_e('Compensation Details', 'divine-agreement-system'); ?></label></th>
                <td>
                    <textarea name="divine_compensation" id="divine_compensation" 
                              class="large-text" rows="3"><?php echo esc_textarea($compensation); ?></textarea>
                </td>
            </tr>
        </table>
        <?php
    }
    
    
    public static function divine_agreement_status_meta_box($post) {
        $status = get_post_meta($post->ID, '_divine_status', true);
        $status = $status ? $status : 'pending';
        $signed_date = get_post_meta($post->ID, '_divine_signed_date', true);
        $signed_ip = get_post_meta($post->ID, '_divine_signed_ip', true);
        $pdf_path = get_post_meta($post->ID, '_divine_pdf_path', true);
        ?>
        <div class="divine-status-info">
            <p>
                <strong><?php esc_html_e('Status:', 'divine-agreement-system'); ?></strong>
                <span class="divine-status-badge divine-status-<?php echo esc_attr($status); ?>">
                    <?php echo esc_html(ucfirst($status)); ?>
                </span>
            </p>
            
            <?php if ($status === 'signed' && $signed_date) : ?>
                <p>
                    <strong><?php esc_html_e('Signed On:', 'divine-agreement-system'); ?></strong><br>
                    <?php echo esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($signed_date))); ?>
                </p>
            <?php endif; ?>
            
            <?php if ($signed_ip) : ?>
                <p>
                    <strong><?php esc_html_e('IP Address:', 'divine-agreement-system'); ?></strong><br>
                    <?php echo esc_html($signed_ip); ?>
                </p>
            <?php endif; ?>
            
            <?php if ($pdf_path && file_exists($pdf_path)) : ?>
                <p>
                    <a href="<?php echo esc_url(wp_nonce_url(admin_url('admin-post.php?action=divine_download_pdf&agreement_id=' . $post->ID), 'divine_download_pdf')); ?>" 
                       class="button button-secondary" target="_blank">
                        <?php esc_html_e('Download PDF', 'divine-agreement-system'); ?>
                    </a>
                </p>
            <?php endif; ?>
        </div>
        <?php
    }
    
    
    public static function divine_signing_link_meta_box($post) {
        $token = get_post_meta($post->ID, '_divine_token', true);
        $status = get_post_meta($post->ID, '_divine_status', true);
        
        if (!$token) {
            ?>
            <p class="description">
                <?php esc_html_e('Token will be generated when you publish this agreement.', 'divine-agreement-system'); ?>
            </p>
            <?php
            return;
        }
        
        $signing_url = Divine_Token::divine_get_signing_url($token);
        ?>
        <div class="divine-signing-link">
            <p><strong><?php esc_html_e('Signing URL:', 'divine-agreement-system'); ?></strong></p>
            <input type="text" value="<?php echo esc_url($signing_url); ?>" 
                   class="widefat" readonly onclick="this.select();">
            
            <p style="margin-top: 10px;">
                <button type="button" class="button button-secondary" 
                        onclick="navigator.clipboard.writeText('<?php echo esc_js($signing_url); ?>'); alert('<?php echo esc_js(esc_html__('Link copied!', 'divine-agreement-system')); ?>');">
                    <?php esc_html_e('Copy Link', 'divine-agreement-system'); ?>
                </button>
            </p>
            
            <?php if ($status !== 'signed') : ?>
                <p style="margin-top: 10px;">
                    <a href="<?php echo esc_url(wp_nonce_url(admin_url('admin-post.php?action=divine_send_agreement_email&agreement_id=' . $post->ID), 'divine_send_agreement_email')); ?>" 
                       class="button button-primary divine-send-email-btn">
                        <?php esc_html_e('Send Divine Agreement Email', 'divine-agreement-system'); ?>
                    </a>
                </p>
            <?php endif; ?>
        </div>
        <?php
    }
    
    
    public static function divine_save_agreement_meta($post_id) {
        
        if (!isset($_POST['divine_agreement_nonce']) || 
            !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['divine_agreement_nonce'])), 'divine_agreement_meta_nonce')) {
            return;
        }
        
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        if (get_post_type($post_id) !== 'divine_agreement') {
            return;
        }
        
        
        if (isset($_POST['divine_template_id'])) {
            update_post_meta($post_id, '_divine_template_id', absint(wp_unslash($_POST['divine_template_id'])));
        }

        if (isset($_POST['divine_collaborator_name'])) {
            update_post_meta($post_id, '_divine_collaborator_name', sanitize_text_field(wp_unslash($_POST['divine_collaborator_name'])));
        }

        if (isset($_POST['divine_collaborator_email'])) {
            update_post_meta($post_id, '_divine_collaborator_email', sanitize_email(wp_unslash($_POST['divine_collaborator_email'])));
        }

        if (isset($_POST['divine_collaborator_address'])) {
            update_post_meta($post_id, '_divine_collaborator_address', sanitize_textarea_field(wp_unslash($_POST['divine_collaborator_address'])));
        }

        if (isset($_POST['divine_compensation'])) {
            update_post_meta($post_id, '_divine_compensation', sanitize_textarea_field(wp_unslash($_POST['divine_compensation'])));
        }
        
        
        $token = get_post_meta($post_id, '_divine_token', true);
        if (!$token && get_post_status($post_id) === 'publish') {
            $token = Divine_Token::divine_generate_token($post_id);
            update_post_meta($post_id, '_divine_token', $token);
        }
        
        
        $status = get_post_meta($post_id, '_divine_status', true);
        if (!$status) {
            update_post_meta($post_id, '_divine_status', 'pending');
        }
    }
    
    
    public static function divine_agreement_columns($columns) {
        $new_columns = array();
        $new_columns['cb'] = $columns['cb'];
        $new_columns['title'] = $columns['title'];
        $new_columns['divine_collaborator'] = __('Collaborator', 'divine-agreement-system');
        $new_columns['divine_status'] = __('Status', 'divine-agreement-system');
        $new_columns['divine_signed_date'] = __('Signed Date', 'divine-agreement-system');
        $new_columns['date'] = $columns['date'];
        
        return $new_columns;
    }
    
    
    public static function divine_agreement_column_content($column, $post_id) {
        switch ($column) {
            case 'divine_collaborator':
                $name = get_post_meta($post_id, '_divine_collaborator_name', true);
                $email = get_post_meta($post_id, '_divine_collaborator_email', true);
                echo esc_html($name);
                if ($email) {
                    echo '<br><small>' . esc_html($email) . '</small>';
                }
                break;
                
            case 'divine_status':
                $status = get_post_meta($post_id, '_divine_status', true);
                $status = $status ? $status : 'pending';
                echo '<span class="divine-status-badge divine-status-' . esc_attr($status) . '">';
                echo esc_html(ucfirst($status));
                echo '</span>';
                break;
                
            case 'divine_signed_date':
                $signed_date = get_post_meta($post_id, '_divine_signed_date', true);
                if ($signed_date) {
                    echo esc_html(date_i18n(get_option('date_format'), strtotime($signed_date)));
                } else {
                    echo '&mdash;';
                }
                break;
        }
    }
}


Divine_Post_Types::init();
