<?php
/**
 * Project Templates List View
 *
 * @package Freelance_Studio
 */

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

$messages = array(
    'saved' => __('Template saved successfully.', 'freelance-studio'),
    'duplicated' => __('Template duplicated successfully.', 'freelance-studio'),
    'deleted' => __('Template deleted.', 'freelance-studio'),
    'imported' => __('Templates imported successfully.', 'freelance-studio'),
);

// Get library templates and their import status
$library_templates = FS_Template_Library::get_templates();
$library_categories = FS_Template_Library::get_categories();
$imported_status = FS_Template_Library::get_imported_status();
?>

<div class="wrap fs-wrap">
    <?php if ($message && isset($messages[$message])): ?>
        <div class="notice notice-success is-dismissible">
            <p><?php echo esc_html($messages[$message]); ?></p>
        </div>
    <?php endif; ?>

    <div class="fs-list-header">
        <h1><?php esc_html_e('Project Templates', 'freelance-studio'); ?></h1>
        <div class="fs-header-buttons">
            <button type="button" class="fs-btn fs-btn-secondary" id="open-template-library">
                <span class="dashicons dashicons-download" style="margin-right: 5px;"></span>
                <?php esc_html_e('Template Library', 'freelance-studio'); ?>
            </button>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-project-templates&action=add') ); ?>" class="fs-btn fs-btn-primary">
                <?php esc_html_e('New Template', 'freelance-studio'); ?>
            </a>
        </div>
    </div>

    <p class="description" style="margin-bottom: 20px;">
        <?php esc_html_e('Create reusable project templates with predefined milestones and tasks. Apply templates when creating new projects to save time.', 'freelance-studio'); ?>
    </p>

    <table class="wp-list-table widefat fixed striped">
        <thead>
            <tr>
                <th><?php esc_html_e('Template Name', 'freelance-studio'); ?></th>
                <th style="width: 120px;"><?php esc_html_e('Billing Type', 'freelance-studio'); ?></th>
                <th style="width: 100px;"><?php esc_html_e('Milestones', 'freelance-studio'); ?></th>
                <th style="width: 100px;"><?php esc_html_e('Tasks', 'freelance-studio'); ?></th>
                <th style="width: 120px;"><?php esc_html_e('Est. Hours', 'freelance-studio'); ?></th>
                <th style="width: 150px;"><?php esc_html_e('Price Range', 'freelance-studio'); ?></th>
                <th style="width: 60px;" class="column-actions"></th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($templates)): ?>
                <tr>
                    <td colspan="7">
                        <?php esc_html_e('No templates found.', 'freelance-studio'); ?>
                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-project-templates&action=add') ); ?>">
                            <?php esc_html_e('Create your first template', 'freelance-studio'); ?>
                        </a>
                        <?php esc_html_e('or', 'freelance-studio'); ?>
                        <a href="#" id="open-template-library-link">
                            <?php esc_html_e('import from the Template Library', 'freelance-studio'); ?>
                        </a>
                    </td>
                </tr>
            <?php else: ?>
                <?php foreach ($templates as $template): ?>
                    <tr>
                        <td>
                            <strong>
                                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-project-templates&action=edit&id=' . $template->id) ); ?>">
                                    <?php echo esc_html($template->name); ?>
                                </a>
                            </strong>
                            <?php if ($template->description): ?>
                                <br><small class="fs-muted"><?php echo esc_html(wp_trim_words($template->description, 10)); ?></small>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php 
                            $billing_labels = array(
                                'hourly' => __('Hourly', 'freelance-studio'),
                                'fixed' => __('Fixed', 'freelance-studio'),
                                'retainer' => __('Retainer', 'freelance-studio'),
                            );
                            echo esc_html($billing_labels[$template->default_billing_type] ?? $template->default_billing_type);
                            ?>
                        </td>
                        <td><?php echo count($template->default_milestones); ?></td>
                        <td><?php echo count($template->default_tasks); ?></td>
                        <td>
                            <?php if ($template->estimated_hours): ?>
                                <?php echo number_format($template->estimated_hours, 1); ?> hrs
                            <?php else: ?>
                                <span class="fs-muted">—</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($template->typical_price_min || $template->typical_price_max): ?>
                                <?php 
                                if ($template->typical_price_min && $template->typical_price_max) {
                                    echo  esc_html( FS_View_Context::format_currency($template->typical_price_min) . ' - ' . FS_View_Context::format_currency($template->typical_price_max) );                                } elseif ($template->typical_price_min) {
                                    echo  esc_html( 'From ' . FS_View_Context::format_currency($template->typical_price_min) );                                } else {
                                    echo  esc_html( 'Up to ' . FS_View_Context::format_currency($template->typical_price_max) );                                }
                                ?>
                            <?php else: ?>
                                <span class="fs-muted">—</span>
                            <?php endif; ?>
                        </td>
                        <td class="column-actions">
                            <div class="fs-row-menu">
                                <button type="button" class="fs-row-menu-trigger">⋯</button>
                                <div class="fs-row-menu-dropdown">
                                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-project-templates&action=edit&id=' . $template->id) ); ?>"><?php esc_html_e('Edit', 'freelance-studio'); ?></a>
                                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-project-templates&action=duplicate&id=' . $template->id) ); ?>"><?php esc_html_e('Duplicate', 'freelance-studio'); ?></a>
                                    <hr>
                                    <a href="#" class="fs-delete-template text-danger" data-id="<?php echo esc_attr($template->id); ?>"><?php esc_html_e('Delete', 'freelance-studio'); ?></a>
                                </div>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<!-- Template Library Modal -->
