<?php
/**
 * Plugin Name:       Simple Invoice Generator
 * Plugin URI:        https://oplugins.com
 * Description:       Generate invoices and download them as PDFs without a database.
 * Version:           1.0.9
 * Requires at least: 5.2
 * Requires PHP:      7.0
 * Author:            tsplugins
 * License:           GPL v2 or later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       invoice-generator
 * Domain Path:       /languages
 */

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

define( 'INGEN_DIR_PATH' , plugin_dir_path(__FILE__)  ) ;

require_once INGEN_DIR_PATH . 'includes/generate-invoice-pdf-from-data.php';

if (get_option('ingen_enable_woo', true)) {
    require_once INGEN_DIR_PATH . 'includes/woo-integration.php';
    add_action('woocommerce_order_status_completed', 'ingen_generate_invoice_for_order');
}


add_action('admin_menu', 'ingen_add_admin_menu');
add_action('admin_enqueue_scripts', 'ingen_enqueue_assets');
add_action('wp_ajax_ingen_generate_pdf', 'ingen_generate_pdf');
add_action('admin_init', 'ingen_register_settings');


function ingen_add_admin_menu() {
    add_menu_page('Invoice Generator', 'Invoice Generator', 'manage_options', 'invoice-generator', 'ingen_render_page');
    add_submenu_page('invoice-generator', 'Settings', 'Settings', 'manage_options', 'invoice-generator-settings', 'ingen_settings_page');
}


function ingen_enqueue_assets($hook) {
    if ($hook !== 'toplevel_page_invoice-generator') return;

     wp_enqueue_script('jquery');
     wp_enqueue_media();

     wp_enqueue_script('flatpickr-js', plugin_dir_url(__FILE__) . 'vendor/flatpickr/flatpickr.min.js', array(), '4.6.13', true);
     wp_enqueue_style('flatpickr-css', plugin_dir_url(__FILE__) . 'vendor/flatpickr/flatpickr.min.css', array(), '4.6.13');

     wp_enqueue_script('invoice-generator-script', plugin_dir_url(__FILE__) . 'script.js', array('flatpickr-js'), '1.0', true);
     wp_enqueue_style('invoice-generator-tailwindcss', plugin_dir_url(__FILE__) . 'admin/css/tailwind/tailwind.min.css', array(), '1.0');
     wp_enqueue_style(
            'invoice-generator-style',
            plugin_dir_url(__FILE__) . 'admin/css/invoice-style.css',
            array(),
            '1.0'
        );

    wp_localize_script('invoice-generator-script', 'ingen_ajax_object', [
        'ajax_url' => admin_url('admin-ajax.php'),
    ]);
}


