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

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

// Handle items - might be JSON string or already an array
$items = $invoice->items;
if (is_string($items)) {
    $items = json_decode($items, true) ?: array();
} elseif (!is_array($items)) {
    $items = array();
}

$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);

// Messages
$message = isset($_GET['message']) ? sanitize_text_field($_GET['message']) : '';
$prompt_send = isset($_GET['prompt_send']) && $_GET['prompt_send'] == '1';
$prompt_receipt = isset($_GET['prompt_receipt']) && $_GET['prompt_receipt'] == '1';
$messages = array(
    'created' => __('Invoice created successfully. Ready to send to client.', 'freelance-studio'),
    'updated' => __('Invoice updated successfully.', 'freelance-studio'),
    'sent' => __('Invoice sent successfully.', 'freelance-studio'),
    'sent_no_email' => __('Invoice status updated, but email could not be sent. Please check your SMTP settings.', 'freelance-studio'),
    'paid' => __('Payment recorded successfully.', 'freelance-studio'),
    'receipt_sent' => __('Payment receipt sent successfully.', 'freelance-studio'),
);

// Check if invoice is paid
$is_paid = $invoice->status === 'paid';
$is_overdue = !$is_paid && strtotime($invoice->due_date) < time();

// Client link
$client_link = home_url('?fs_invoice=' . $invoice->view_token);
?>