<div id="fs-template-library-modal" class="fs-modal">
    <div class="fs-modal-content fs-modal--xlarge">
        <div class="fs-modal-header">
            <h2><?php esc_html_e('Template Library', 'freelance-studio'); ?></h2>
            <button type="button" class="fs-modal-close">&times;</button>
        </div>
        <div class="fs-modal-body">
            <p class="description" style="margin-bottom: 20px;">
                <?php esc_html_e('Select pre-built templates to import. These templates include common milestones and tasks for freelance design and development projects. You can customize them after importing.', 'freelance-studio'); ?>
            </p>
            
            <div class="fs-library-select-all" style="margin-bottom: 15px;">
                <label class="fs-checkbox-label">
                    <input type="checkbox" id="select-all-templates">
                    <strong><?php esc_html_e('Select All Available Templates', 'freelance-studio'); ?></strong>
                </label>
            </div>
            
            <?php foreach ($library_categories as $cat_slug => $cat_label): ?>
                <?php 
                $cat_templates = array_filter($library_templates, function($t) use ($cat_slug) {
                    return $t['category'] === $cat_slug;
                });
                if (empty($cat_templates)) continue;
                ?>
                <div class="fs-library-category">
                    <h3><?php echo esc_html($cat_label); ?></h3>
                    <div class="fs-library-grid">
                        <?php foreach ($cat_templates as $slug => $tpl): ?>
                            <?php $is_imported = $imported_status[$slug] ?? false; ?>
                            <div class="fs-library-card <?php echo $is_imported ? 'imported' : ''; ?>">
                                <label class="fs-library-card-content">
                                    <?php if (!$is_imported): ?>
                                        <input type="checkbox" name="import_templates[]" value="<?php echo esc_attr($slug); ?>" class="fs-library-checkbox">
                                    <?php endif; ?>
                                    <div class="fs-library-card-header">
                                        <h4><?php echo esc_html($tpl['name']); ?></h4>
                                        <?php if ($is_imported): ?>
                                            <span class="fs-badge fs-badge-success"><?php esc_html_e('Imported', 'freelance-studio'); ?></span>
                                        <?php endif; ?>
                                    </div>
                                    <p class="fs-library-card-desc"><?php echo esc_html($tpl['description']); ?></p>
                                    <div class="fs-library-card-meta">
                                        <span><strong><?php echo count($tpl['milestones']); ?></strong> <?php esc_html_e('milestones', 'freelance-studio'); ?></span>
                                        <span><strong><?php echo count($tpl['tasks']); ?></strong> <?php esc_html_e('tasks', 'freelance-studio'); ?></span>
                                        <?php if (!empty($tpl['estimated_hours'])): ?>
                                            <span><strong><?php echo  esc_html( $tpl['estimated_hours'] ); ?></strong> <?php esc_html_e('hrs', 'freelance-studio'); ?></span>
                                        <?php endif; ?>
                                    </div>
                                    <?php if (!empty($tpl['typical_price_min']) && !empty($tpl['typical_price_max'])): ?>
                                        <div class="fs-library-card-price">
                                            <?php echo  esc_html( FS_View_Context::format_currency($tpl['typical_price_min']) ); ?> - <?php echo  esc_html( FS_View_Context::format_currency($tpl['typical_price_max']) ); ?>
                                        </div>
                                    <?php endif; ?>
                                </label>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        <div class="fs-modal-footer">
            <button type="button" class="fs-btn fs-btn-secondary fs-modal-cancel"><?php esc_html_e('Cancel', 'freelance-studio'); ?></button>
            <button type="button" class="fs-btn fs-btn-primary" id="import-templates-btn">
                <?php esc_html_e('Import Selected Templates', 'freelance-studio'); ?>
            </button>
        </div>
    </div>
</div>

