<?php
/**
 * Public Contract View
 *
 * @package Freelance_Studio
 */

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

// Handle services
$services = array();
if (!empty($contract->services)) {
    if (is_string($contract->services)) {
        $services = json_decode($contract->services, true) ?: array();
    } elseif (is_array($contract->services)) {
        $services = $contract->services;
    }
}

$primary_color = !empty($settings['invoice_primary_color']) ? $settings['invoice_primary_color'] : '#2271b1';
$primary_color_mode = !empty($settings['invoice_primary_color_mode']) ? $settings['invoice_primary_color_mode'] : 'solid';
$primary_color_2 = !empty($settings['invoice_primary_color_2']) ? $settings['invoice_primary_color_2'] : $primary_color;
$gradient_direction = !empty($settings['invoice_gradient_direction']) ? $settings['invoice_gradient_direction'] : '135';
$just_signed = isset($_GET['signed']) && $_GET['signed'] === '1';
$is_expired = !empty($contract->valid_until) && strtotime($contract->valid_until) < time();

// Get enabled sections
$enabled_sections = array();
if (class_exists('FS_Contract')) {
    $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 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'] : '';

// Can sign?
$can_sign = !in_array($contract->status, array('signed', 'completed', 'declined', 'cancelled')) && !$is_expired;

// E-signatures require Pro plan - disable signing on free plan
if ( function_exists( 'fs_studio_is_free_plan' ) && fs_studio_is_free_plan() ) {
    $can_sign = false;
}

// Contract number
$contract_number = 'CON-' . gmdate('Y', strtotime($contract->created_at)) . '-' . str_pad($contract->id, 3, '0', STR_PAD_LEFT);

// Status for badge
$status_class = 'status-' . $contract->status;
if ($is_expired && $contract->status !== 'approved') {
    $status_class = 'status-expired';
}
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo('charset'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="robots" content="noindex, nofollow">
    <title><?php echo esc_html($contract->title); ?> - <?php echo esc_html($settings['business_name']); ?></title>
    <?php include dirname(__FILE__) . '/document-styles.php'; ?>
</head>
<body>
    <div class="fs-doc-container">
        <?php if (!empty($portal_url)): ?>
        <a href="<?php echo esc_url($portal_url); ?>" class="fs-doc-back-link">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polyline points="15 18 9 12 15 6"/>
            </svg>
            <?php esc_html_e('Back to Dashboard', 'freelance-studio'); ?>
        </a>
        <?php endif; ?>
        
        <div class="fs-doc-card">
            <!-- Header -->
            <div class="fs-doc-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-logo">
                <?php endif; ?>
                <div class="fs-doc-business-name"><?php echo esc_html($settings['business_name']); ?></div>
                <h1 class="fs-doc-title"><?php echo esc_html($contract->title); ?></h1>
                <?php /* translators: 1. number/ID */ ?>
                <div class="fs-doc-number"><?php echo wp_kses_post( sprintf( __('Contract #%s', 'freelance-studio'), esc_html($contract_number))); ?></div>
                
                <?php if ($contract->status === 'approved'): ?>
                    <span class="fs-status-badge status-approved"><?php esc_html_e('Signed', 'freelance-studio'); ?></span>
                <?php elseif ($is_expired): ?>
                    <span class="fs-status-badge status-expired"><?php esc_html_e('Expired', 'freelance-studio'); ?></span>
                <?php elseif ($just_signed): ?>
                    <span class="fs-status-badge status-approved"><?php esc_html_e('Signed', 'freelance-studio'); ?></span>
                <?php else: ?>
                    <span class="fs-status-badge <?php echo esc_attr($status_class); ?>"><?php echo esc_html(ucfirst($contract->status)); ?></span>
                <?php endif; ?>
            </div>
            
            <!-- Body -->
            <div class="fs-doc-body">
                <!-- Success message -->
                <?php if ($just_signed): ?>
                    <div class="fs-doc-notes" style="background: #d1fae5; margin-bottom: 24px;">
                        <p style="color: #065f46; text-align: center; margin: 0;">✓ <?php esc_html_e('Thank you! Your signature has been recorded.', 'freelance-studio'); ?></p>
                    </div>
                <?php endif; ?>
                
                <!-- Parties -->
                <div class="fs-doc-parties">
                    <h2 class="fs-doc-section-title"><?php esc_html_e('Parties', 'freelance-studio'); ?></h2>
                    <div class="fs-doc-parties-grid">
                        <div class="fs-doc-party-card">
                            <div class="fs-doc-party-label contractor"><?php esc_html_e('Contractor', 'freelance-studio'); ?></div>
                            <div class="fs-doc-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-party-card">
                            <div class="fs-doc-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-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-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 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-dates">
                    <?php if ($has_start): ?>
                    <div class="fs-doc-date-item">
                        <label><?php esc_html_e('Start Date', 'freelance-studio'); ?></label>
                        <span><?php echo  esc_html( date_i18n(get_option('date_format'), strtotime($contract->start_date)) ); ?></span>
                    </div>
                    <?php endif; ?>
                    <?php if ($has_end): ?>
                    <div class="fs-doc-date-item">
                        <label><?php esc_html_e('End Date', 'freelance-studio'); ?></label>
                        <span><?php echo  esc_html( date_i18n(get_option('date_format'), strtotime($contract->end_date)) ); ?></span>
                    </div>
                    <?php elseif ($has_valid): ?>
                    <div class="fs-doc-date-item <?php echo $is_expired ? 'overdue' : ''; ?>">
                        <label><?php esc_html_e('Valid Until', 'freelance-studio'); ?></label>
                        <span><?php echo  esc_html( date_i18n(get_option('date_format'), strtotime($contract->valid_until)) ); ?></span>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
                
                <!-- Project Description -->
                <?php if (!empty($contract->description)): ?>
                <div class="fs-doc-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-section">
                    <h2 class="fs-doc-section-title"><?php esc_html_e('Services', 'freelance-studio'); ?></h2>
                    <table class="fs-doc-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-item-name"><?php echo esc_html($service['name']); ?></div>
                                    <?php if (!empty($service['description'])): ?>
                                        <div class="fs-doc-item-description"><?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-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 === 'quantity' && !empty($service['quantity'])): ?>
                                        <div class="fs-doc-item-meta">
                                            <?php echo esc_html($service['quantity']); ?> <?php esc_html_e('items', 'freelance-studio'); ?> 
                                            × <?php echo  esc_html( FS_View_Context::format_currency($service['rate'] ?? 0) ); ?>
                                        </div>
                                    <?php elseif ($rate_type === 'flat'): ?>
                                        <div class="fs-doc-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-totals">
                        <div class="fs-doc-totals-row grand-total">
                            <span class="fs-doc-totals-label"><?php esc_html_e('Total', 'freelance-studio'); ?></span>
                            <span class="fs-doc-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-terms">
                    <h2 class="fs-doc-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-term-section">
                            <h3 class="fs-doc-term-title"><?php echo esc_html($section['title']); ?></h3>
                            <div class="fs-doc-term-content">
                                <?php echo wp_kses_post(wpautop($content)); ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
                
                <!-- Client-Facing Notes -->
                <?php if (!empty($contract->notes)): ?>
                <div class="fs-doc-section" style="margin-top: 24px;">
                    <h2 class="fs-doc-section-title"><?php esc_html_e('Notes', 'freelance-studio'); ?></h2>
                    <div class="fs-doc-content">
                        <?php echo wp_kses_post(wpautop($contract->notes)); ?>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Signatures Section -->
                <?php if (in_array($contract->status, array('signed', 'completed')) || !empty($contractor_signature)): ?>
                <div class="fs-doc-signatures">
                    <div class="fs-doc-signatures-grid">
                        <div class="fs-doc-signature-block">
                            <div class="fs-doc-signature-label"><?php esc_html_e('Contractor', 'freelance-studio'); ?></div>
                            <?php if (!empty($contractor_signature)): ?>
                                <div class="fs-doc-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-signature-pending"><?php esc_html_e('Pending', 'freelance-studio'); ?></div>
                            <?php endif; ?>
                            <div class="fs-doc-signature-line"></div>
                            <div class="fs-doc-signature-name"><?php echo esc_html($contractor_signer_name); ?></div>
                            <?php if (!empty($contractor_signer_title)): ?>
                                <div class="fs-doc-signature-title"><?php echo esc_html($contractor_signer_title); ?></div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="fs-doc-signature-block">
                            <div class="fs-doc-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-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-signature-line"></div>
                                <div class="fs-doc-signature-name"><?php echo esc_html($contract->signature_client_name); ?></div>
                                <div class="fs-doc-signature-date"><?php echo  esc_html( date_i18n(get_option('date_format'), strtotime($contract->signature_client_date)) ); ?></div>
                            <?php else: ?>
                                <div class="fs-doc-signature-pending"><?php esc_html_e('Awaiting signature', 'freelance-studio'); ?></div>
                                <div class="fs-doc-signature-line"></div>
                                <div class="fs-doc-signature-name"><?php echo esc_html($client->name); ?></div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Sign Form -->
                <?php if ($can_sign): ?>
                <div class="fs-doc-sign-section">
                    <h3 class="fs-doc-sign-title"><?php esc_html_e('Sign This Contract', 'freelance-studio'); ?></h3>
                    
                    <form id="fs-signature-form" method="post">
                        <?php wp_nonce_field('fs_sign_contract', 'fs_sign_nonce'); ?>
                        <input type="hidden" name="action" value="fs_sign_contract">
                        <input type="hidden" name="contract_id" value="<?php echo esc_attr($contract->id); ?>">
                        <input type="hidden" name="signature_data" id="signature-data" value="">
                        
                        <div class="fs-doc-form-group">
                            <label><?php esc_html_e('Your Signature', 'freelance-studio'); ?></label>
                            <div class="fs-doc-signature-pad-container" id="signature-pad-container">
                                <canvas id="signature-pad" class="fs-doc-signature-pad"></canvas>
                                <div class="fs-doc-signature-hint"><?php esc_html_e('Sign here', 'freelance-studio'); ?></div>
                                <button type="button" class="fs-doc-clear-signature" id="clear-signature"><?php esc_html_e('Clear', 'freelance-studio'); ?></button>
                            </div>
                        </div>
                        
                        <div class="fs-doc-form-group">
                            <label for="signer-name"><?php esc_html_e('Your Full Name', 'freelance-studio'); ?></label>
                            <input type="text" id="signer-name" name="signer_name" required value="<?php echo esc_attr($display_contact->name ?: ($client ? $client->name : '')); ?>">
                        </div>
                        
                        <button type="submit" class="fs-doc-sign-btn" id="submit-signature" disabled>
                            <?php esc_html_e('Sign Contract', 'freelance-studio'); ?>
                        </button>
                    </form>
                </div>
                <?php elseif ($is_expired && $contract->status !== 'approved'): ?>
                <div class="fs-doc-notes">
                    <p style="text-align: center;"><?php esc_html_e('This contract has expired. Please contact us for a new contract.', 'freelance-studio'); ?></p>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <footer class="fs-doc-footer">
            <?php /* translators: 1. sent by value */ ?>
            <p><?php echo wp_kses_post( sprintf( __('Sent by %s', 'freelance-studio'), esc_html($settings['business_name']))); ?></p>
            <?php if ( function_exists( 'fs_studio_show_powered_badge' ) && fs_studio_show_powered_badge() ): ?>
                <div class="fs-powered-badge">
                    <a href="https://freelancestud.io?ref=contract" target="_blank" rel="noopener">Powered by Freelance Studio</a>
                </div>
            <?php endif; ?>
        </footer>
    </div>
    
    <?php if ($can_sign): ?>
    <script>
    (function() {
        var canvas = document.getElementById('signature-pad');
        var container = document.getElementById('signature-pad-container');
        var clearBtn = document.getElementById('clear-signature');
        var form = document.getElementById('fs-signature-form');
        var submitBtn = document.getElementById('submit-signature');
        var signatureData = document.getElementById('signature-data');
        
        var ctx = canvas.getContext('2d');
        var isDrawing = false;
        var lastX = 0;
        var lastY = 0;
        var hasSignature = false;
        
        function resizeCanvas() {
            var rect = canvas.getBoundingClientRect();
            canvas.width = rect.width;
            canvas.height = rect.height;
            ctx.strokeStyle = '#000';
            ctx.lineWidth = 2;
            ctx.lineCap = 'round';
            ctx.lineJoin = 'round';
        }
        
        resizeCanvas();
        window.addEventListener('resize', resizeCanvas);
        
        function getCoords(e) {
            var rect = canvas.getBoundingClientRect();
            if (e.touches) {
                return { x: e.touches[0].clientX - rect.left, y: e.touches[0].clientY - rect.top };
            }
            return { x: e.clientX - rect.left, y: e.clientY - rect.top };
        }
        
        function startDrawing(e) {
            e.preventDefault();
            isDrawing = true;
            var coords = getCoords(e);
            lastX = coords.x;
            lastY = coords.y;
        }
        
        function draw(e) {
            if (!isDrawing) return;
            e.preventDefault();
            var coords = getCoords(e);
            ctx.beginPath();
            ctx.moveTo(lastX, lastY);
            ctx.lineTo(coords.x, coords.y);
            ctx.stroke();
            lastX = coords.x;
            lastY = coords.y;
            hasSignature = true;
            container.classList.add('has-signature');
            submitBtn.disabled = false;
        }
        
        function stopDrawing() {
            isDrawing = false;
        }
        
        canvas.addEventListener('mousedown', startDrawing);
        canvas.addEventListener('mousemove', draw);
        canvas.addEventListener('mouseup', stopDrawing);
        canvas.addEventListener('mouseout', stopDrawing);
        canvas.addEventListener('touchstart', startDrawing);
        canvas.addEventListener('touchmove', draw);
        canvas.addEventListener('touchend', stopDrawing);
        
        clearBtn.addEventListener('click', function() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            hasSignature = false;
            container.classList.remove('has-signature');
            submitBtn.disabled = true;
        });
        
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            if (!hasSignature) {
                alert('<?php esc_html_e('Please sign the contract first.', 'freelance-studio'); ?>');
                return;
            }
            signatureData.value = canvas.toDataURL('image/png');
            submitBtn.disabled = true;
            submitBtn.textContent = '<?php esc_html_e('Processing...', 'freelance-studio'); ?>';
            
            var formData = new FormData(form);
            fetch('<?php echo  esc_url( admin_url('admin-ajax.php') ); ?>', {
                method: 'POST',
                body: formData
            })
            .then(function(response) { return response.json(); })
            .then(function(data) {
                if (data.success) {
                    window.location.href = window.location.pathname + window.location.search + (window.location.search ? '&' : '?') + 'signed=1';
                } else {
                    var errorMsg = (data.data && data.data.message) ? data.data.message : '<?php esc_html_e('An error occurred. Please try again.', 'freelance-studio'); ?>';
                    alert(errorMsg);
                    submitBtn.disabled = false;
                    submitBtn.textContent = '<?php esc_html_e('Sign Contract', 'freelance-studio'); ?>';
                }
            })
            .catch(function() {
                alert('<?php esc_html_e('An error occurred. Please try again.', 'freelance-studio'); ?>');
                submitBtn.disabled = false;
                submitBtn.textContent = '<?php esc_html_e('Sign Contract', 'freelance-studio'); ?>';
            });
        });
    })();
    </script>
    <?php endif; ?>
</body>
</html>