function ingen_render_page() {
    ?> <div class="wrap max-w-5xl mx-auto px-4">
    <h1 class="text-2xl sm:text-3xl font-medium text-center text-gray-900 mb-16"><?php esc_html_e('Create Invoice', 'invoice-generator'); ?></h1>
    <form id="invoice-form" class="mt-3 space-y-6 bg-white p-6 rounded-xl shadow-md">
        <!-- Invoice Header Section -->
        <div class="text-center w-full md:w-auto">
            <div class="text-base font-semibold text-gray-800"><?php esc_html_e('Invoice', 'invoice-generator'); ?> #</div>
            <input type="text" id="invoice_number" name="invoice_number" maxlength="15" value="<?php echo esc_attr( wp_date('zHi') ); ?>" class="form-input text-center text-sm font-medium text-gray-700 max-w-xs w-auto mt-1">
        </div>
        <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-4">
            <div class="flex flex-col sm:flex-row items-start sm:items-center gap-2 w-full md:w-auto">
                <label for="invoice_date" class="text-sm font-medium text-gray-700 whitespace-nowrap"><?php esc_html_e('Invoice Date', 'invoice-generator'); ?></label>
                <input type="date" id="invoice_date" name="invoice_date" required class="form-input">
            </div>
            <div class="flex flex-col sm:flex-row items-start sm:items-center gap-2 w-full md:w-auto">
                <label for="due_date" class="text-sm font-medium text-gray-700 whitespace-nowrap"><?php esc_html_e('Due Date', 'invoice-generator'); ?>: </label>
                <input type="date" id="due_date" name="due_date" required class="form-input">
            </div>
        </div>
        <!-- Bill Info -->
        <div class="grid sm:grid-cols-2 gap-4">
            <div>
                <h2 class="font-medium text-sm text-gray-700 mb-1"><?php esc_html_e('Bill From', 'invoice-generator'); ?></h2>
                <input type="text" id="bill_from_name" name="bill_from_name" placeholder="Name" required maxlength="30" class="form-input mt-1 block w-full">
                <input type="email" id="bill_from_email" name="bill_from_email" placeholder="Email" required maxlength="30" class="form-input mt-2 block w-full">
                <textarea name="bill_from_description" placeholder="Who is this invoice from?" maxlength="100" class="form-input mt-2 block w-full" rows="3"></textarea>
            </div>
            <div>
                <h2 class="font-medium text-sm text-gray-700 mb-1"><?php esc_html_e('Bill To', 'invoice-generator'); ?></h2>
                <input type="text" id="bill_to_name" name="bill_to_name" placeholder="Name" required maxlength="30" class="form-input mt-1 block w-full">
                <input type="email" id="bill_to_email" name="bill_to_email" placeholder="Email" required maxlength="30" class="form-input mt-2 block w-full">
                <textarea name="bill_to_description" placeholder="Who is this invoice for?" maxlength="100" class="form-input mt-2 block w-full" rows="3"></textarea>
            </div>
        </div>
        <!-- Invoice Items -->
        <div class="w-full overflow-x-auto">
          <div class="inline-block min-w-full align-middle">
            <table class="min-w-[700px] table-auto text-left border-collapse text-sm">
                <thead>
                    <tr>
                        <th class="py-2 px-3 border-b text-sm font-medium text-gray-700 bg-white w-1/2 text-left"><?php esc_html_e('Item', 'invoice-generator'); ?></th>
                        <th class="py-2 px-3 border-b text-sm font-medium text-gray-700 bg-white w-1/6 text-center"><?php esc_html_e('QTY', 'invoice-generator'); ?></th>
                        <th class="py-2 px-3 border-b text-sm font-medium text-gray-700 bg-white w-1/6 text-center"><?php esc_html_e('Price', 'invoice-generator'); ?></th>
                        <th class="py-2 px-3 border-b text-sm font-medium text-gray-700 bg-white w-1/6 text-center"><?php esc_html_e('Total', 'invoice-generator'); ?></th>
                        <th class="py-2 px-3 border-b text-sm font-medium text-gray-700 bg-white w-1/6 text-center"><?php esc_html_e('Action', 'invoice-generator'); ?></th>
                    </tr>
                </thead>
                <tbody id="invoice-items">
                    <tr>
                        <td class="py-2 px-3 border-b">
                            <input type="text" class="form-input w-full text-sm" name="item_name[]" placeholder="<?php esc_attr_e('Item name', 'invoice-generator'); ?>" required maxlength="50">
                        </td>
                        <td class="py-2 px-3 border-b">
                            <input type="number" class="form-input w-full text-sm" name="item_qty[]" value="1" min="1" max="999" required>
                        </td>
                        <td class="py-2 px-3 border-b">
                            <input type="text" class="form-input w-full text-sm" name="item_price[]" value="0.00" min="0.00" max="9999999" step="0.01" required>
                        </td>
                        <td class="py-2 px-3 border-b">
                            <input type="number" class="form-input w-full text-sm" name="item_total[]" value="0.00" readonly>
                        </td>
                        <td class="py-2 px-3 border-b text-center">
                            <button type="button" class="remove-item bg-gray-400 hover:bg-gray-500 text-white p-1 rounded-md flex items-center justify-center" title="<?php esc_attr_e('Remove', 'invoice-generator'); ?>">
                                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 pointer-events-none" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                                </svg>
                                <span class="sr-only"><?php esc_html_e('Remove', 'invoice-generator'); ?></span>
                            </button>
                        </td>
                    </tr>
                </tbody>
            </table> <?php wp_nonce_field('ingen_generate_pdf', 'ingen_nonce'); ?> <button type="button" id="add-item" class="mt-4 bg-blue-500 hover:bg-blue-600 text-white py-2 px-4 text-sm rounded-md"><?php esc_html_e('Add Item', 'invoice-generator'); ?></button>
        </div>
    </div>
        <!-- Currency Selector -->
        <div class="mb-4 flex justify-between items-center">
            <div class="flex-1 ingen_select_currency">
                <label for="currency" class="block mb-2 font-medium"><?php esc_html_e('Currency', 'invoice-generator'); ?></label>
                <select id="currency" name="currency" class="border border-gray-300 p-2 rounded currency-dropdown">
                    <option value="$" selected>USD - <?php esc_html_e('United States Dollar', 'invoice-generator'); ?> ($)</option>
                    <option value="€">EUR - <?php esc_html_e('Euro', 'invoice-generator'); ?> (€)</option>
                    <option value="£">GBP - <?php esc_html_e('British Pound', 'invoice-generator'); ?> (£)</option>
                    <option value="₴">UAH - <?php esc_html_e('Ukrainian Hryvnia', 'invoice-generator'); ?> (₴)</option>
                    <option value="JPY">JPY - <?php esc_html_e('Japanese Yen', 'invoice-generator'); ?> (¥)</option>
                    <option value="AUD">AUD - <?php esc_html_e('Australian Dollar', 'invoice-generator'); ?> (A$)</option>
                    <option value="CAD">CAD - <?php esc_html_e('Canadian Dollar', 'invoice-generator'); ?> (C$)</option>
                    <option value="CHF">CHF - <?php esc_html_e('Swiss Franc', 'invoice-generator'); ?> (Fr.)</option>
                    <option value="NZD">NZD - <?php esc_html_e('New Zealand Dollar', 'invoice-generator'); ?> (NZ$)</option>
                    <option value="SEK">SEK - <?php esc_html_e('Swedish Krona', 'invoice-generator'); ?> (kr)</option>
                    <option value="NOK">NOK - <?php esc_html_e('Norwegian Krone', 'invoice-generator'); ?> (kr)</option>
                    <option value="DKK">DKK - <?php esc_html_e('Danish Krone', 'invoice-generator'); ?> (kr)</option>
                    <option value="PLN">PLN - <?php esc_html_e('Polish Zloty', 'invoice-generator'); ?> (zł)</option>
                    <option value="HUF">HUF - <?php esc_html_e('Hungarian Forint', 'invoice-generator'); ?> (Ft)</option>
                    <option value="TRY">TRY - <?php esc_html_e('Turkish Lira', 'invoice-generator'); ?> (₺)</option>
                    <option value="BRL">BRL - <?php esc_html_e('Brazilian Real', 'invoice-generator'); ?> (R$)</option>
                    <option value="INR">INR - <?php esc_html_e('Indian Rupee', 'invoice-generator'); ?> (₹)</option>
                    <option value="RUB">RUB - <?php esc_html_e('Russian Ruble', 'invoice-generator'); ?> (₽)</option>
                    <option value="CNY">CNY - <?php esc_html_e('Chinese Yuan', 'invoice-generator'); ?> (¥)</option>
                    <option value="MXN">MXN - <?php esc_html_e('Mexican Peso', 'invoice-generator'); ?> (MX$)</option>
                </select>
            </div>

            <div class="ml-4 text-right">
                <p><strong><?php esc_html_e('Subtotal', 'invoice-generator'); ?>: </strong><span id="subtotal">$0.00</span></p>
                <p>
                    <strong><?php esc_html_e('Tax', 'invoice-generator'); ?> (%): </strong>
                    <input type="text" id="taxRate" value="0.00" min="0" max="9999999" step="0.01" required class="border rounded p-1 text-sm text-right w-20" style="width: 80px;" />
                </p>
                <p><strong><?php esc_html_e('Total', 'invoice-generator'); ?>: </strong><span id="total">$0.00</span></p>
            </div>
        </div>

        <div class="invoice-styles-row mt-8">
            <!-- Invoice Style Selector -->
            <div class="invoice-styles-selector-section">
                <label for="template_style" class="block mb-1 font-medium text-gray-700 ">
                    <?php esc_html_e('Invoice Style', 'invoice-generator'); ?>
                </label>
                <select
                    id="template_style"
                    name="template_style"
                    class="invoice-styles-selector appearance-none bg-white border border-gray-300 p-2 rounded currency-dropdown text-gray-700 text-sm rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 px-4 py-2 pr-10 w-full sm:w-60"
                >
                    <option value="standard" selected><?php esc_html_e('Standard', 'invoice-generator'); ?></option>
                    <option value="blue-accent"><?php esc_html_e('Blue Accent', 'invoice-generator'); ?></option>
                </select>
            </div>
    `        <div class="invoice-logo-selector-section">
                  <input type="hidden" id="logo_url" name="logo_url" />
                  <button
                    type="button"
                    id="upload_logo_button"
                    class="bg-blue-500 hover:bg-blue-600 text-white py-2 px-4 text-sm rounded-md"
                  >
                    <?php esc_html_e('Upload Logo', 'invoice-generator'); ?>
                  </button>
                  <div id="logo_preview" class="mt-3"></div>
            </div>
        </div>

        <div class="invoice-last-action-row flex justify-between pt-1">

            <button type="reset" id="reset-form" class="bg-gray-700 hover:bg-gray-800 text-white py-2 px-4 text-sm rounded-md min-w-[120px]"> <?php esc_html_e('Reset Form', 'invoice-generator'); ?> </button>
            <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white py-2 px-4 text-sm rounded-md min-w-[120px]"> <?php esc_html_e('Generate Invoice', 'invoice-generator'); ?> </button>
        </div>


    </form>
    <p id="invoice-message" class="mt-4"></p>

 <div class="mt-8 mb-8 text-center text-sm text-gray-500">
     <p>
         <a style="padding:0 10px" href="mailto:ts@oplugins.com?subject=Invoice%20Tool%20Help" class="text-blue-600 hover:underline">
             <?php esc_html_e( 'Contact support', 'invoice-generator' ); ?>
         </a> |
         <a style="padding:0 10px" href="mailto:ts@oplugins.com?subject=Feature%20Request%20for%20Invoice%20Tool" class="text-blue-600 hover:underline">
             <?php esc_html_e( 'Request a new feature', 'invoice-generator' ); ?>
         </a> |
         <a style="padding:0 10px" href="mailto:ts@oplugins.com?subject=Bug%20Report%20for%20Invoice%20Tool" class="text-blue-600 hover:underline">
             <?php esc_html_e( 'Report a bug', 'invoice-generator' ); ?>
         </a>
     </p>
 </div>

</div> <?php
}


function ingen_generate_pdf() {

    if ( ! isset($_POST['ingen_nonce']) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['ingen_nonce'] ) ), 'ingen_generate_pdf') ) {
        wp_send_json_error(['message' => 'Invalid nonce.'], 403);
        return;
    }

    $upload_dir = wp_upload_dir();
    $invoices_dir = $upload_dir['basedir'] . '/invoices';
    if (!file_exists($invoices_dir)) wp_mkdir_p($invoices_dir);

    $invoice_number = ( ! empty( $_POST['invoice_number'] ) )? sanitize_text_field(wp_unslash( $_POST['invoice_number'])): '';
    $invoice_date = ( ! empty( $_POST['invoice_date'] ) )? sanitize_text_field(wp_unslash( $_POST['invoice_date'])): '';
    $due_date = ( ! empty( $_POST['due_date'] ) )? sanitize_text_field(wp_unslash( $_POST['due_date'])): '';
    $bill_from_name = ( ! empty( $_POST['bill_from_name'] ) )? sanitize_text_field( wp_unslash( $_POST['bill_from_name'])): '';
    $bill_from_email = ( ! empty( $_POST['bill_from_email'] ) )? sanitize_email( wp_unslash( $_POST['bill_from_email'])): '';
    $bill_from_description = ( ! empty( $_POST['bill_from_description'] ) )? sanitize_textarea_field(wp_unslash($_POST['bill_from_description'])): '';
    $bill_to_name = ( ! empty( $_POST['bill_to_name'] ) )? sanitize_text_field(wp_unslash($_POST['bill_to_name'])): '';
    $bill_to_email = ( ! empty( $_POST['bill_to_email'] ) )? sanitize_email(wp_unslash($_POST['bill_to_email'])): '';
    $bill_to_description = ( ! empty( $_POST['bill_to_description'] ) )? sanitize_textarea_field( wp_unslash( $_POST['bill_to_description'])) : '';
    $currency = ( ! empty( $_POST['currency'] ) )? sanitize_text_field(wp_unslash($_POST['currency'])): '';
    $items =  ( ! empty( $_POST['items'] ) ) ? json_decode(sanitize_text_field(wp_unslash($_POST['items'])), true) : json_decode('{}');
    $tax_rate = isset($_POST['tax_rate']) ? floatval($_POST['tax_rate']) : 0;
    $template_style = isset($_POST['template_style']) ? sanitize_text_field($_POST['template_style']) : 'standard';
    $table_class = $template_style === 'blue-accent' ? 'invoice-table-blue' : 'invoice-table';
    $logo_url = ! empty( $_POST['logo_url'] ) ? esc_url_raw( wp_unslash( $_POST['logo_url'] ) ) : '';


   $html = ingen_generate_invoice_html(
       $invoice_number,
       $invoice_date,
       $due_date,
       $bill_from_name,
       $bill_from_email,
       $bill_from_description,
       $bill_to_name,
       $bill_to_email,
       $bill_to_description,
       $currency,
       $tax_rate,
       $items,
       'ingen_render_items_with_precalculated_totals',
       $table_class,
       $template_style,
       $logo_url
   );

     $pdf_url = ingen_generate_invoice_pdf($html, $invoice_number);
     wp_send_json_success(['url' => $pdf_url]);
}


function ingen_generate_invoice_html($invoice_number,
 $invoice_date,
 $due_date,
 $bill_from_name,
 $bill_from_email,
 $bill_from_description,
 $bill_to_name,
 $bill_to_email,
 $bill_to_description,
 $currency,
 $tax_rate,
 $items,
 callable $render_items_callback,
 $table_class = 'invoice-table',
 $template_style = 'standard',
 $logo_url = '')
 {
    ob_start();
    ?> <style>
    body {
        font-family: Arial, sans-serif;
        color: #333;
        font-size: 14px;
        padding: 20px;
    }

.invoice-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 50px;
  margin-bottom: 10px;
}

.invoice-header .logo img {
  max-height: 80px;
  width: auto;
  display: block;
}

.invoice-label {
  font-size: 32px;
  font-weight: bold;
  color: #888;
  letter-spacing: 2px;
  text-align: right;
  margin-left: 20px;
}

.header-line {
  border-top: 2px solid #ccc;
  margin-bottom: 40px;
}

    .info-container {
        display: flex;
        flex-flow: row wrap;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 30px;
        margin-top: 40px;
    }

    .left-info,
    .right-info {
        flex: 0 1 auto;
        margin-left: auto;
    }

    .left-info p,
    .right-info p {
        margin: 5px 0;
        line-height: 1.4;
    }

    .right-info {
        text-align: right;
    }

    table {
        width: 100%;
        border-collapse: collapse;
        margin-bottom: 15px;
    }

    table th,
    table td {
        padding: 6px 0;
        text-align: left;
    }

    table th {
        border-bottom: 2px solid #ccc;
        text-transform: uppercase;
    }

    .totals {
        margin-top: 10px;
    }

    .totals p {
        text-align: right;
        margin: 5px 0;
    }

    .line {
        border-top: 2px solid #ccc;
        margin: 10px 0;
    }

    .right-info {
        text-align: right;
    }

    .info-container p {
        margin: 0;
    }

    <?php if ($template_style === 'blue-accent') : ?>
        .right-info p.invoice-number span {
            color: #2563EB;
            font-weight: bold;
        }

       table thead th{
            border: 0;
        }

       .total-value {
         color: #2563EB;
         font-weight: bold;
       }

       .invoice_header_item{
       padding-left: 1em;
       }

        table thead th {
            background-color: #2563EB;
            color: #ffffff;
            font-weight: normal;
            font-size: 1rem;
        }
    <?php endif; ?>

    .right-info {
        text-align: right;
        margin-top: 0;
    }

    .right-info p {
        margin: 10px 0;
    }
</style>

<div class="invoice-header">
    <div class="logo">
        <?php if ( ! empty( $logo_url ) ) { ?>
            <img src="<?php echo esc_url( $logo_url ); ?>" alt="Logo">
        <?php } ?>
    </div>
    <div class="invoice-label">
        <?php esc_html_e('INVOICE', 'invoice-generator'); ?>
    </div>
</div>

<div class="header-line"></div>



<div class="info-container">
    <div class="right-info">
        <p class="invoice-number">
            <strong><?php esc_html_e('INVOICE', 'invoice-generator'); ?> #<span><?php echo esc_html($invoice_number); ?></span></strong>
        </p>
        <p>
            <strong><?php esc_html_e('INVOICE DATE', 'invoice-generator'); ?>:</strong>
            <?php echo esc_html($invoice_date); ?>
        </p>
        <p>
            <strong><?php esc_html_e('DUE DATE', 'invoice-generator'); ?>:</strong>
            <?php echo esc_html($due_date); ?>
        </p>
    </div>
</div>

<div class="info-container">
    <div class="left-info">
        <p><strong><?php esc_html_e('ISSUED TO', 'invoice-generator'); ?>:</strong> <?php echo esc_html($bill_from_name); ?></p>
        <p><?php echo esc_html($bill_from_email); ?></p>
        <p><?php echo nl2br(esc_html($bill_from_description)); ?></p>
        <br>
        <p><strong><?php esc_html_e('PAY TO', 'invoice-generator'); ?>:</strong> <?php echo esc_html($bill_to_name); ?></p>
        <p><?php echo esc_html($bill_to_email); ?></p>
        <p><?php echo nl2br(esc_html($bill_to_description)); ?></p>
    </div>
</div>
<table>
    <thead>
        <tr>
            <th style="width: 40%;" class='invoice_header_item'><?php esc_html_e('ITEM', 'invoice-generator'); ?></th>
            <th style="width: 15%;"><?php esc_html_e('QTY', 'invoice-generator'); ?></th>
            <th style="width: 20%;"><?php esc_html_e('PRICE', 'invoice-generator'); ?></th>
            <th style="width: 25%;"><?php esc_html_e('TOTAL', 'invoice-generator'); ?></th>
        </tr>
    </thead>
    <tbody> <?php

            $render_items_callback($items, $currency, $tax_rate);
            ?> </tbody>
</table>


<?php

    return ob_get_clean();
}


function ingen_render_items_with_precalculated_totals($items, $currency, $tax_rate) {
    $subtotal = 0;

    foreach ($items as $item) {
        $name = esc_html($item['name']);
        $qty = intval($item['qty']);
        $price = floatval($item['price']);
        $total = floatval($item['total']);
        $subtotal += $total;

        echo "<tr><td class='invoice_header_item'>{$name}</td><td>{$qty}</td><td>{$currency}" . number_format($price, 2) . "</td><td>{$currency}" . number_format($total, 2) . "</td></tr>";
    }

    $tax_amount = round($subtotal * ($tax_rate / 100), 2);
    ?> </tbody>
</table>
<div class="totals">
    <div class="line"></div>
    <p><strong><?php esc_html_e('SUBTOTAL', 'invoice-generator'); ?>:</strong> <?php echo esc_html($currency) . number_format($subtotal, 2); ?></p>
    <p><strong><?php esc_html_e('TAX', 'invoice-generator'); ?> (<?php echo floatval($tax_rate); ?>%):</strong> <?php echo esc_html($currency) . number_format($tax_amount, 2); ?></p>
    <p><strong class="total-amount"><?php esc_html_e('TOTAL', 'invoice-generator'); ?>:</strong> <span class="total-value"><?php echo esc_html($currency) . number_format($subtotal + $tax_amount, 2); ?></span></p>
</div>
<?php
}

function ingen_register_settings() {
    register_setting(
        'ingen_settings_group',
        'ingen_enable_woo',
        [
            'sanitize_callback' => 'ingen_sanitize_checkbox',
            'default'           => true,
        ]
    );

    add_settings_section(
        'ingen_main_section',
        esc_html__('Settings', 'invoice-generator'),
        '__return_false',
        'invoice-generator-settings'
    );

    add_settings_field(
        'ingen_enable_woo',
        esc_html__('WooCommerce Integration', 'invoice-generator'),
        'ingen_enable_woo_render',
        'invoice-generator-settings',
        'ingen_main_section'
    );
}

function ingen_enable_woo_render() {
    $enabled = get_option('ingen_enable_woo', true);
    ?>
    <label for="ingen_enable_woo">
        <input type="checkbox"
               id="ingen_enable_woo"
               name="ingen_enable_woo"
               value="1"
               <?php echo checked(1, $enabled, false); ?> />
        <?php esc_html_e('Enable automatic invoice generation in WooCommerce', 'invoice-generator'); ?>
    </label>
    <?php
}

function ingen_settings_page() {
    ?>
    <div class="wrap">
        <h1><?php esc_html_e('Invoice Generator Settings', 'invoice-generator'); ?></h1>
        <form method="post" action="options.php">
            <?php
            settings_fields('ingen_settings_group');
            do_settings_sections('invoice-generator-settings');
            submit_button();
            ?>
        </form>
    </div>
    <?php
}

function ingen_sanitize_checkbox($input) {
    return $input === '1' ? 1 : 0;
}
