<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

add_action( 'admin_menu', 'elementsell_issued_invoices_register_menu', 21 );
add_action( 'admin_post_elementsell_save_invoice_edit', 'elementsell_handle_save_invoice_edit' );

/**
 * @return void
 */
function elementsell_issued_invoices_register_menu() {
    add_submenu_page(
        null,
        'Faktury, které jste vystavili',
        'Faktury, které jste vystavili',
        'manage_options',
        'elementsell-issued-invoices',
        'elementsell_render_issued_invoices_page'
    );

    add_submenu_page(
        null,
        'Upravit fakturu',
        'Upravit fakturu',
        'manage_options',
        'elementsell-invoice-edit',
        'elementsell_render_invoice_edit_page'
    );
}

/**
 * @param array $args
 * @return string
 */
function elementsell_get_issued_invoices_admin_url( $args = [] ) {
    return add_query_arg(
        array_merge(
            [ 'page' => 'elementsell-issued-invoices' ],
            $args
        ),
        admin_url( 'admin.php' )
    );
}

/**
 * @return int[]
 */
function elementsell_get_issued_invoice_years() {
    global $wpdb;

    $table = elementsell_get_invoices_table_name();

    $years = $wpdb->get_col(
        "SELECT DISTINCT YEAR(issue_date) AS invoice_year
         FROM {$table}
         WHERE type != 'demo' AND status = 'paid' AND issue_date IS NOT NULL
         ORDER BY invoice_year DESC"
    );

    return array_map( 'intval', (array) $years );
}

/**
 * @param array $args
 * @return array<int, object>
 */
function elementsell_get_issued_invoices_filtered( $args = [] ) {
    global $wpdb;

    $invoices_table = elementsell_get_invoices_table_name();
    $orders_table   = $wpdb->prefix . 'elementsell_orders';
    $year           = isset( $args['year'] ) ? (int) $args['year'] : 0;
    $month          = isset( $args['month'] ) ? (int) $args['month'] : 0;
    $limit          = isset( $args['limit'] ) ? max( 1, (int) $args['limit'] ) : 200;

    $where  = [ "i.type != 'demo'", "i.status = 'paid'" ];
    $params = [];

    if ( $year > 0 ) {
        $where[]  = 'YEAR(i.issue_date) = %d';
        $params[] = $year;
    }

    if ( $month > 0 ) {
        $where[]  = 'MONTH(i.issue_date) = %d';
        $params[] = $month;
    }

    $sql = "
        SELECT i.*, o.email AS customer_email, o.first_name, o.surname
        FROM {$invoices_table} i
        INNER JOIN {$orders_table} o ON o.id = i.order_id
        WHERE " . implode( ' AND ', $where ) . "
        ORDER BY i.issue_date DESC, i.id DESC
        LIMIT {$limit}
    ";

    if ( ! empty( $params ) ) {
        return (array) $wpdb->get_results( $wpdb->prepare( $sql, ...$params ) );
    }

    return (array) $wpdb->get_results( $sql );
}

/**
 * @return void
 */