<style>
.fs-header-buttons {
    display: flex;
    gap: 10px;
}
.fs-modal--xlarge .fs-modal-content {
    max-width: 900px;
}
.fs-library-category {
    margin-bottom: 30px;
}
.fs-library-category h3 {
    margin: 0 0 15px 0;
    padding-bottom: 8px;
    border-bottom: 2px solid var(--fs-gray-200);
    color: var(--fs-gray-700);
    font-size: 16px;
}
.fs-library-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 15px;
}
.fs-library-card {
    border: 2px solid var(--fs-gray-300);
    border-radius: var(--fs-border-radius);
    background: #fff;
    transition: all 0.2s;
}
.fs-library-card:hover:not(.imported) {
    border-color: var(--fs-primary);
    box-shadow: 0 2px 8px rgba(62, 207, 178, 0.15);
}
.fs-library-card.imported {
    background: var(--fs-gray-100);
    opacity: 0.7;
}
.fs-library-card-content {
    display: block;
    padding: 15px;
    cursor: pointer;
}
.fs-library-card.imported .fs-library-card-content {
    cursor: default;
}
.fs-library-card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 8px;
}
.fs-library-card-header h4 {
    margin: 0;
    font-size: 14px;
    font-weight: 600;
    color: var(--fs-gray-800);
}
.fs-library-checkbox {
    float: right;
    margin-left: 10px;
}
.fs-library-card-desc {
    font-size: 12px;
    color: var(--fs-gray-600);
    margin: 0 0 10px 0;
    line-height: 1.4;
}
.fs-library-card-meta {
    display: flex;
    gap: 15px;
    font-size: 11px;
    color: var(--fs-gray-500);
}
.fs-library-card-meta strong {
    color: var(--fs-gray-700);
}
.fs-library-card-price {
    margin-top: 8px;
    padding-top: 8px;
    border-top: 1px solid var(--fs-gray-200);
    font-size: 12px;
    color: var(--fs-primary-dark);
    font-weight: 500;
}
.fs-badge {
    display: inline-block;
    padding: 2px 8px;
    font-size: 10px;
    font-weight: 600;
    text-transform: uppercase;
    border-radius: 10px;
}
.fs-badge-success {
    background: var(--fs-primary-xtralight);
    color: var(--fs-primary-dark);
}
.fs-library-select-all {
    padding: 10px 15px;
    background: var(--fs-gray-100);
    border-radius: var(--fs-border-radius);
}
</style>

<script>
jQuery(document).ready(function($) {
    // Delete template
    $('.fs-delete-template').on('click', function(e) {
        e.preventDefault();
        if (!confirm('<?php esc_html_e('Are you sure you want to delete this template?', 'freelance-studio'); ?>')) {
            return;
        }
        
        var id = $(this).data('id');
        var $row = $(this).closest('tr');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_delete_project_template',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                id: id
            },
            success: function(response) {
                if (response.success) {
                    $row.fadeOut(300, function() { $(this).remove(); });
                } else {
                    alert(response.data || 'Error deleting template');
                }
            }
        });
    });
    
    // Open template library modal
    $('#open-template-library, #open-template-library-link').on('click', function(e) {
        e.preventDefault();
        $('#fs-template-library-modal').addClass('active');
    });
    
    // Close template library modal
    $('#fs-template-library-modal .fs-modal-close, #fs-template-library-modal .fs-modal-cancel').on('click', function() {
        $('#fs-template-library-modal').removeClass('active');
    });
    
    $('#fs-template-library-modal').on('click', function(e) {
        if (e.target === this) {
            $(this).removeClass('active');
        }
    });
    
    // Select all templates
    $('#select-all-templates').on('change', function() {
        var isChecked = $(this).is(':checked');
        $('.fs-library-checkbox').prop('checked', isChecked);
    });
    
    // Update select all checkbox state
    $(document).on('change', '.fs-library-checkbox', function() {
        var total = $('.fs-library-checkbox').length;
        var checked = $('.fs-library-checkbox:checked').length;
        $('#select-all-templates').prop('checked', total === checked);
    });
    
    // Import templates
    $('#import-templates-btn').on('click', function() {
        var $btn = $(this);
        var slugs = [];
        
        $('.fs-library-checkbox:checked').each(function() {
            slugs.push($(this).val());
        });
        
        if (slugs.length === 0) {
            alert('<?php esc_html_e('Please select at least one template to import.', 'freelance-studio'); ?>');
            return;
        }
        
        $btn.prop('disabled', true).text('<?php esc_html_e('Importing...', 'freelance-studio'); ?>');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_import_library_template',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                slugs: slugs
            },
            success: function(response) {
                if (response.success) {
                    alert(response.data.message);
                    location.reload();
                } else {
                    alert(response.data || '<?php esc_html_e('Error importing templates', 'freelance-studio'); ?>');
                    $btn.prop('disabled', false).text('<?php esc_html_e('Import Selected Templates', 'freelance-studio'); ?>');
                }
            },
            error: function() {
                alert('<?php esc_html_e('Error importing templates', 'freelance-studio'); ?>');
                $btn.prop('disabled', false).text('<?php esc_html_e('Import Selected Templates', 'freelance-studio'); ?>');
            }
        });
    });
});
</script>
