<?php
/**
 * Proposal View/Preview
 *
 * @package Freelance_Studio
 */

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

$services = is_array($proposal->services) ? $proposal->services : array();
$custom_sections = is_array($proposal->custom_sections) ? $proposal->custom_sections : array();
$deposit_amount = FS_Proposal::calculate_deposit($proposal);
$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);

// Separate custom sections by position
$sections_before = array_filter($custom_sections, function($s) { return ($s['position'] ?? 'before_pricing') === 'before_pricing'; });
$sections_after = array_filter($custom_sections, function($s) { return ($s['position'] ?? '') === 'after_pricing'; });

// 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'] : '';

// Messages
$message = isset($_GET['message']) ? sanitize_text_field($_GET['message']) : '';
$messages = array(
    'created' => __('Proposal created successfully. Ready to send to client.', 'freelance-studio'),
    'updated' => __('Proposal updated successfully.', 'freelance-studio'),
    'sent' => __('Proposal sent to client.', 'freelance-studio'),
    'sent_no_email' => __('Proposal status updated, but email could not be sent. Check your SMTP settings.', 'freelance-studio'),
    'approved' => __('Proposal marked as approved.', 'freelance-studio'),
);

$billing_frequencies = array(
    'once' => __('Once', 'freelance-studio'),
    'weekly' => __('Weekly', 'freelance-studio'),
    'bi-weekly' => __('Bi-weekly', 'freelance-studio'),
    'monthly' => __('Monthly', 'freelance-studio'),
    'quarterly' => __('Quarterly', 'freelance-studio'),
);
?>