function elementsell_render_issued_invoices_page() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    elementsell_render_admin_styles();

    $year     = isset( $_GET['issued_year'] ) ? (int) $_GET['issued_year'] : 0;
    $month    = isset( $_GET['issued_month'] ) ? (int) $_GET['issued_month'] : 0;
    $years    = elementsell_get_issued_invoice_years();
    $invoices = elementsell_get_issued_invoices_filtered(
        [
            'year'  => $year,
            'month' => $month,
            'limit' => 500,
        ]
    );

    $month_labels = [
        1  => 'Leden',
        2  => 'Únor',
        3  => 'Březen',
        4  => 'Duben',
        5  => 'Květen',
        6  => 'Červen',
        7  => 'Červenec',
        8  => 'Srpen',
        9  => 'Září',
        10 => 'Říjen',
        11 => 'Listopad',
        12 => 'Prosinec',
    ];

    ?>
    <div class="wrap elementsell-admin elementsell-issued-invoices-page">
        <p style="margin-bottom:16px;">
            <a href="<?php echo esc_url( admin_url( 'admin.php?page=elementsell' ) ); ?>">&larr; Zpět na ElementSell</a>
        </p>

        <h1>Faktury, které jste vystavili</h1>
        <p class="description">Faktury vystavené vašim zákazníkům po zaplacení objednávky.</p>

        <div class="elementsell-invoices-toolbar">
        <form method="get" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>" class="elementsell-invoices-filter">
            <input type="hidden" name="page" value="elementsell-issued-invoices">

            <label for="elementsell-issued-year">Rok</label>
            <select id="elementsell-issued-year" name="issued_year">
                <option value="0">Vše</option>
                <?php foreach ( $years as $invoice_year ) : ?>
                    <option value="<?php echo esc_attr( (string) $invoice_year ); ?>"<?php selected( $year, $invoice_year ); ?>>
                        <?php echo esc_html( (string) $invoice_year ); ?>
                    </option>
                <?php endforeach; ?>
            </select>

            <label for="elementsell-issued-month">Měsíc</label>
            <select id="elementsell-issued-month" name="issued_month">
                <option value="0">Vše</option>
                <?php foreach ( $month_labels as $month_number => $month_label ) : ?>
                    <option value="<?php echo esc_attr( (string) $month_number ); ?>"<?php selected( $month, $month_number ); ?>>
                        <?php echo esc_html( $month_label ); ?>
                    </option>
                <?php endforeach; ?>
            </select>

            <button type="submit" class="button">Filtrovat</button>
            <a class="button button-link" href="<?php echo esc_url( elementsell_get_issued_invoices_admin_url() ); ?>">Zrušit filtr</a>
        </form>
        <?php
        elementsell_render_invoices_zip_download_button(
            'elementsell_download_issued_invoices_zip',
            [
                'issued_year'  => $year,
                'issued_month' => $month,
            ],
            empty( $invoices )
        );
        ?>
        </div>

        <div class="elementsell-admin-card" style="margin-top:20px;">
            <?php if ( empty( $invoices ) ) : ?>
                <p class="elementsell-admin-empty">Žádné faktury pro zvolený filtr.</p>
            <?php else : ?>
                <table class="widefat striped">
                    <thead>
                        <tr>
                            <th>Číslo</th>
                            <th>Vystaveno</th>
                            <th>Zákazník</th>
                            <th>Produkt</th>
                            <th>Částka</th>
                            <th>Akce</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ( $invoices as $invoice ) : ?>
                            <?php
                            $customer_name = trim( (string) $invoice->first_name . ' ' . (string) $invoice->surname );
                            ?>
                            <tr>
                                <td><?php echo esc_html( $invoice->invoice_number ); ?></td>
                                <td><?php echo esc_html( mysql2date( 'j. n. Y', $invoice->issue_date, false ) ); ?></td>
                                <td>
                                    <?php echo esc_html( $customer_name !== '' ? $customer_name : '—' ); ?><br>
                                    <span class="description"><?php echo esc_html( (string) $invoice->customer_email ); ?></span>
                                </td>
                                <td><?php echo esc_html( (string) $invoice->product_name ); ?></td>
                                <td><?php echo esc_html( elementsell_format_invoice_amount( (float) $invoice->price ) ); ?></td>
                                <td>
                                    <?php if ( function_exists( 'elementsell_get_invoice_edit_admin_url' ) ) : ?>
                                        <a href="<?php echo esc_url( elementsell_get_invoice_edit_admin_url( (int) $invoice->id ) ); ?>">Upravit</a>
                                        <span class="description">|</span>
                                    <?php endif; ?>
                                    <a href="<?php echo esc_url( add_query_arg( 'return', 'issued', elementsell_get_invoice_admin_url( (int) $invoice->id ) ) ); ?>">Náhled</a>
                                    <?php if ( function_exists( 'elementsell_get_issued_invoice_download_url' ) ) : ?>
                                        <span class="description">|</span>
                                        <a href="<?php echo esc_url( elementsell_get_issued_invoice_download_url( (int) $invoice->id ) ); ?>">Stáhnout</a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>
    <?php
}

/**
 * @param string $return
 * @return string
 */
function elementsell_get_invoice_edit_back_url( $return = 'issued' ) {
    if ( $return === 'orders' ) {
        return admin_url( 'admin.php?page=elementsell' );
    }

    return elementsell_get_issued_invoices_admin_url();
}

/**
 * @return void
 */
