<?php
use BLR\Backline\Modules\Finances\Module as FinancesModule;

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

$base = rtrim((string) ($ctx['base_url'] ?? ''), '/') . '/';
$is_edit = (($ctx['action'] ?? '') === 'edit');
$id = (int) ($ctx['id'] ?? 0);
$post = $is_edit ? get_post($id) : null;

if ($is_edit && (!$post instanceof WP_Post || $post->post_type !== FinancesModule::POST_TYPE)) {
    echo '<div class="container-fluid p-0"><div class="alert alert-danger">' . esc_html__('Finance record not found.', 'blr-backline') . '</div></div>';
    return;
}

$title_v = $post ? $post->post_title : '';
$content_v = $post ? (string) $post->post_content : '';
$errors = isset($ctx['errors']) && is_array($ctx['errors']) ? $ctx['errors'] : [];
$posted_values = isset($ctx['finance_values']) && is_array($ctx['finance_values']) ? $ctx['finance_values'] : [];

$get_posted_value = static function (string $key, string $fallback = '') use ($posted_values): string {
    return array_key_exists($key, $posted_values) ? $posted_values[$key] : $fallback;
};

$get_meta_value = static function (string $key, string $fallback = '') use ($id, $post, $get_posted_value): string {
    $stored = $post ? (string) get_post_meta($id, $key, true) : $fallback;
    return $get_posted_value($key, $stored);
};

$title_value = $get_posted_value('title', $title_v);
$content_value = $get_posted_value('content', $content_v);
$attachment_selected = FinancesModule::validate_attachment_id(absint($get_posted_value(FinancesModule::ATTACHMENT_META_KEY, $post ? (string) get_post_meta($id, FinancesModule::ATTACHMENT_META_KEY, true) : '0')));
$attachment_data = $attachment_selected > 0 ? FinancesModule::attachment_data($attachment_selected) : [];
$attachment_options = FinancesModule::attachment_options(150, $attachment_selected);
$selected_contact_id = absint($get_meta_value('blr_finance_contact_id', '0'));
$contact_options = FinancesModule::contact_options($selected_contact_id);

// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only success notice.
$saved_notice = isset($_GET['saved']) ? absint((string) wp_unslash($_GET['saved'])) : 0;
// phpcs:enable WordPress.Security.NonceVerification.Recommended
?>
<div class="container-fluid p-0">
    <div class="d-flex flex-column flex-md-row align-items-md-center justify-content-between gap-3 mb-3">
        <div>
            <h1 class="h3 mb-0"><?php echo esc_html($is_edit ? __('Edit Finance Record', 'blr-backline') : __('New Finance Record', 'blr-backline')); ?></h1>
        </div>
        <div>
            <a class="btn btn-outline-secondary" href="<?php echo esc_url($base . 'finances/'); ?>"><?php echo esc_html__('Back to Finances', 'blr-backline'); ?></a>
        </div>
    </div>

    <?php if ($saved_notice) : ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo esc_html__('Saved.', 'blr-backline'); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="<?php echo esc_attr__('Close', 'blr-backline'); ?>"></button>
        </div>
    <?php endif; ?>

    <?php if (!empty($errors)) : ?>
        <div class="alert alert-danger" role="alert">
            <div class="fw-semibold mb-2"><?php echo esc_html__('Please fix the following:', 'blr-backline'); ?></div>
            <ul class="mb-0">
                <?php foreach ($errors as $error) : ?>
                    <li><?php echo esc_html((string) $error); ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <div class="card shadow-sm border-0">
        <div class="card-body">
            <form method="post" enctype="multipart/form-data">
                <input type="hidden" name="blr_ba_action" value="blr_ba_save_finance">
                <?php wp_nonce_field('blr_ba_save_finance'); ?>

                <div class="row g-4">
                    <div class="col-12 col-xl-8">
                        <div class="mb-3">
                            <label class="form-label"><?php echo esc_html__('Title', 'blr-backline'); ?></label>
                            <input class="form-control" type="text" name="title" value="<?php echo esc_attr($title_value); ?>" required>
                        </div>

                        <div class="row g-3">
                            <div class="col-12 col-md-4">
                                <label class="form-label"><?php echo esc_html__('Type', 'blr-backline'); ?></label>
                                <select class="form-select" name="blr_finance_kind" required>
                                    <option value=""><?php echo esc_html__('Select type', 'blr-backline'); ?></option>
                                    <?php foreach (FinancesModule::kinds() as $kind) : ?>
                                        <option value="<?php echo esc_attr($kind); ?>" <?php selected($get_meta_value('blr_finance_kind'), $kind); ?>><?php echo esc_html(FinancesModule::kind_label($kind)); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-12 col-md-4">
                                <label class="form-label"><?php echo esc_html__('Status', 'blr-backline'); ?></label>
                                <select class="form-select" name="blr_finance_status" required>
                                    <option value=""><?php echo esc_html__('Select status', 'blr-backline'); ?></option>
                                    <?php foreach (FinancesModule::statuses() as $status) : ?>
                                        <option value="<?php echo esc_attr($status); ?>" <?php selected($get_meta_value('blr_finance_status'), $status); ?>><?php echo esc_html(FinancesModule::status_label($status)); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-12 col-md-4">
                                <label class="form-label"><?php echo esc_html__('Category', 'blr-backline'); ?></label>
                                <input class="form-control" type="text" name="blr_finance_category" value="<?php echo esc_attr($get_meta_value('blr_finance_category')); ?>" placeholder="<?php echo esc_attr__('Studio, merch, venue, etc.', 'blr-backline'); ?>">
                            </div>
                        </div>

                        <div class="row g-3 mt-0">
                            <div class="col-12 col-md-4">
                                <label class="form-label"><?php echo esc_html__('Amount', 'blr-backline'); ?></label>
                                <input class="form-control" type="text" name="blr_finance_amount" value="<?php echo esc_attr($get_meta_value('blr_finance_amount')); ?>" required>
                            </div>
                            <div class="col-12 col-md-4">
                                <label class="form-label"><?php echo esc_html__('Currency', 'blr-backline'); ?></label>
                                <input class="form-control text-uppercase" type="text" name="blr_finance_currency" value="<?php echo esc_attr($get_meta_value('blr_finance_currency', 'USD')); ?>" maxlength="3" required>
                            </div>
                            <div class="col-12 col-md-4">
                                <label class="form-label"><?php echo esc_html__('Payment Method', 'blr-backline'); ?></label>
                                <input class="form-control" type="text" name="blr_finance_payment_method" value="<?php echo esc_attr($get_meta_value('blr_finance_payment_method')); ?>" placeholder="<?php echo esc_attr__('Card, ACH, cash, etc.', 'blr-backline'); ?>">
                            </div>
                        </div>

                        <div class="row g-3 mt-0">
                            <div class="col-12 col-md-4">
                                <label class="form-label"><?php echo esc_html__('Date', 'blr-backline'); ?></label>
                                <input class="form-control" type="date" name="blr_finance_date" value="<?php echo esc_attr($get_meta_value('blr_finance_date')); ?>" required>
                            </div>
                            <div class="col-12 col-md-4">
                                <label class="form-label"><?php echo esc_html__('Due Date', 'blr-backline'); ?></label>
                                <input class="form-control" type="date" name="blr_finance_due_date" value="<?php echo esc_attr($get_meta_value('blr_finance_due_date')); ?>">
                            </div>
                            <div class="col-12 col-md-4">
                                <label class="form-label"><?php echo esc_html__('Reference', 'blr-backline'); ?></label>
                                <input class="form-control" type="text" name="blr_finance_reference" value="<?php echo esc_attr($get_meta_value('blr_finance_reference')); ?>" placeholder="<?php echo esc_attr__('Invoice #, receipt #, PO, etc.', 'blr-backline'); ?>">
                            </div>
                        </div>

                        <div class="row g-3 mt-0">
                            <div class="col-12">
                                <label class="form-label"><?php echo esc_html__('Notes', 'blr-backline'); ?></label>
                                <textarea class="form-control" name="content" rows="8"><?php echo esc_textarea($content_value); ?></textarea>
                            </div>
                        </div>
                    </div>

                    <div class="col-12 col-xl-4">
                        <div class="mb-3">
                            <label class="form-label"><?php echo esc_html__('Contact', 'blr-backline'); ?></label>
                            <select class="form-select" name="blr_finance_contact_id">
                                <option value="0"><?php echo esc_html__('No linked contact', 'blr-backline'); ?></option>
                                <?php foreach ($contact_options as $contact_id => $contact_label) : ?>
                                    <option value="<?php echo (int) $contact_id; ?>" <?php selected($selected_contact_id, (int) $contact_id); ?>><?php echo esc_html($contact_label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="card bg-light-subtle border-0 mb-3">
                            <div class="card-body">
                                <h2 class="h6 mb-3"><?php echo esc_html__('Choose Existing Attachment', 'blr-backline'); ?></h2>
                                <?php
                                FinancesModule::render_visual_attachment_picker(
                                    FinancesModule::ATTACHMENT_META_KEY,
                                    [
                                        'selected' => $attachment_selected,
                                        'options' => $attachment_options,
                                        'allow_none' => true,
                                        'none_label' => __('No attachment selected', 'blr-backline'),
                                    ]
                                );
                                ?>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><?php echo esc_html__('Upload Attachment', 'blr-backline'); ?></label>
                            <input class="form-control" type="file" name="finance_attachment_file" accept="image/*,.pdf,application/pdf">
                            <div class="form-text"><?php echo esc_html__('Upload one image or PDF. If you upload a new file, it replaces the selected attachment.', 'blr-backline'); ?></div>
                        </div>

                        <?php if (!empty($attachment_data)) : ?>
                            <div class="card shadow-sm border-0">
                                <div class="card-header">
                                    <h2 class="h6 mb-0"><?php echo esc_html__('Current Attachment', 'blr-backline'); ?></h2>
                                </div>
                                <div class="card-body">
                                    <?php if (!empty($attachment_data['is_image']) && !empty($attachment_data['preview_url'])) : ?>
                                        <img class="img-fluid rounded border mb-3" src="<?php echo esc_url((string) $attachment_data['preview_url']); ?>" alt="<?php echo esc_attr(FinancesModule::attachment_label($attachment_data)); ?>">
                                    <?php elseif (!empty($attachment_data['preview_url'])) : ?>
                                        <img class="img-fluid rounded border mb-3" src="<?php echo esc_url((string) $attachment_data['preview_url']); ?>" alt="<?php echo esc_attr(FinancesModule::attachment_label($attachment_data)); ?>">
                                    <?php endif; ?>
                                    <div class="fw-semibold"><?php echo esc_html(FinancesModule::attachment_label($attachment_data)); ?></div>
                                    <?php if (!empty($attachment_data['filename'])) : ?>
                                        <div class="small text-muted"><?php echo esc_html((string) $attachment_data['filename']); ?></div>
                                    <?php endif; ?>
                                    <?php if (!empty($attachment_data['url'])) : ?>
                                        <div class="mt-3"><a class="btn btn-sm btn-outline-secondary" href="<?php echo esc_url((string) $attachment_data['url']); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('Open attachment', 'blr-backline'); ?></a></div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="d-flex gap-2 mt-4">
                    <button class="btn btn-primary" type="submit"><?php echo esc_html__('Save', 'blr-backline'); ?></button>
                    <a class="btn btn-outline-secondary" href="<?php echo esc_url($base . 'finances/'); ?>"><?php echo esc_html__('Cancel', 'blr-backline'); ?></a>
                </div>
            </form>
        </div>
    </div>
</div>
