<?php
/**
 * Contract View/Preview
 */
if (!defined('ABSPATH')) exit;

$services = $contract->services ?: array();
$deposit_amount = FS_Contract::calculate_deposit($contract);
$is_expired = FS_Contract::is_expired($contract);
$primary_color = !empty($settings['invoice_primary_color']) ? $settings['invoice_primary_color'] : '#3ECFB2';
$color_mode = !empty($settings['invoice_primary_color_mode']) ? $settings['invoice_primary_color_mode'] : 'solid';
$color_2 = !empty($settings['invoice_primary_color_2']) ? $settings['invoice_primary_color_2'] : $primary_color;
$grad_dir = !empty($settings['invoice_gradient_direction']) ? intval($settings['invoice_gradient_direction']) : 135;
$primary_bg = ($color_mode === 'gradient' && !empty($color_2))
    ? 'linear-gradient(' . $grad_dir . 'deg, ' . esc_attr($primary_color) . ' 0%, ' . esc_attr($color_2) . ' 100%)'
    : esc_attr($primary_color);

// Get enabled sections
$enabled_sections = FS_Contract::get_enabled_sections($contract);
$all_sections = class_exists('FS_Contract_Section') ? FS_Contract_Section::get_all_keyed() : array();

// Get contractor signature from settings
$contractor_signature = !empty($settings['contractor_signature']) ? $settings['contractor_signature'] : '';
$contractor_signer_name = !empty($settings['contractor_signer_name']) ? $settings['contractor_signer_name'] : $settings['business_name'];
$contractor_signer_title = !empty($settings['contractor_signer_title']) ? $settings['contractor_signer_title'] : '';