<?php if (empty($GLOBALS['fs_in_finances'])): ?>
<div class="wrap fs-wrap">
<?php endif; ?>
    <?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">
        <?php /* translators: 1. invoice value */ ?>
        <h1><?php echo wp_kses_post( sprintf( __('Invoice %s', 'freelance-studio'), esc_html($invoice->invoice_number))); ?></h1>
        <div>
            <?php if (!$is_paid): ?>
                <a href="#" class="fs-btn fs-btn-primary fs-send-email-btn" data-type="invoice" data-id="<?php echo  intval( $invoice->id ); ?>" data-client-id="<?php echo  intval( $invoice->client_id ); ?>">
                    <?php echo  esc_html( $invoice->status === 'draft' ? __('Send to Client', 'freelance-studio') : __('Resend to Client', 'freelance-studio') ); ?>
                </a>
            <?php endif; ?>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=edit&id=' . $invoice->id) ); ?>" class="fs-btn fs-btn-secondary">
                <?php esc_html_e('Edit', 'freelance-studio'); ?>
            </a>
            <?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('Download PDF', 'freelance-studio'); ?>
                </span>
            <?php else: ?>
                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=pdf&id=' . $invoice->id) ); ?>" class="fs-btn fs-btn-secondary">
                    <?php esc_html_e('Download PDF', 'freelance-studio'); ?>
                </a>
            <?php endif; ?>
            <?php if (!$is_paid): ?>
                <a href="#" class="fs-btn fs-btn-danger fs-delete-btn" data-type="invoice" data-id="<?php echo  intval( $invoice->id ); ?>" data-redirect="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&message=deleted') ); ?>">
                    <?php esc_html_e('Delete', 'freelance-studio'); ?>
                </a>
            <?php endif; ?>
            <!-- Hidden trigger for payment receipt modal -->
            <a href="#" class="fs-send-email-btn" data-type="payment_receipt" data-id="<?php echo  intval( $invoice->id ); ?>" data-client-id="<?php echo  intval( $invoice->client_id ); ?>" style="display:none;" id="fs-send-receipt-trigger"></a>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices') ); ?>" class="fs-btn fs-btn-secondary">
                <?php esc_html_e('Back to Invoices', '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($invoice->status) ); ?>
            
            <?php if (!empty($invoice->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($invoice->sent_at))); ?></span>
            <?php endif; ?>
        </div>
        
        <?php if ($invoice->due_date): ?>
            <div class="fs-expiry-info <?php echo $is_overdue ? 'expired' : ''; ?>">
                <?php if ($is_overdue): ?>
                    <?php esc_html_e('Overdue', 'freelance-studio'); ?>
                <?php else: ?>
                    <?php /* translators: 1. due value */ ?>
                    <?php echo esc_html( sprintf( __( 'Due %s', 'freelance-studio'), FS_View_Context::format_date($invoice->due_date)) ); ?>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
    
    <!-- Two Column Layout -->
    <div class="fs-view-two-col">
        <!-- Main Content -->
        <div class="fs-view-main">
            <!-- Invoice 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>
                    
                    <?php if ($project): ?>
                        <h1 class="fs-doc-preview-title"><?php echo esc_html($project->name); ?></h1>
                    <?php else: ?>
                        <h1 class="fs-doc-preview-title"><?php esc_html_e('Invoice', 'freelance-studio'); ?></h1>
                    <?php endif; ?>
                    
                    <?php /* translators: 1. number/ID */ ?>
                    <div class="fs-doc-preview-number"><?php echo wp_kses_post( sprintf( __('Invoice #%s', 'freelance-studio'), esc_html($invoice->invoice_number))); ?></div>
                    
                    <?php 
                    $status_class = $invoice->status;
                    if ($is_overdue) $status_class = 'overdue';
                    echo  wp_kses_post( FS_View_Context::status_badge($status_class) );                    ?>
                </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('From', 'freelance-studio'); ?></div>
                                <div class="fs-doc-preview-party-name"><?php echo esc_html($settings['business_name']); ?></div>
                                <?php if (!empty($settings['business_address'])): ?>
                                    <p><?php echo esc_html($settings['business_address']); ?></p>
                                <?php endif; ?>
                                <?php if (!empty($settings['business_city']) || !empty($settings['business_state']) || !empty($settings['business_zip'])): ?>
                                    <p>
                                        <?php echo esc_html($settings['business_city']); ?>
                                        <?php if ($settings['business_city'] && $settings['business_state']) echo ', '; ?>
                                        <?php echo esc_html($settings['business_state']); ?>
                                        <?php echo esc_html($settings['business_zip']); ?>
                                    </p>
                                <?php endif; ?>
                                <?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('Bill To', '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->address)): ?>
                                        <p><?php echo esc_html($client->address); ?></p>
                                    <?php endif; ?>
                                    <?php if (!empty($client->city) || !empty($client->state) || !empty($client->zip)): ?>
                                        <p>
                                            <?php echo esc_html($client->city); ?>
                                            <?php if ($client->city && $client->state) echo ', '; ?>
                                            <?php echo esc_html($client->state); ?>
                                            <?php echo esc_html($client->zip); ?>
                                        </p>
                                    <?php endif; ?>
                                    <?php if (!empty($client->email)): ?>
                                        <p><?php echo esc_html($client->email); ?></p>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <p class="text-muted"><?php esc_html_e('Client not found', 'freelance-studio'); ?></p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Dates -->
                    <div class="fs-doc-preview-dates">
                        <div class="fs-doc-preview-date-item">
                            <label><?php esc_html_e('Invoice Date', 'freelance-studio'); ?></label>
                            <span><?php echo  esc_html( FS_View_Context::format_date($invoice->invoice_date) ); ?></span>
                        </div>
                        <div class="fs-doc-preview-date-item <?php echo $is_overdue ? 'overdue' : ''; ?>">
                            <label><?php esc_html_e('Due Date', 'freelance-studio'); ?></label>
                            <span><?php echo  esc_html( FS_View_Context::format_date($invoice->due_date) ); ?></span>
                        </div>
                        <?php if ($is_paid && ($invoice->paid_date || $invoice->paid_at)): ?>
                        <div class="fs-doc-preview-date-item">
                            <label><?php esc_html_e('Paid On', 'freelance-studio'); ?></label>
                            <span><?php echo  esc_html( FS_View_Context::format_date($invoice->paid_date ?: $invoice->paid_at) ); ?></span>
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Line Items -->
                    <?php if (!empty($items)): ?>
                    <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('Description', 'freelance-studio'); ?></th>
                                    <th class="text-center"><?php esc_html_e('Qty', 'freelance-studio'); ?></th>
                                    <th class="text-right"><?php esc_html_e('Rate', 'freelance-studio'); ?></th>
                                    <th><?php esc_html_e('Amount', 'freelance-studio'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($items as $item): ?>
                                <tr>
                                    <td>
                                        <div class="fs-doc-preview-item-name"><?php echo esc_html($item['description']); ?></div>
                                    </td>
                                    <td class="text-center"><?php echo esc_html($item['quantity']); ?></td>
                                    <td class="text-right"><?php echo  esc_html( FS_View_Context::format_currency($item['rate']) ); ?></td>
                                    <td><?php echo  esc_html( FS_View_Context::format_currency($item['amount']) ); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                        
                        <!-- Totals -->
                        <div class="fs-doc-preview-totals">
                            <div class="fs-doc-preview-totals-row">
                                <span class="fs-doc-preview-totals-label"><?php esc_html_e('Subtotal', 'freelance-studio'); ?></span>
                                <span class="fs-doc-preview-totals-value"><?php echo  esc_html( FS_View_Context::format_currency($invoice->subtotal) ); ?></span>
                            </div>
                            <?php if ($invoice->discount_value > 0): ?>
                            <div class="fs-doc-preview-totals-row">
                                <span class="fs-doc-preview-totals-label"><?php esc_html_e('Discount', 'freelance-studio'); ?></span>
                                <span class="fs-doc-preview-totals-value">-<?php echo  esc_html( FS_View_Context::format_currency($invoice->discount_amount) ); ?></span>
                            </div>
                            <?php endif; ?>
                            <?php if ($invoice->tax_rate > 0): ?>
                            <div class="fs-doc-preview-totals-row">
                                <?php /* translators: 1. tax value */ ?>
                                <span class="fs-doc-preview-totals-label"><?php echo wp_kses_post( sprintf( __('Tax (%s%%)', 'freelance-studio'), $invoice->tax_rate)); ?></span>
                                <span class="fs-doc-preview-totals-value"><?php echo  esc_html( FS_View_Context::format_currency($invoice->tax_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($invoice->total) ); ?></span>
                            </div>
                            <?php if ($invoice->amount_paid > 0): ?>
                            <div class="fs-doc-preview-totals-row">
                                <span class="fs-doc-preview-totals-label"><?php esc_html_e('Paid', 'freelance-studio'); ?></span>
                                <span class="fs-doc-preview-totals-value fs-text-success">-<?php echo  esc_html( FS_View_Context::format_currency($invoice->amount_paid) ); ?></span>
                            </div>
                            <div class="fs-doc-preview-totals-row grand-total<?php echo $invoice->balance_due > 0 ? ' fs-text-danger' : ''; ?>">
                                <span class="fs-doc-preview-totals-label"><?php esc_html_e('Balance Due', 'freelance-studio'); ?></span>
                                <span class="fs-doc-preview-totals-value"><?php echo  esc_html( FS_View_Context::format_currency($invoice->balance_due) ); ?></span>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Notes -->
                    <?php if (!empty($invoice->notes)): ?>
                    <div class="fs-doc-preview-notes">
                        <h3><?php esc_html_e('Notes', 'freelance-studio'); ?></h3>
                        <p><?php echo nl2br(esc_html($invoice->notes)); ?></p>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Payment Instructions -->
                    <?php if (!empty($settings['payment_instructions'])): ?>
                    <div class="fs-doc-preview-notes">
                        <h3><?php esc_html_e('Payment Instructions', 'freelance-studio'); ?></h3>
                        <p><?php echo wp_kses_post($settings['payment_instructions']); ?></p>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Pay Now Button Status -->
                    <?php 
                    $global_payment_url = get_option('fs_payment_url', '');
                    $invoice_payment_link = $invoice->payment_link ?? '';
                    $has_payment_link = !empty($invoice_payment_link) || !empty($global_payment_url);
                    ?>
                    <?php if ($invoice->status !== 'paid'): ?>
                    <div class="fs-doc-preview-notes" style="margin-top: 12px;">
                        <?php if ($has_payment_link): ?>
                            <p style="color: var(--fs-primary-dark, #2BA891); font-size: 13px;">
                                <span class="dashicons dashicons-yes-alt" style="font-size: 16px; vertical-align: text-bottom;"></span>
                                <?php 
                                $link_source = !empty($invoice_payment_link) ? $invoice_payment_link : $global_payment_url;
                                /* translators: 1. date/time */
                                echo wp_kses_post( sprintf( __('Pay Now button will show on the client view, linking to: %s', 'freelance-studio'), '<code style="font-size: 12px;">' . esc_html($link_source) . '</code>') ); 
                                ?>
                            </p>
                        <?php else: ?>
                            <p style="color: var(--fs-gray-500, #9CA3AF); font-size: 13px;">
                                <span class="dashicons dashicons-info-outline" style="font-size: 16px; vertical-align: text-bottom;"></span>
                                <?php printf( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                    /* translators: placeholder(s) in this string */
                                    __('No payment link configured. Add one on this invoice\'s %1$sedit page%2$s or set a global default in %3$sSettings → Invoices%4$s to show a "Pay Now" button.', 'freelance-studio'), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                    '<a href="' . admin_url('admin.php?page=fs-finances&tab=invoices&action=edit&id=' . $invoice->id) . '">', // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                    '</a>',
                                    '<a href="' . admin_url('admin.php?page=fs-settings&tab=invoices') . '">', // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                    '</a>'
                                ); ?>
                            </p>
                        <?php endif; ?>
                    </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 fs-text-share-hint"><?php esc_html_e('Share this link with your client to view and pay.', 'freelance-studio'); ?></p>
                    <input type="text" id="fs-invoice-link" value="<?php echo esc_url($client_link); ?>" readonly class="fs-link-input">
                    <div class="fs-link-buttons">
                        <button type="button" class="button fs-copy-link-btn" data-target="fs-invoice-link">
                            <span class="dashicons dashicons-clipboard"></span> <?php esc_html_e('Copy', 'freelance-studio'); ?>
                        </button>
                        <a href="<?php echo esc_url($client_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($invoice->total) ); ?></span>
                    </div>
                    <?php if ($invoice->amount_paid > 0): ?>
                    <div class="fs-summary-row">
                        <span class="fs-summary-label"><?php esc_html_e('Paid', 'freelance-studio'); ?></span>
                        <span class="fs-summary-value fs-text-success"><?php echo  esc_html( FS_View_Context::format_currency($invoice->amount_paid) ); ?></span>
                    </div>
                    <div class="fs-summary-row">
                        <span class="fs-summary-label"><?php esc_html_e('Balance', 'freelance-studio'); ?></span>
                        <span class="fs-summary-value<?php echo  esc_attr( $invoice->balance_due > 0 ? ' fs-text-danger' : '' ); ?>"><?php echo  esc_html( FS_View_Context::format_currency($invoice->balance_due) ); ?></span>
                    </div>
                    <?php endif; ?>
                    <div class="fs-summary-row">
                        <span class="fs-summary-label"><?php esc_html_e('Due Date', 'freelance-studio'); ?></span>
                        <span class="fs-summary-value"><?php echo  esc_html( FS_View_Context::format_date($invoice->due_date) ); ?></span>
                    </div>
                </div>
            </div>
            
            <!-- Record Payment Card (if not paid) -->
            <?php if (!$is_paid): ?>
            <div class="fs-project-card">
                <div class="fs-card-header">
                    <h3 class="fs-card-title"><?php esc_html_e('Record Payment', 'freelance-studio'); ?></h3>
                </div>
                <div class="fs-card-body">
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=record_payment&id=' . $invoice->id) ); ?>" class="fs-btn fs-btn-primary" style="display:block;text-align:center;">
                        <?php esc_html_e('Record Payment', 'freelance-studio'); ?>
                    </a>
                </div>
            </div>
            <?php endif; ?>
            
            <!-- Payment Reminders Card (if not paid and not draft) -->
            <?php if (!$is_paid && $invoice->status !== 'draft'): 
                $reminders = FS_Payment_Reminder::get_by_invoice($invoice->id);
                $reminder_history = FS_Payment_Reminder::get_history($invoice->id);
            ?>
            <div class="fs-project-card">
                <div class="fs-card-header">
                    <h3 class="fs-card-title"><?php esc_html_e('Payment Reminders', 'freelance-studio'); ?></h3>
                </div>
                <div class="fs-card-body">
                    <div class="fs-flex-row-gap">
                        <button type="button" class="button fs-send-reminder-btn" data-invoice-id="<?php echo  intval( $invoice->id ); ?>">
                            <span class="dashicons dashicons-email"></span> <?php esc_html_e('Send Now', 'freelance-studio'); ?>
                        </button>
                        <?php if (empty($reminders)): ?>
                            <button type="button" class="button fs-schedule-reminders-btn" data-invoice-id="<?php echo  intval( $invoice->id ); ?>">
                                <span class="dashicons dashicons-calendar-alt"></span> <?php esc_html_e('Schedule', 'freelance-studio'); ?>
                            </button>
                        <?php endif; ?>
                    </div>
                    
                    <?php if (!empty($reminders)): ?>
                        <div class="fs-text-muted-sm">
                            <strong><?php esc_html_e('Scheduled:', 'freelance-studio'); ?></strong>
                            <?php 
                            $types = FS_Payment_Reminder::get_types();
                            $pending = array_filter($reminders, function($r) { return $r->status !== 'sent'; });
                            echo  esc_html( count($pending) . ' ' . _n('reminder', 'reminders', count($pending), 'freelance-studio') );                            ?>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (!empty($reminder_history)): ?>
                        <div class="fs-text-muted-xs">
                            <?php /* translators: 1. last sent value */ ?>
                            <?php echo esc_html( sprintf( __( 'Last sent: %s', 'freelance-studio'), FS_View_Context::format_date($reminder_history[0]->sent_at)) ); ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
        </div><!-- End fs-view-sidebar -->
    </div><!-- End fs-view-two-col -->
<?php if (empty($GLOBALS['fs_in_finances'])): ?>
</div>
<?php endif; ?>

<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'); ?>');
        }
    });
    
    // Send reminder button
    $('.fs-send-reminder-btn').on('click', function() {
        var $btn = $(this);
        var invoiceId = $btn.data('invoice-id');
        
        $btn.prop('disabled', true).text('<?php esc_html_e('Sending...', 'freelance-studio'); ?>');
        
        $.post(ajaxurl, {
            action: 'fs_send_payment_reminder',
            invoice_id: invoiceId,
            nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>'
        }, function(response) {
            if (response.success) {
                alert(response.data.message);
                location.reload();
            } else {
                alert(response.data || '<?php esc_html_e('Failed to send reminder', 'freelance-studio'); ?>');
                $btn.prop('disabled', false).html('<span class="dashicons dashicons-email"></span> <?php esc_html_e('Send Reminder Now', 'freelance-studio'); ?>');
            }
        });
    });
    
    // Schedule reminders button
    $('.fs-schedule-reminders-btn').on('click', function() {
        var $btn = $(this);
        var invoiceId = $btn.data('invoice-id');
        
        $btn.prop('disabled', true).text('<?php esc_html_e('Scheduling...', 'freelance-studio'); ?>');
        
        $.post(ajaxurl, {
            action: 'fs_schedule_reminders',
            invoice_id: invoiceId,
            nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>'
        }, function(response) {
            if (response.success) {
                alert(response.data.message);
                location.reload();
            } else {
                alert(response.data || '<?php esc_html_e('Failed to schedule reminders', 'freelance-studio'); ?>');
                $btn.prop('disabled', false).html('<span class="dashicons dashicons-calendar-alt"></span> <?php esc_html_e('Schedule Reminders', 'freelance-studio'); ?>');
            }
        });
    });
    
    <?php if ($prompt_send && $invoice->status === 'draft'): ?>
    // Auto-trigger send modal after invoice creation
    setTimeout(function() {
        $('.fs-send-email-btn[data-type="invoice"]').first().trigger('click');
    }, 500);
    <?php endif; ?>
    
    <?php if ($prompt_receipt): ?>
    // Auto-trigger send receipt modal after payment recorded
    setTimeout(function() {
        $('#fs-send-receipt-trigger').trigger('click');
    }, 500);
    <?php endif; ?>
});
</script>