<div class="wrap fs-wrap">
    <?php if ($message && isset($messages[$message])): ?>
        <div class="notice <?php echo $message === 'sent_no_email' ? 'notice-warning' : 'notice-success'; ?> is-dismissible">
            <p><?php echo esc_html($messages[$message]); ?></p>
        </div>
    <?php endif; ?>
    
    <div class="fs-list-header">
        <h1><?php echo esc_html($proposal->title); ?></h1>
        <div>
            <?php if (!in_array($proposal->status, array('approved', 'converted'))): ?>
                <?php 
                $send_btn_text = __('Send to Client', 'freelance-studio');
                if ($proposal->status === 'revised') {
                    $send_btn_text = __('Send Revised Proposal', 'freelance-studio');
                } elseif ($proposal->status !== 'draft') {
                    $send_btn_text = __('Resend to Client', 'freelance-studio');
                }
                ?>
                <a href="#" class="fs-btn fs-btn-primary fs-send-email-btn" data-type="proposal" data-id="<?php echo  intval( $proposal->id ); ?>" data-client-id="<?php echo  intval( $proposal->client_id ); ?>">
                    <?php echo  esc_html( $send_btn_text ); ?>
                </a>
                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-proposals&action=approve&id=' . $proposal->id) ); ?>" class="fs-btn fs-btn-secondary" onclick="return confirm('<?php esc_attr_e('Mark this proposal as approved? Use this for verbal approvals.', 'freelance-studio'); ?>');">
                    <?php esc_html_e('Mark as Approved', '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-proposals&action=pdf&id=' . $proposal->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-proposals&action=edit&id=' . $proposal->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-proposals&action=duplicate&id=' . $proposal->id) ); ?>" class="fs-btn fs-btn-secondary">
                <?php esc_html_e('Duplicate', 'freelance-studio'); ?>
            </a>
            <?php if ($proposal->status === 'approved' && !$proposal->contract_id): ?>
                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-proposals&action=convert&id=' . $proposal->id) ); ?>" class="fs-btn fs-btn-deposit">
                    <?php esc_html_e('Convert to Contract', 'freelance-studio'); ?>
                </a>
            <?php endif; ?>
            <?php if ($proposal->status === 'approved'): ?>
                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=add&proposal_id=' . $proposal->id) ); ?>" class="fs-btn fs-btn-primary">
                    <?php esc_html_e('Create Project', 'freelance-studio'); ?>
                </a>
            <?php endif; ?>
            <?php if ($proposal->status !== 'converted'): ?>
                <a href="#" class="fs-btn fs-btn-danger fs-delete-btn" data-type="proposal" data-id="<?php echo  intval( $proposal->id ); ?>" data-redirect="<?php echo  esc_url( admin_url('admin.php?page=fs-proposals&message=deleted') ); ?>">
                    <?php esc_html_e('Delete', 'freelance-studio'); ?>
                </a>
            <?php endif; ?>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-proposals') ); ?>" class="fs-btn fs-btn-secondary">
                <?php esc_html_e('Back to Proposals', '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($proposal->status) ); ?>
            
            <?php if ($proposal->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($proposal->sent_at))); ?></span>
            <?php endif; ?>
            
            <?php if ($proposal->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($proposal->viewed_at))); ?></span>
            <?php endif; ?>
        </div>
        
        <?php if ($proposal->valid_until): ?>
            <div class="fs-expiry-info <?php echo FS_Proposal::is_expired($proposal) ? 'expired' : ''; ?>">
                <?php if (FS_Proposal::is_expired($proposal)): ?>
                    <?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($proposal->valid_until)) ); ?>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
    
    <?php if ($proposal->status === 'revision_requested' && !empty($proposal->revision_notes)): ?>
    <!-- Revision Request Alert -->
    <div class="fs-revision-alert">
        <div class="fs-revision-alert-header">
            <span class="dashicons dashicons-edit"></span>
            <strong><?php esc_html_e('Client Requested Changes', 'freelance-studio'); ?></strong>
            <?php if ($proposal->revision_requested_at): ?>
                <span class="fs-revision-date"><?php echo  esc_html( FS_View_Context::format_date($proposal->revision_requested_at, get_option('date_format') . ' ' . get_option('time_format')) ); ?></span>
            <?php endif; ?>
        </div>
        <div class="fs-revision-alert-body">
            <?php echo nl2br(esc_html($proposal->revision_notes)); ?>
        </div>
        <div class="fs-revision-alert-actions">
            <a href="<?php echo esc_url(admin_url('admin.php?page=fs-proposals&action=edit&id=' . $proposal->id)); ?>" class="button button-primary">
                <?php esc_html_e('Edit Proposal', 'freelance-studio'); ?>
            </a>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- Two Column Layout -->
    <div class="fs-view-two-col">
        <!-- Main Content -->
        <div class="fs-view-main">
            <!-- Proposal 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($proposal->title); ?></h1>
                    <div class="fs-doc-preview-number"><?php esc_html_e('Proposal', 'freelance-studio'); ?></div>
                    <?php echo  wp_kses_post( FS_View_Context::status_badge($proposal->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 if ($client): ?>
                                    <?php if (!empty($client->company_name)): ?>
                                        <div class="fs-doc-preview-party-name"><?php echo esc_html($client->company_name); ?></div>
                                        <p><?php echo esc_html($client->name); ?></p>
                                    <?php else: ?>
                                        <div class="fs-doc-preview-party-name"><?php echo esc_html($client->name); ?></div>
                                    <?php endif; ?>
                                    <?php if (!empty($client->email)): ?>
                                        <p><?php echo esc_html($client->email); ?></p>
                                    <?php endif; ?>
                                    <?php if (!empty($client->phone)): ?>
                                        <p><?php echo esc_html($client->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 if ($proposal->start_date || $proposal->valid_until): ?>
                    <div class="fs-doc-preview-dates">
                        <?php if ($proposal->start_date): ?>
                        <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($proposal->start_date) ); ?></span>
                        </div>
                        <?php endif; ?>
                        <?php if ($proposal->valid_until): ?>
                        <div class="fs-doc-preview-date-item <?php echo FS_Proposal::is_expired($proposal) ? 'overdue' : ''; ?>">
                            <label><?php esc_html_e('Valid Until', 'freelance-studio'); ?></label>
                            <span><?php echo  esc_html( FS_View_Context::format_date($proposal->valid_until) ); ?></span>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Custom Sections: Before Pricing -->
                    <?php if (!empty($sections_before)): ?>
                        <?php foreach ($sections_before as $section): ?>
                            <div class="fs-doc-preview-custom-section">
                                <?php if (!empty($section['title'])): ?>
                                    <h3><?php echo esc_html($section['title']); ?></h3>
                                <?php endif; ?>
                                <div class="fs-doc-custom-section-content">
                                    <?php echo wp_kses_post($section['content']); ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?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['pricing_type'] ?? $service['rate_type'] ?? 'flat';
                                        if ($rate_type === 'hourly' && !empty($service['quantity'])): ?>
                                            <div class="fs-doc-preview-item-meta">
                                                <?php echo esc_html($service['quantity']); ?> <?php esc_html_e('hours', 'freelance-studio'); ?> 
                                                × <?php echo  esc_html( FS_View_Context::format_currency($service['rate'] ?? 0) ); ?>
                                            </div>
                                        <?php elseif ($rate_type === 'fixed' || $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">
                            <?php if ($deposit_amount > 0): ?>
                            <div class="fs-doc-preview-totals-row">
                                <span class="fs-doc-preview-totals-label"><?php esc_html_e('Deposit Due', 'freelance-studio'); ?></span>
                                <span class="fs-doc-preview-totals-value"><?php echo  esc_html( FS_View_Context::format_currency($deposit_amount) ); ?></span>
                            </div>
                            <?php endif; ?>
                            <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($proposal->total_amount) ); ?></span>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Custom Sections: After Pricing -->
                    <?php if (!empty($sections_after)): ?>
                        <?php foreach ($sections_after as $section): ?>
                            <div class="fs-doc-preview-custom-section">
                                <?php if (!empty($section['title'])): ?>
                                    <h3><?php echo esc_html($section['title']); ?></h3>
                                <?php endif; ?>
                                <div class="fs-doc-custom-section-content">
                                    <?php echo wp_kses_post($section['content']); ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    
                    <!-- Notes -->
                    <?php if (!empty($proposal->notes)): ?>
                    <div class="fs-doc-preview-notes">
                        <h3><?php esc_html_e('Notes', 'freelance-studio'); ?></h3>
                        <p><?php echo nl2br(esc_html(wp_unslash($proposal->notes))); ?></p>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Signatures -->
                    <?php if ($proposal->status === 'approved' || !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 ($proposal->status === 'approved' && !empty($proposal->signature_client)): ?>
                                    <div class="fs-doc-preview-signature-image">
                                        <img src="<?php echo esc_attr($proposal->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($proposal->signature_client_name); ?></div>
                                    <div class="fs-doc-preview-signature-date"><?php echo  esc_html( FS_View_Context::format_date($proposal->signature_date) ); ?></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($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 approve.', 'freelance-studio'); ?></p>
                    <input type="text" id="fs-proposal-link" value="<?php echo esc_url(home_url('?fs_proposal=' . $proposal->view_token)); ?>" readonly class="fs-link-input">
                    <div class="fs-link-buttons">
                        <button type="button" class="button fs-copy-link-btn" data-target="fs-proposal-link">
                            <span class="dashicons dashicons-clipboard"></span> <?php esc_html_e('Copy', 'freelance-studio'); ?>
                        </button>
                        <a href="<?php echo esc_url(home_url('?fs_proposal=' . $proposal->view_token)); ?>" 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($proposal->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 ($proposal->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($proposal->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>