// Contract number
$contract_number = 'CON-' . gmdate('Y', strtotime($contract->created_at)) . '-' . str_pad($contract->id, 3, '0', STR_PAD_LEFT);
?>
<div class="wrap fs-wrap">
    <?php if (!empty($message) && isset($messages[$message])): ?>
        <div class="notice notice-<?php echo $message === 'error' ? 'error' : 'success'; ?> is-dismissible">
            <p><?php echo esc_html($messages[$message]); ?></p>
        </div>
    <?php endif; ?>
    
    <div class="fs-list-header">
        <h1><?php echo esc_html($contract->title); ?></h1>
        <div>
            <?php if (!in_array($contract->status, array('signed', 'completed'))): ?>
                <a href="#" class="fs-btn fs-btn-primary fs-send-email-btn" data-type="contract" data-id="<?php echo  intval( $contract->id ); ?>" data-client-id="<?php echo  intval( $contract->client_id ); ?>">
                    <?php echo  esc_html( $contract->status === 'draft' ? __('Send to Client', 'freelance-studio') : __('Resend to Client', 'freelance-studio') ); ?>
                </a>
            <?php endif; ?>
            <?php if ( function_exists( 'fs_studio_is_free_plan' ) && fs_studio_is_free_plan() ): ?>
                <span class="fs-btn fs-btn-secondary fs-btn-pro-gate" onclick="alert('<?php echo esc_js( __( 'PDF downloads are available with Freelance Studio Pro.', 'freelance-studio' ) ); ?>')">
                    <?php esc_html_e('PDF', 'freelance-studio'); ?>
                </span>
            <?php else: ?>
                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-contracts&action=pdf&id=' . $contract->id) ); ?>" class="fs-btn fs-btn-secondary" target="_blank">
                    <?php esc_html_e('PDF', 'freelance-studio'); ?>
                </a>
            <?php endif; ?>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-contracts&action=edit&id=' . $contract->id) ); ?>" class="fs-btn fs-btn-secondary">
                <?php esc_html_e('Edit', 'freelance-studio'); ?>
            </a>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-contracts&action=duplicate&id=' . $contract->id) ); ?>" class="fs-btn fs-btn-secondary">
                <?php esc_html_e('Duplicate', 'freelance-studio'); ?>
            </a>
            <?php if ($contract->status === 'signed'): ?>
                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=add&contract_id=' . $contract->id) ); ?>" class="fs-btn fs-btn-primary">
                    <?php esc_html_e('Create Project', 'freelance-studio'); ?>
                </a>
                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-contracts&action=complete&id=' . $contract->id) ); ?>" class="fs-btn fs-btn-secondary" onclick="return confirm('<?php esc_attr_e('Mark this contract as complete?', 'freelance-studio'); ?>');">
                    <?php esc_html_e('Mark Complete', 'freelance-studio'); ?>
                </a>
            <?php endif; ?>
            <?php if (in_array($contract->status, array('signed', 'completed'))): ?>
                <button type="button" class="fs-btn fs-btn-secondary fs-open-invoice-wizard" data-client-id="<?php echo esc_attr($contract->client_id); ?>">
                    <?php esc_html_e('Create Invoice', 'freelance-studio'); ?>
                </button>
            <?php endif; ?>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-contracts') ); ?>" class="fs-btn fs-btn-secondary">
                <?php esc_html_e('Back to Contracts', 'freelance-studio'); ?>
            </a>
        </div>
    </div>
    
    <!-- Status Bar -->
    <div class="fs-proposal-status-bar">
        <div class="fs-status-info">
            <span class="fs-status-label"><?php esc_html_e('Status:', 'freelance-studio'); ?></span>
            <?php echo  wp_kses_post( FS_View_Context::status_badge($contract->status) ); ?>
            
            <?php if ($contract->sent_at): ?>
                <?php /* translators: 1. sent value */ ?>
                <span class="fs-status-meta"><?php echo wp_kses_post( sprintf( __('Sent %s', 'freelance-studio'), FS_View_Context::format_date($contract->sent_at))); ?></span>
            <?php endif; ?>
            
            <?php if ($contract->viewed_at): ?>
                <?php /* translators: 1. viewed value */ ?>
                <span class="fs-status-meta"><?php echo wp_kses_post( sprintf( __('Viewed %s', 'freelance-studio'), FS_View_Context::format_date($contract->viewed_at))); ?></span>
            <?php endif; ?>
            
            <?php if ($contract->signed_at): ?>
                <?php /* translators: 1. signed value */ ?>
                <span class="fs-status-meta"><?php echo wp_kses_post( sprintf( __('Signed %s', 'freelance-studio'), FS_View_Context::format_date($contract->signed_at))); ?></span>
            <?php endif; ?>
        </div>
        
        <?php if ($contract->valid_until && !in_array($contract->status, array('signed', 'completed'))): ?>
            <div class="fs-expiry-info <?php echo $is_expired ? 'expired' : ''; ?>">
                <?php if ($is_expired): ?>
                    <?php esc_html_e('Expired', 'freelance-studio'); ?>
                <?php else: ?>
                    <?php /* translators: 1. date/time */ ?>
                    <?php echo esc_html( sprintf( __( 'Valid until %s', 'freelance-studio'), FS_View_Context::format_date($contract->valid_until)) ); ?>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
    
    <!-- Two Column Layout -->
    <?php $contract_link = home_url('?fs_contract=' . $contract->view_token); ?>
    <div class="fs-view-two-col">
        <!-- Main Content -->
        <div class="fs-view-main">
            <!-- Contract Preview (matches client view) -->
            <div class="fs-doc-preview" style="--fs-primary: <?php echo esc_attr($primary_color); ?>; --fs-primary-bg: <?php echo  esc_attr( $primary_bg ); ?>">
                <!-- Colored Header -->
                <div class="fs-doc-preview-header">
                    <?php
                        $header_logo = !empty($settings['business_logo_light']) ? $settings['business_logo_light'] : (!empty($settings['business_logo']) ? $settings['business_logo'] : '');
                    ?>
                    <?php if ($header_logo): ?>
                        <img src="<?php echo esc_url($header_logo); ?>" alt="<?php echo esc_attr($settings['business_name']); ?>" class="fs-doc-preview-logo">
                    <?php endif; ?>
                    <div class="fs-doc-preview-business"><?php echo esc_html($settings['business_name']); ?></div>
                    <h1 class="fs-doc-preview-title"><?php echo esc_html($contract->title); ?></h1>
                    <?php /* translators: 1. number/ID */ ?>
                    <div class="fs-doc-preview-number"><?php echo wp_kses_post( sprintf( __('Contract #%s', 'freelance-studio'), esc_html($contract_number))); ?></div>
                    <?php 
                    $display_status = $contract->status;
                    if ($contract->status === 'approved' || $contract->status === 'signed') {
                        $display_status = 'approved';
                    }
                    echo  wp_kses_post( FS_View_Context::status_badge($display_status) );                    ?>
                </div>
                
                <!-- Body Content -->
                <div class="fs-doc-preview-body">
                    <!-- Parties -->
                    <div class="fs-doc-preview-parties">
                        <h2 class="fs-doc-preview-section-title"><?php esc_html_e('Parties', 'freelance-studio'); ?></h2>
                        <div class="fs-doc-preview-parties-grid">
                            <div class="fs-doc-preview-party-card">
                                <div class="fs-doc-preview-party-label contractor"><?php esc_html_e('Contractor', 'freelance-studio'); ?></div>
                                <div class="fs-doc-preview-party-name"><?php echo esc_html($settings['business_name']); ?></div>
                                <?php if (!empty($settings['business_email'])): ?>
                                    <p><?php echo esc_html($settings['business_email']); ?></p>
                                <?php endif; ?>
                                <?php if (!empty($settings['business_phone'])): ?>
                                    <p><?php echo esc_html($settings['business_phone']); ?></p>
                                <?php endif; ?>
                            </div>
                            
                            <div class="fs-doc-preview-party-card">
                                <div class="fs-doc-preview-party-label client"><?php esc_html_e('Client', 'freelance-studio'); ?></div>
                                <?php 
                                $display_contact = FS_Contract::get_display_contact($contract, $client);
                                if ($display_contact->name || $display_contact->company_name): ?>
                                    <?php if (!empty($display_contact->company_name)): ?>
                                        <div class="fs-doc-preview-party-name"><?php echo esc_html($display_contact->company_name); ?></div>
                                        <p><?php echo esc_html($display_contact->name); ?></p>
                                    <?php else: ?>
                                        <div class="fs-doc-preview-party-name"><?php echo esc_html($display_contact->name); ?></div>
                                    <?php endif; ?>
                                    <?php if (!empty($display_contact->email)): ?>
                                        <p><?php echo esc_html($display_contact->email); ?></p>
                                    <?php endif; ?>
                                    <?php if (!empty($display_contact->phone)): ?>
                                        <p><?php echo esc_html($display_contact->phone); ?></p>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <p class="text-muted"><?php esc_html_e('No client selected', 'freelance-studio'); ?></p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Dates -->
                    <?php 
                    $has_start = !empty($contract->start_date) && $contract->start_date !== '0000-00-00';
                    $has_end = !empty($contract->end_date) && $contract->end_date !== '0000-00-00';
                    $has_valid = !empty($contract->valid_until) && $contract->valid_until !== '0000-00-00';
                    ?>
                    <?php if ($has_start || $has_end || $has_valid): ?>
                    <div class="fs-doc-preview-dates">
                        <?php if ($has_start): ?>
                        <div class="fs-doc-preview-date-item">
                            <label><?php esc_html_e('Start Date', 'freelance-studio'); ?></label>
                            <span><?php echo  esc_html( FS_View_Context::format_date($contract->start_date) ); ?></span>
                        </div>
                        <?php endif; ?>
                        <?php if ($has_end): ?>
                        <div class="fs-doc-preview-date-item">
                            <label><?php esc_html_e('End Date', 'freelance-studio'); ?></label>
                            <span><?php echo  esc_html( FS_View_Context::format_date($contract->end_date) ); ?></span>
                        </div>
                        <?php elseif ($has_valid): ?>
                        <div class="fs-doc-preview-date-item <?php echo $is_expired ? 'overdue' : ''; ?>">
                            <label><?php esc_html_e('Valid Until', 'freelance-studio'); ?></label>
                            <span><?php echo  esc_html( FS_View_Context::format_date($contract->valid_until) ); ?></span>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Project Description -->
                    <?php if (!empty($contract->description)): ?>
                    <div class="fs-doc-preview-custom-section">
                        <h3><?php esc_html_e('Project Description', 'freelance-studio'); ?></h3>
                        <div class="fs-doc-custom-section-content">
                            <?php echo wp_kses_post(wpautop($contract->description)); ?>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Services -->
                    <?php if (!empty($services)): ?>
                    <div class="fs-doc-preview-section">
                        <h2 class="fs-doc-preview-section-title"><?php esc_html_e('Services', 'freelance-studio'); ?></h2>
                        <table class="fs-doc-preview-table">
                            <thead>
                                <tr>
                                    <th><?php esc_html_e('Service', 'freelance-studio'); ?></th>
                                    <th><?php esc_html_e('Amount', 'freelance-studio'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($services as $service): ?>
                                <tr>
                                    <td>
                                        <div class="fs-doc-preview-item-name"><?php echo esc_html($service['name']); ?></div>
                                        <?php if (!empty($service['description'])): ?>
                                            <div class="fs-doc-preview-item-desc"><?php echo nl2br(esc_html($service['description'])); ?></div>
                                        <?php endif; ?>
                                        <?php 
                                        $rate_type = $service['rate_type'] ?? 'flat';
                                        if ($rate_type === 'hourly' && !empty($service['hours'])): ?>
                                            <div class="fs-doc-preview-item-meta">
                                                <?php echo esc_html($service['hours']); ?> <?php esc_html_e('hours', 'freelance-studio'); ?> 
                                                × <?php echo  esc_html( FS_View_Context::format_currency($service['rate'] ?? 0) ); ?>
                                            </div>
                                        <?php elseif ($rate_type === 'flat'): ?>
                                            <div class="fs-doc-preview-item-meta"><?php esc_html_e('Flat fee', 'freelance-studio'); ?></div>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo  esc_html( FS_View_Context::format_currency($service['amount'] ?? 0) ); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                        
                        <!-- Totals -->
                        <div class="fs-doc-preview-totals">
                            <div class="fs-doc-preview-totals-row grand-total">
                                <span class="fs-doc-preview-totals-label"><?php esc_html_e('Total', 'freelance-studio'); ?></span>
                                <span class="fs-doc-preview-totals-value"><?php echo  esc_html( FS_View_Context::format_currency($contract->total_amount) ); ?></span>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Contract Terms/Sections -->
                    <?php if (!empty($enabled_sections)): ?>
                    <div class="fs-doc-preview-terms">
                        <h2 class="fs-doc-preview-section-title"><?php esc_html_e('Terms & Conditions', 'freelance-studio'); ?></h2>
                        
                        <?php foreach ($enabled_sections as $section_slug): ?>
                            <?php 
                            if (!isset($all_sections[$section_slug])) continue;
                            $section = $all_sections[$section_slug];
                            $content = FS_Contract::process_section_content($section['content'], $contract, $client, $settings);
                            ?>
                            <div class="fs-doc-preview-term-section">
                                <h3 class="fs-doc-preview-term-title"><?php echo esc_html($section['title']); ?></h3>
                                <div class="fs-doc-preview-term-content">
                                    <?php echo wp_kses_post(wpautop($content)); ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Signatures -->
                    <?php if (in_array($contract->status, array('signed', 'approved', 'completed')) || !empty($contractor_signature)): ?>
                    <div class="fs-doc-preview-signatures">
                        <div class="fs-doc-preview-signatures-grid">
                            <div class="fs-doc-preview-signature-block">
                                <div class="fs-doc-preview-signature-label"><?php esc_html_e('Contractor', 'freelance-studio'); ?></div>
                                <?php if (!empty($contractor_signature)): ?>
                                    <div class="fs-doc-preview-signature-image">
                                        <img src="<?php echo esc_attr($contractor_signature); ?>" alt="<?php esc_attr_e('Contractor Signature', 'freelance-studio'); ?>">
                                    </div>
                                <?php else: ?>
                                    <div class="fs-doc-preview-signature-pending"><?php esc_html_e('Pending', 'freelance-studio'); ?></div>
                                <?php endif; ?>
                                <div class="fs-doc-preview-signature-line"></div>
                                <div class="fs-doc-preview-signature-name"><?php echo esc_html($contractor_signer_name); ?></div>
                                <?php if (!empty($contractor_signer_title)): ?>
                                    <div class="fs-doc-preview-signature-title"><?php echo esc_html($contractor_signer_title); ?></div>
                                <?php endif; ?>
                            </div>
                            
                            <div class="fs-doc-preview-signature-block">
                                <div class="fs-doc-preview-signature-label"><?php esc_html_e('Client', 'freelance-studio'); ?></div>
                                <?php if (in_array($contract->status, array('signed', 'completed')) && !empty($contract->signature_client)): ?>
                                    <div class="fs-doc-preview-signature-image">
                                        <img src="<?php echo esc_attr($contract->signature_client); ?>" alt="<?php esc_attr_e('Client Signature', 'freelance-studio'); ?>">
                                    </div>
                                    <div class="fs-doc-preview-signature-line"></div>
                                    <div class="fs-doc-preview-signature-name"><?php echo esc_html($contract->signature_client_name); ?></div>
                                    <div class="fs-doc-preview-signature-date"><?php echo  esc_html( FS_View_Context::format_date($contract->signed_at) ); ?></div>
                                <?php else: ?>
                                    <div class="fs-doc-preview-signature-pending"><?php esc_html_e('Awaiting signature', 'freelance-studio'); ?></div>
                                    <div class="fs-doc-preview-signature-line"></div>
                                    <div class="fs-doc-preview-signature-name"><?php echo esc_html($display_contact->name ?: ($client->name ?? '')); ?></div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div><!-- End fs-doc-preview -->
        </div><!-- End fs-view-main -->
        
        <!-- Sidebar -->
        <div class="fs-view-sidebar">
            <!-- Client Link Card -->
            <div class="fs-client-link-card">
                <div class="fs-client-link-card-header">
                    <h3><?php esc_html_e('Client Link', 'freelance-studio'); ?></h3>
                </div>
                <div class="fs-client-link-card-body">
                    <p class="text-muted" style="margin-bottom: 12px; font-size: 13px;"><?php esc_html_e('Share this link with your client to view and sign.', 'freelance-studio'); ?></p>
                    <input type="text" id="fs-contract-link" value="<?php echo esc_url($contract_link); ?>" readonly class="fs-link-input">
                    <div class="fs-link-buttons">
                        <button type="button" class="button fs-copy-link-btn" data-target="fs-contract-link">
                            <span class="dashicons dashicons-clipboard"></span> <?php esc_html_e('Copy', 'freelance-studio'); ?>
                        </button>
                        <a href="<?php echo esc_url($contract_link); ?>" target="_blank" class="button">
                            <span class="dashicons dashicons-external"></span> <?php esc_html_e('Preview', 'freelance-studio'); ?>
                        </a>
                    </div>
                </div>
            </div>
            
            <!-- Quick Stats Card -->
            <div class="fs-project-card">
                <div class="fs-card-header">
                    <h3 class="fs-card-title"><?php esc_html_e('Summary', 'freelance-studio'); ?></h3>
                </div>
                <div class="fs-card-body">
                    <div class="fs-summary-row">
                        <span class="fs-summary-label"><?php esc_html_e('Total', 'freelance-studio'); ?></span>
                        <span class="fs-summary-value"><?php echo  esc_html( FS_View_Context::format_currency($contract->total_amount) ); ?></span>
                    </div>
                    <?php if ($deposit_amount > 0): ?>
                    <div class="fs-summary-row">
                        <span class="fs-summary-label"><?php esc_html_e('Deposit', 'freelance-studio'); ?></span>
                        <span class="fs-summary-value"><?php echo  esc_html( FS_View_Context::format_currency($deposit_amount) ); ?></span>
                    </div>
                    <?php endif; ?>
                    <?php if ($contract->start_date): ?>
                    <div class="fs-summary-row">
                        <span class="fs-summary-label"><?php esc_html_e('Start Date', 'freelance-studio'); ?></span>
                        <span class="fs-summary-value"><?php echo  esc_html( FS_View_Context::format_date($contract->start_date) ); ?></span>
                    </div>
                    <?php endif; ?>
                    <?php if ($contract->valid_until): ?>
                    <div class="fs-summary-row">
                        <span class="fs-summary-label"><?php esc_html_e('Valid Until', 'freelance-studio'); ?></span>
                        <span class="fs-summary-value"><?php echo  esc_html( FS_View_Context::format_date($contract->valid_until) ); ?></span>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div><!-- End fs-view-sidebar -->
    </div><!-- End fs-view-two-col -->
</div>

<script>
jQuery(document).ready(function($) {
    // Copy link functionality
    $('.fs-copy-link-btn').on('click', function() {
        var targetId = $(this).data('target');
        var $input = $('#' + targetId);
        var $btn = $(this);
        
        $input.select();
        $input[0].setSelectionRange(0, 99999);
        
        try {
            document.execCommand('copy');
            $btn.addClass('copied');
            $btn.find('.dashicons').removeClass('dashicons-clipboard').addClass('dashicons-yes');
            $btn.contents().filter(function() { return this.nodeType === 3; }).first()[0].textContent = ' <?php esc_html_e('Copied!', 'freelance-studio'); ?>';
            
            setTimeout(function() {
                $btn.removeClass('copied');
                $btn.find('.dashicons').removeClass('dashicons-yes').addClass('dashicons-clipboard');
                $btn.contents().filter(function() { return this.nodeType === 3; }).first()[0].textContent = ' <?php esc_html_e('Copy', 'freelance-studio'); ?>';
            }, 2000);
        } catch (err) {
            alert('<?php esc_html_e('Failed to copy. Please select and copy manually.', 'freelance-studio'); ?>');
        }
    });
});
</script>

<?php include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/invoice-wizard-modal.php'; ?>