function elementsell_handle_save_invoice_edit() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'Nemáte oprávnění.', 'platebni-formular' ) );
    }

    if ( ! function_exists( 'elementsell_update_issued_invoice' ) ) {
        wp_die( esc_html__( 'Editor faktur není k dispozici. Aktualizujte plugin.', 'platebni-formular' ) );
    }

    $invoice_id = isset( $_POST['invoice_id'] ) ? (int) $_POST['invoice_id'] : 0;
    $return     = isset( $_POST['return'] ) ? sanitize_key( wp_unslash( (string) $_POST['return'] ) ) : 'issued';

    check_admin_referer( 'elementsell_save_invoice_edit_' . $invoice_id );

    $result = elementsell_update_issued_invoice(
        $invoice_id,
        [
            'product_name' => isset( $_POST['product_name'] ) ? wp_unslash( (string) $_POST['product_name'] ) : '',
            'price'        => isset( $_POST['price'] ) ? wp_unslash( (string) $_POST['price'] ) : '',
            'issue_date'   => isset( $_POST['issue_date'] ) ? wp_unslash( (string) $_POST['issue_date'] ) : '',
            'paid_date'    => isset( $_POST['paid_date'] ) ? wp_unslash( (string) $_POST['paid_date'] ) : '',
            'first_name'   => isset( $_POST['first_name'] ) ? wp_unslash( (string) $_POST['first_name'] ) : '',
            'surname'      => isset( $_POST['surname'] ) ? wp_unslash( (string) $_POST['surname'] ) : '',
            'company'      => isset( $_POST['company'] ) ? wp_unslash( (string) $_POST['company'] ) : '',
            'address'      => isset( $_POST['address'] ) ? wp_unslash( (string) $_POST['address'] ) : '',
            'ico'          => isset( $_POST['ico'] ) ? wp_unslash( (string) $_POST['ico'] ) : '',
            'dic'          => isset( $_POST['dic'] ) ? wp_unslash( (string) $_POST['dic'] ) : '',
        ]
    );

    if ( is_wp_error( $result ) ) {
        wp_safe_redirect(
            add_query_arg(
                [
                    'page'       => 'elementsell-invoice-edit',
                    'invoice_id' => $invoice_id,
                    'return'     => $return,
                    'error'      => rawurlencode( $result->get_error_message() ),
                ],
                admin_url( 'admin.php' )
            )
        );
        exit;
    }

    wp_safe_redirect(
        add_query_arg(
            [
                'page'       => 'elementsell-invoice-edit',
                'invoice_id' => $invoice_id,
                'return'     => $return,
                'saved'      => '1',
            ],
            admin_url( 'admin.php' )
        )
    );
    exit;
}

/**
 * @return void
 */
