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

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

$show_success = isset($_GET['message']) && $_GET['message'] === 'saved';
$show_error = isset($_GET['error']) && $_GET['error'] === 'generate_failed';

// Status class mapping
$status_classes = array(
    'active' => 'status-active',
    'paused' => 'status-pending',
    'completed' => 'status-completed',
    'cancelled' => 'status-cancelled',
);
$status_class = $status_classes[$recurring->status] ?? 'status-draft';

// Calculate next invoice info
$next_date = $recurring->next_invoice_date ? strtotime($recurring->next_invoice_date) : null;
$is_due = $next_date && $next_date <= strtotime('today');
?>

<?php if (empty($GLOBALS['fs_in_finances'])): ?>
<div class="wrap fs-wrap">
<?php endif; ?>
    <div class="fs-breadcrumb">
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=recurring') ); ?>"><?php esc_html_e('Recurring Invoices', 'freelance-studio'); ?></a>
        <span>/</span>
        <span><?php echo esc_html($recurring->name); ?></span>
    </div>

    <?php if ($show_success): ?>
        <div class="notice notice-success is-dismissible">
            <p><?php esc_html_e('Recurring invoice saved successfully.', 'freelance-studio'); ?></p>
        </div>
    <?php endif; ?>

    <?php if ($show_error): ?>
        <div class="notice notice-error is-dismissible">
            <p><?php esc_html_e('Failed to generate invoice. The recurring invoice may be paused or completed.', 'freelance-studio'); ?></p>
        </div>
    <?php endif; ?>

    <!-- Header -->
    <div class="fs-list-header">
        <div class="fs-header-title-group">
            <h1><?php echo esc_html($recurring->name); ?></h1>
            <span class="fs-status-badge <?php echo  esc_attr( $status_class ); ?>"><?php echo esc_html($statuses[$recurring->status] ?? $recurring->status); ?></span>
        </div>
        <div class="fs-header-actions">
            <?php if ($recurring->status === 'active'): ?>
                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=recurring&action=generate&id=' . $recurring->id) ); ?>" class="fs-btn fs-btn-primary" onclick="return confirm('<?php esc_html_e('Generate an invoice now?', 'freelance-studio'); ?>');">
                    <?php esc_html_e('Generate Invoice Now', 'freelance-studio'); ?>
                </a>
            <?php endif; ?>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=recurring&action=edit&id=' . $recurring->id) ); ?>" class="fs-btn fs-btn-secondary">
                <?php esc_html_e('Edit', 'freelance-studio'); ?>
            </a>
            <span class="fs-header-client">
                <span class="dashicons dashicons-building"></span>
                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-clients&action=view&id=' . $recurring->client_id) ); ?>">
                    <?php echo esc_html($recurring->company_name ?: $recurring->client_name); ?>
                </a>
                <?php if ($recurring->project_name): ?>
                    <span class="fs-header-project-link">
                        / <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=view&id=' . $recurring->project_id) ); ?>"><?php echo esc_html($recurring->project_name); ?></a>
                    </span>
                <?php endif; ?>
            </span>
        </div>
    </div>

    <!-- Schedule Stats Row -->
    <div class="fs-stats-grid fs-recurring-stats">
        <div class="fs-stat-card <?php echo $is_due && $recurring->status === 'active' ? 'warning' : ''; ?>">
            <div class="fs-stat-icon">
                <span class="dashicons dashicons-calendar-alt"></span>
            </div>
            <div class="fs-stat-content">
                <span class="fs-stat-label"><?php esc_html_e('Next Invoice', 'freelance-studio'); ?></span>
                <span class="fs-stat-value <?php echo $is_due ? 'warning' : ''; ?>">
                    <?php if ($next_date): ?>
                        <?php echo esc_html(gmdate('M j, Y', $next_date)); ?>
                        <?php if ($is_due && $recurring->status === 'active'): ?>
                            <small class="fs-due-badge"><?php esc_html_e('Due!', 'freelance-studio'); ?></small>
                        <?php endif; ?>
                    <?php else: ?>
                        <span class="fs-muted">—</span>
                    <?php endif; ?>
                </span>
            </div>
        </div>
        
        <div class="fs-stat-card">
            <div class="fs-stat-icon">
                <span class="dashicons dashicons-update"></span>
            </div>
            <div class="fs-stat-content">
                <span class="fs-stat-label"><?php esc_html_e('Frequency', 'freelance-studio'); ?></span>
                <span class="fs-stat-value"><?php echo esc_html($frequencies[$recurring->frequency] ?? $recurring->frequency); ?></span>
            </div>
        </div>
        
        <div class="fs-stat-card">
            <div class="fs-stat-icon">
                <span class="dashicons dashicons-money-alt"></span>
            </div>
            <div class="fs-stat-content">
                <span class="fs-stat-label"><?php esc_html_e('Amount Per Invoice', 'freelance-studio'); ?></span>
                <span class="fs-stat-value"><?php echo  esc_html( FS_View_Context::format_currency($recurring->amount) ); ?></span>
            </div>
        </div>
        
        <div class="fs-stat-card">
            <div class="fs-stat-icon">
                <span class="dashicons dashicons-media-text"></span>
            </div>
            <div class="fs-stat-content">
                <span class="fs-stat-label"><?php esc_html_e('Invoices Generated', 'freelance-studio'); ?></span>
                <span class="fs-stat-value"><?php echo intval($recurring->invoices_generated); ?></span>
            </div>
        </div>
    </div>

    <!-- Main Content Area -->
    <div class="fs-recurring-content">
        <!-- Schedule Details Card -->
        <div class="fs-card">
            <div class="fs-card-header">
                <h2><?php esc_html_e('Schedule Details', 'freelance-studio'); ?></h2>
            </div>
            <div class="fs-card-body">
                <div class="fs-detail-list">
                    <div class="fs-detail-row">
                        <span class="fs-detail-label"><?php esc_html_e('Last Invoice Date', 'freelance-studio'); ?></span>
                        <span class="fs-detail-value">
                            <?php if ($recurring->last_invoice_date): ?>
                                <?php echo esc_html(gmdate('F j, Y', strtotime($recurring->last_invoice_date))); ?>
                            <?php else: ?>
                                <span class="fs-muted"><?php esc_html_e('Never', 'freelance-studio'); ?></span>
                            <?php endif; ?>
                        </span>
                    </div>
                    <div class="fs-detail-row">
                        <span class="fs-detail-label"><?php esc_html_e('End Date', 'freelance-studio'); ?></span>
                        <span class="fs-detail-value">
                            <?php if ($recurring->end_date): ?>
                                <?php echo esc_html(gmdate('F j, Y', strtotime($recurring->end_date))); ?>
                            <?php else: ?>
                                <span class="fs-muted"><?php esc_html_e('No end date', 'freelance-studio'); ?></span>
                            <?php endif; ?>
                        </span>
                    </div>
                    <div class="fs-detail-row">
                        <span class="fs-detail-label"><?php esc_html_e('Auto-Send', 'freelance-studio'); ?></span>
                        <span class="fs-detail-value">
                            <?php if ($recurring->auto_send): ?>
                                <span class="fs-status-badge status-completed"><?php esc_html_e('Enabled', 'freelance-studio'); ?></span>
                            <?php else: ?>
                                <span class="fs-status-badge status-draft"><?php esc_html_e('Disabled', 'freelance-studio'); ?></span>
                            <?php endif; ?>
                        </span>
                    </div>
                    <div class="fs-detail-row">
                        <span class="fs-detail-label"><?php esc_html_e('Include Time Entries', 'freelance-studio'); ?></span>
                        <span class="fs-detail-value">
                            <?php if (!empty($recurring->include_time_entries)): ?>
                                <span class="fs-status-badge status-completed"><?php esc_html_e('Enabled', 'freelance-studio'); ?></span>
                                <small><?php 
                                    $grouping_labels = array('task' => __('Grouped by task', 'freelance-studio'), 'activity' => __('Grouped by activity', 'freelance-studio'), 'entry' => __('Individual entries', 'freelance-studio'));
                                    echo esc_html($grouping_labels[$recurring->time_grouping ?? 'task'] ?? '');
                                ?></small>
                            <?php else: ?>
                                <span class="fs-status-badge status-draft"><?php esc_html_e('Disabled', 'freelance-studio'); ?></span>
                            <?php endif; ?>
                        </span>
                    </div>
                    <div class="fs-detail-row">
                        <span class="fs-detail-label"><?php esc_html_e('Total Billed', 'freelance-studio'); ?></span>
                        <span class="fs-detail-value fs-text-primary fs-text-large">
                            <?php echo  esc_html( FS_View_Context::format_currency($recurring->amount * $recurring->invoices_generated) ); ?>
                        </span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Invoice Items -->
        <div class="fs-card">
            <div class="fs-card-header">
                <h2><?php esc_html_e('Invoice Items', 'freelance-studio'); ?></h2>
            </div>
            <div class="fs-card-body">
                <?php if (!empty($items)): ?>
                    <table class="fs-table">
                        <thead>
                            <tr>
                                <th><?php esc_html_e('Description', 'freelance-studio'); ?></th>
                                <th class="fs-table-number"><?php esc_html_e('Qty', 'freelance-studio'); ?></th>
                                <th class="fs-table-number"><?php esc_html_e('Rate', 'freelance-studio'); ?></th>
                                <th class="fs-table-number"><?php esc_html_e('Amount', 'freelance-studio'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($items as $item): ?>
                                <tr>
                                    <td><?php echo esc_html($item['description']); ?></td>
                                    <td class="fs-table-number"><?php echo esc_html($item['quantity']); ?></td>
                                    <td class="fs-table-number"><?php echo  esc_html( FS_View_Context::format_currency($item['rate']) ); ?></td>
                                    <td class="fs-table-number"><?php echo  esc_html( FS_View_Context::format_currency($item['amount']) ); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="3" class="fs-table-total-label"><?php esc_html_e('Total', 'freelance-studio'); ?></td>
                                <td class="fs-table-number fs-table-total"><?php echo  esc_html( FS_View_Context::format_currency($recurring->amount) ); ?></td>
                            </tr>
                        </tfoot>
                    </table>
                <?php else: ?>
                    <p class="fs-muted"><?php esc_html_e('No items added yet.', 'freelance-studio'); ?></p>
                <?php endif; ?>
            </div>
        </div>

        <!-- Generated Invoices -->
        <div class="fs-card">
            <div class="fs-card-header">
                <h2><?php esc_html_e('Generated Invoices', 'freelance-studio'); ?></h2>
            </div>
            <div class="fs-card-body">
                <?php if (!empty($generated_invoices)): ?>
                    <table class="fs-table">
                        <thead>
                            <tr>
                                <th><?php esc_html_e('Invoice #', 'freelance-studio'); ?></th>
                                <th><?php esc_html_e('Date', 'freelance-studio'); ?></th>
                                <th><?php esc_html_e('Status', 'freelance-studio'); ?></th>
                                <th class="fs-table-number"><?php esc_html_e('Amount', 'freelance-studio'); ?></th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($generated_invoices as $invoice): ?>
                                <tr>
                                    <td>
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=view&id=' . $invoice->id) ); ?>">
                                            <?php echo esc_html($invoice->invoice_number); ?>
                                        </a>
                                    </td>
                                    <td><?php echo esc_html(gmdate('M j, Y', strtotime($invoice->invoice_date ?: $invoice->created_at))); ?></td>
                                    <td>
                                        <?php 
                                        $inv_status_class = 'status-' . $invoice->status;
                                        ?>
                                        <span class="fs-status-badge <?php echo  esc_attr( $inv_status_class ); ?>">
                                            <?php echo esc_html(ucfirst($invoice->status)); ?>
                                        </span>
                                    </td>
                                    <td class="fs-table-number"><?php echo  esc_html( FS_View_Context::format_currency($invoice->total) ); ?></td>
                                    <td>
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=view&id=' . $invoice->id) ); ?>" class="fs-action-link">
                                            <span class="dashicons dashicons-visibility"></span>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <p class="fs-muted"><?php esc_html_e('No invoices have been generated yet.', 'freelance-studio'); ?></p>
                <?php endif; ?>
            </div>
        </div>

        <!-- Actions Card -->
        <div class="fs-card">
            <div class="fs-card-header">
                <h2><?php esc_html_e('Actions', 'freelance-studio'); ?></h2>
            </div>
            <div class="fs-card-body">
                <div class="fs-action-buttons-row">
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=recurring&action=edit&id=' . $recurring->id) ); ?>" class="fs-btn fs-btn-secondary">
                        <span class="dashicons dashicons-edit"></span>
                        <?php esc_html_e('Edit Recurring Invoice', 'freelance-studio'); ?>
                    </a>
                    
                    <?php if ($recurring->status === 'active'): ?>
                        <button type="button" class="fs-btn fs-btn-secondary" id="pause-recurring">
                            <span class="dashicons dashicons-controls-pause"></span>
                            <?php esc_html_e('Pause', 'freelance-studio'); ?>
                        </button>
                    <?php elseif ($recurring->status === 'paused'): ?>
                        <button type="button" class="fs-btn fs-btn-primary" id="resume-recurring">
                            <span class="dashicons dashicons-controls-play"></span>
                            <?php esc_html_e('Resume', 'freelance-studio'); ?>
                        </button>
                    <?php endif; ?>
                    
                    <button type="button" class="fs-btn fs-btn-danger fs-delete-recurring" data-id="<?php echo esc_attr($recurring->id); ?>">
                        <span class="dashicons dashicons-trash"></span>
                        <?php esc_html_e('Delete', 'freelance-studio'); ?>
                    </button>
                </div>
            </div>
        </div>
    </div>
<?php if (empty($GLOBALS['fs_in_finances'])): ?>
</div>
<?php endif; ?>

<script>
jQuery(document).ready(function($) {
    // Pause recurring invoice
    $('#pause-recurring').on('click', function() {
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_update_recurring_status',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                id: <?php echo  intval( $recurring->id ); ?>,
                status: 'paused'
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.data || 'Error updating status');
                }
            }
        });
    });
    
    // Resume recurring invoice
    $('#resume-recurring').on('click', function() {
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_update_recurring_status',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                id: <?php echo  intval( $recurring->id ); ?>,
                status: 'active'
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.data || 'Error updating status');
                }
            }
        });
    });
    
    // Delete recurring invoice
    $('.fs-delete-recurring').on('click', function() {
        if (!confirm('<?php esc_html_e('Are you sure you want to delete this recurring invoice?', 'freelance-studio'); ?>')) {
            return;
        }
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_delete_recurring_invoice',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                id: $(this).data('id')
            },
            success: function(response) {
                if (response.success) {
                    window.location.href = '<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=recurring') ); ?>';
                } else {
                    alert(response.data || 'Error deleting recurring invoice');
                }
            }
        });
    });
});
</script>
