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

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

$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';
$payment_instructions = get_option('fs_payment_instructions', '');
if (is_array($payment_instructions)) {
    $payment_instructions = implode("\n", array_filter($payment_instructions));
}

// Calculate invoice status
$is_paid = $invoice->status === 'paid';
$is_overdue = !$is_paid && strtotime($invoice->due_date) < time();
$is_partial = $invoice->status === 'partial';

// Get line items
$line_items = array();
if (!empty($invoice->items)) {
    if (is_string($invoice->items)) {
        $line_items = json_decode($invoice->items, true) ?: array();
    } else {
        $line_items = $invoice->items;
    }
}

// Calculate totals
$subtotal = floatval($invoice->subtotal ?? $invoice->total ?? 0);
$tax_amount = floatval($invoice->tax_amount ?? 0);
$discount_amount = floatval($invoice->discount_amount ?? 0);
$total = floatval($invoice->total ?? 0);
$paid_amount = floatval($invoice->amount_paid ?? 0);
$balance_due = $total - $paid_amount;

// Status for badge
$status_class = 'status-' . $invoice->status;
if ($is_overdue) {
    $status_class = 'status-overdue';
}
?>
<!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">
    <?php /* translators: 1. number/ID */ ?>
    <title><?php echo esc_html( sprintf( __('Invoice #%s', 'freelance-studio'), esc_html($invoice->invoice_number))); ?> - <?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>
                
                <?php if ($project): ?>
                    <h1 class="fs-doc-title"><?php echo esc_html($project->name); ?></h1>
                <?php else: ?>
                    <h1 class="fs-doc-title"><?php esc_html_e('Invoice', 'freelance-studio'); ?></h1>
                <?php endif; ?>
                
                <?php /* translators: 1. number/ID */ ?>
                <div class="fs-doc-number"><?php echo wp_kses_post( sprintf( __('Invoice #%s', 'freelance-studio'), esc_html($invoice->invoice_number))); ?></div>
                
                <?php if ($is_paid): ?>
                    <span class="fs-status-badge status-paid"><?php esc_html_e('Paid', 'freelance-studio'); ?></span>
                <?php elseif ($is_overdue): ?>
                    <span class="fs-status-badge status-overdue"><?php esc_html_e('Overdue', 'freelance-studio'); ?></span>
                <?php elseif ($is_partial): ?>
                    <span class="fs-status-badge status-partial"><?php esc_html_e('Partial', 'freelance-studio'); ?></span>
                <?php else: ?>
                    <span class="fs-status-badge <?php echo esc_attr($status_class); ?>"><?php echo esc_html(ucfirst($invoice->status)); ?></span>
                <?php endif; ?>
            </div>
            
            <!-- Body -->
            <div class="fs-doc-body">
                <!-- 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('From', 'freelance-studio'); ?></div>
                            <div class="fs-doc-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-party-card">
                            <div class="fs-doc-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-party-name"><?php echo esc_html($client->company_name); ?></div>
                                    <p><?php echo esc_html($client->name); ?></p>
                                <?php else: ?>
                                    <div class="fs-doc-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 endif; ?>
                        </div>
                    </div>
                </div>
                
                <!-- Dates -->
                <div class="fs-doc-dates">
                    <div class="fs-doc-date-item">
                        <label><?php esc_html_e('Invoice Date', 'freelance-studio'); ?></label>
                        <span><?php echo  esc_html( date_i18n(get_option('date_format'), strtotime($invoice->invoice_date)) ); ?></span>
                    </div>
                    <div class="fs-doc-date-item <?php echo $is_overdue ? 'overdue' : ''; ?>">
                        <label><?php esc_html_e('Due Date', 'freelance-studio'); ?></label>
                        <span><?php echo  esc_html( date_i18n(get_option('date_format'), strtotime($invoice->due_date)) ); ?></span>
                    </div>
                    <?php if ($is_paid && $invoice->paid_at): ?>
                    <div class="fs-doc-date-item">
                        <label><?php esc_html_e('Paid On', 'freelance-studio'); ?></label>
                        <span><?php echo  esc_html( date_i18n(get_option('date_format'), strtotime($invoice->paid_at)) ); ?></span>
                    </div>
                    <?php endif; ?>
                </div>
                
                <!-- Line Items -->
                <?php if (!empty($line_items)): ?>
                <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 ($line_items as $item): ?>
                            <tr>
                                <td>
                                    <div class="fs-doc-item-name"><?php echo esc_html($item['description'] ?? $item['name'] ?? ''); ?></div>
                                    <?php if (!empty($item['quantity']) && !empty($item['rate'])): ?>
                                        <div class="fs-doc-item-meta">
                                            <?php echo esc_html($item['quantity']); ?> × <?php echo  esc_html( FS_View_Context::format_currency($item['rate']) ); ?>
                                        </div>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo  esc_html( FS_View_Context::format_currency($item['amount'] ?? 0) ); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    
                    <!-- Totals -->
                    <div class="fs-doc-totals">
                        <div class="fs-doc-totals-row">
                            <span class="fs-doc-totals-label"><?php esc_html_e('Subtotal', 'freelance-studio'); ?></span>
                            <span class="fs-doc-totals-value"><?php echo  esc_html( FS_View_Context::format_currency($subtotal) ); ?></span>
                        </div>
                        <?php if ($discount_amount > 0): ?>
                        <div class="fs-doc-totals-row">
                            <span class="fs-doc-totals-label"><?php esc_html_e('Discount', 'freelance-studio'); ?></span>
                            <span class="fs-doc-totals-value">-<?php echo  esc_html( FS_View_Context::format_currency($discount_amount) ); ?></span>
                        </div>
                        <?php endif; ?>
                        <?php if ($tax_amount > 0): ?>
                        <div class="fs-doc-totals-row">
                            <span class="fs-doc-totals-label"><?php esc_html_e('Tax', 'freelance-studio'); ?></span>
                            <span class="fs-doc-totals-value"><?php echo  esc_html( FS_View_Context::format_currency($tax_amount) ); ?></span>
                        </div>
                        <?php endif; ?>
                        <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($total) ); ?></span>
                        </div>
                        <?php if ($paid_amount > 0 && !$is_paid): ?>
                        <div class="fs-doc-totals-row">
                            <span class="fs-doc-totals-label"><?php esc_html_e('Paid', 'freelance-studio'); ?></span>
                            <span class="fs-doc-totals-value">-<?php echo  esc_html( FS_View_Context::format_currency($paid_amount) ); ?></span>
                        </div>
                        <div class="fs-doc-totals-row grand-total" style="color: var(--danger);">
                            <span class="fs-doc-totals-label"><?php esc_html_e('Balance Due', 'freelance-studio'); ?></span>
                            <span class="fs-doc-totals-value"><?php echo  esc_html( FS_View_Context::format_currency($balance_due) ); ?></span>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Payment Instructions -->
                <?php if (!empty($payment_instructions) && !$is_paid): ?>
                <div class="fs-doc-notes">
                    <h3><?php esc_html_e('Payment Instructions', 'freelance-studio'); ?></h3>
                    <p><?php echo wp_kses_post($payment_instructions); ?></p>
                </div>
                <?php endif; ?>
                
                <!-- Notes -->
                <?php if (!empty($invoice->notes)): ?>
                <div class="fs-doc-notes">
                    <h3><?php esc_html_e('Notes', 'freelance-studio'); ?></h3>
                    <p><?php echo nl2br(esc_html($invoice->notes)); ?></p>
                </div>
                <?php endif; ?>
                
                <!-- Payment Actions -->
                <?php 
                // Check for payment URL: per-invoice link takes priority, then global setting
                $effective_payment_url = '';
                if (!empty($invoice->payment_link)) {
                    $effective_payment_url = $invoice->payment_link;
                } elseif (!empty($payment_url)) {
                    $effective_payment_url = $payment_url;
                }
                ?>
                <?php if (!$is_paid && $balance_due > 0 && !empty($effective_payment_url)): ?>
                <div class="fs-doc-actions">
                    <?php
                    // Build payment URL with smart provider detection
                    // PayPal.Me and Venmo support amount pass-through via URL
                    $pay_link = $effective_payment_url;
                    $amount_formatted = number_format($balance_due, 2, '.', '');
                    $invoice_ref = $invoice->invoice_number;
                    
                    if (strpos($pay_link, 'paypal.me/') !== false || strpos($pay_link, 'paypal.me\\') !== false) {
                        // PayPal.Me: append amount to path — paypal.me/Name/600.00
                        // Strip trailing slash if present
                        $pay_link = rtrim($pay_link, '/');
                        $pay_link = $pay_link . '/' . $amount_formatted;
                        
                    } elseif (strpos($pay_link, 'venmo.com/') !== false) {
                        // Venmo: use query params — venmo.com/Name?txn=pay&amount=600&note=Invoice+INV-001
                        $pay_link = add_query_arg(array(
                            'txn'    => 'pay',
                            'amount' => $amount_formatted,
                            'note'   => 'Invoice ' . $invoice_ref,
                        ), $pay_link);
                        
                    } else {
                        // Generic / Stripe / other providers: append reference and email params
                        $pay_params = array();
                        $pay_params['client_reference_id'] = $invoice_ref;
                        if (!empty($client->email)) {
                            $pay_params['prefilled_email'] = $client->email;
                        }
                        $pay_link = add_query_arg($pay_params, $pay_link);
                    }
                    ?>
                    <a href="<?php echo esc_url($pay_link); ?>" target="_blank" rel="noopener noreferrer" class="fs-doc-btn fs-doc-btn-primary">
                        <?php /* translators: 1. now — value */ ?>
                        <?php echo esc_html( sprintf( __( 'Pay Now — %s', 'freelance-studio'), FS_View_Context::format_currency($balance_due)) ); ?>
                    </a>
                </div>
                <?php endif; ?>
                
                <!-- Download PDF (always visible) -->
                <div class="fs-doc-actions">
                    <a href="<?php echo esc_url(add_query_arg('download', 'pdf', home_url('?fs_invoice=' . $invoice->view_token))); ?>" class="fs-doc-btn fs-doc-btn-secondary">
                        <?php esc_html_e('Download PDF', 'freelance-studio'); ?>
                    </a>
                </div>
            </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=invoice" target="_blank" rel="noopener">Powered by Freelance Studio</a>
                </div>
            <?php endif; ?>
        </footer>
    </div>
</body>
</html>