function elementsell_render_invoice_edit_page() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    if ( ! function_exists( 'elementsell_update_issued_invoice' ) ) {
        echo '<div class="wrap"><p>Editor faktur není k dispozici. Nahrajte aktuální verzi pluginu.</p></div>';
        return;
    }

    $invoice_id = isset( $_GET['invoice_id'] ) ? (int) $_GET['invoice_id'] : 0;
    $return     = isset( $_GET['return'] ) ? sanitize_key( wp_unslash( (string) $_GET['return'] ) ) : 'issued';
    $invoice    = $invoice_id ? elementsell_get_invoice( $invoice_id ) : null;

    elementsell_render_admin_styles();

    echo '<div class="wrap elementsell-admin elementsell-invoice-edit-wrap">';
    echo '<p style="margin-bottom:16px;"><a href="' . esc_url( elementsell_get_invoice_edit_back_url( $return ) ) . '">&larr; Zpět na faktury</a></p>';

    if ( ! $invoice || (string) $invoice->type === 'demo' ) {
        echo '<p>Fakturu nelze upravit.</p>';
        echo '</div>';
        return;
    }

    $order = elementsell_get_order( (int) $invoice->order_id );

    if ( ! $order ) {
        echo '<p>Objednávka k faktuře nebyla nalezena.</p>';
        echo '</div>';
        return;
    }

    if ( ! empty( $_GET['saved'] ) ) {
        echo '<div class="notice notice-success"><p>Faktura byla uložena a PDF přegenerováno.</p></div>';
    }

    if ( ! empty( $_GET['error'] ) ) {
        echo '<div class="notice notice-error"><p>' . esc_html( wp_unslash( (string) $_GET['error'] ) ) . '</p></div>';
    }

    $company = (string) elementsell_get_order_field( $order->id, 'company' );
    $address = (string) elementsell_get_order_field( $order->id, 'address' );
    $ico     = (string) elementsell_get_order_field( $order->id, 'ico' );
    $dic     = (string) elementsell_get_order_field( $order->id, 'dic' );

    ?>
    <h1>Upravit fakturu <?php echo esc_html( $invoice->invoice_number ); ?></h1>
    <p class="description">Změny se projeví na faktuře i v PDF. Číslo faktury zůstává stejné.</p>

    <div class="elementsell-admin-card elementsell-admin-card--form">
        <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
            <?php wp_nonce_field( 'elementsell_save_invoice_edit_' . $invoice_id ); ?>
            <input type="hidden" name="action" value="elementsell_save_invoice_edit">
            <input type="hidden" name="invoice_id" value="<?php echo esc_attr( (string) $invoice_id ); ?>">
            <input type="hidden" name="return" value="<?php echo esc_attr( $return ); ?>">

            <table class="form-table">
                <tr>
                    <th scope="row"><label for="elementsell-invoice-product-name">Popis na faktuře</label></th>
                    <td>
                        <input type="text" class="large-text" id="elementsell-invoice-product-name" name="product_name" value="<?php echo esc_attr( (string) $invoice->product_name ); ?>" required>
                        <p class="description">Text v řádku faktury, např. pro proplacení zaměstnavatelem.</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="elementsell-invoice-price">Částka (Kč)</label></th>
                    <td>
                        <input type="number" step="0.01" min="0.01" class="small-text" id="elementsell-invoice-price" name="price" value="<?php echo esc_attr( (string) $invoice->price ); ?>" required>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="elementsell-invoice-issue-date">Datum vystavení</label></th>
                    <td>
                        <input type="date" id="elementsell-invoice-issue-date" name="issue_date" value="<?php echo esc_attr( (string) $invoice->issue_date ); ?>" required>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="elementsell-invoice-paid-date">Datum úhrady</label></th>
                    <td>
                        <input type="date" id="elementsell-invoice-paid-date" name="paid_date" value="<?php echo esc_attr( (string) $invoice->paid_date ); ?>" required>
                    </td>
                </tr>
            </table>

            <h2 class="elementsell-admin-section-title" style="margin-top:24px;">Odběratel na faktuře</h2>
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="elementsell-invoice-first-name">Jméno</label></th>
                    <td><input type="text" class="regular-text" id="elementsell-invoice-first-name" name="first_name" value="<?php echo esc_attr( (string) $order->first_name ); ?>"></td>
                </tr>
                <tr>
                    <th scope="row"><label for="elementsell-invoice-surname">Příjmení</label></th>
                    <td><input type="text" class="regular-text" id="elementsell-invoice-surname" name="surname" value="<?php echo esc_attr( (string) $order->surname ); ?>"></td>
                </tr>
                <tr>
                    <th scope="row"><label for="elementsell-invoice-company">Firma</label></th>
                    <td><input type="text" class="regular-text" id="elementsell-invoice-company" name="company" value="<?php echo esc_attr( $company ); ?>"></td>
                </tr>
                <tr>
                    <th scope="row"><label for="elementsell-invoice-address">Adresa</label></th>
                    <td><textarea class="large-text" rows="3" id="elementsell-invoice-address" name="address"><?php echo esc_textarea( $address ); ?></textarea></td>
                </tr>
                <tr>
                    <th scope="row"><label for="elementsell-invoice-ico">IČO</label></th>
                    <td><input type="text" class="regular-text" id="elementsell-invoice-ico" name="ico" value="<?php echo esc_attr( $ico ); ?>"></td>
                </tr>
                <tr>
                    <th scope="row"><label for="elementsell-invoice-dic">DIČ</label></th>
                    <td><input type="text" class="regular-text" id="elementsell-invoice-dic" name="dic" value="<?php echo esc_attr( $dic ); ?>"></td>
                </tr>
            </table>

            <p class="submit">
                <button type="submit" class="button button-primary">Uložit a přegenerovat PDF</button>
                <a class="button" href="<?php echo esc_url( add_query_arg( 'return', $return, elementsell_get_invoice_admin_url( $invoice_id ) ) ); ?>">Náhled faktury</a>
            </p>
        </form>
    </div>
    </div>
    <?php
}
