<?php
/**
 * Plugin Name: Simpinby Invoice Manager – Billing & Invoicing
 * Description: Create, manage, send and download invoices in WordPress.
 * Version: 1.4.0
 * Author: Shouvik Trivedy
 * License: GPLv2 or later
 * Text Domain: simpinby-invoice-manager
 */

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

define('SIMPINBY_PLUGIN_PATH', plugin_dir_path(__FILE__));
define('SIMPINBY_PLUGIN_URL', plugin_dir_url(__FILE__));
define('SIMPINBY_VERSION', '1.3.0');


require_once SIMPINBY_PLUGIN_PATH . 'includes/class-simpinby-activator.php';
require_once SIMPINBY_PLUGIN_PATH . 'includes/class-simpinby-db.php';
require_once SIMPINBY_PLUGIN_PATH . 'admin/class-simpinby-admin-menu.php';

if (file_exists(SIMPINBY_PLUGIN_PATH . 'vendor/autoload.php')) {
    require_once SIMPINBY_PLUGIN_PATH . 'vendor/autoload.php';
}

require_once SIMPINBY_PLUGIN_PATH . 'includes/class-simpinby-ajax.php';
require_once SIMPINBY_PLUGIN_PATH . 'includes/class-simpinby-invoice.php';
require_once SIMPINBY_PLUGIN_PATH . 'includes/class-simpinby-actions.php';
require_once SIMPINBY_PLUGIN_PATH . 'includes/class-simpinby-pdf.php';
require_once SIMPINBY_PLUGIN_PATH . 'includes/class-simpinby-pdf-actions.php';
require_once SIMPINBY_PLUGIN_PATH . 'includes/class-simpinby-mail.php';
require_once SIMPINBY_PLUGIN_PATH . 'includes/class-simpinby-mail-actions.php';
require_once SIMPINBY_PLUGIN_PATH . "includes/class-simpinby-logo.php";
require_once SIMPINBY_PLUGIN_PATH . "includes/class-simpinby-ajax-actions.php";
require_once SIMPINBY_PLUGIN_PATH . 'includes/helpers.php';

function simpinby_add_invoice_rewrite() {
    add_rewrite_rule(
        '^invoice/([a-zA-Z0-9]+)/?$',
        'index.php?simpinby_invoice=$matches[1]',
        'top'
    );
}
add_action('init', 'simpinby_add_invoice_rewrite');

add_filter('query_vars', function ($vars) {
    $vars[] = 'simpinby_invoice';
    return $vars;
});

register_activation_hook(__FILE__, function () {
    SIMPINBY_Activator::activate();
    simpinby_add_invoice_rewrite();
    flush_rewrite_rules();
});


add_action('init', ['SIMPINBY_DB', 'maybe_upgrade']);


add_action('plugins_loaded', function () {

    if (is_admin()) {
        new SIMPINBY_Admin_Menu();
    }

    new SIMPINBY_Ajax();
    new SIMPINBY_Actions();
    new SIMPINBY_PDF_Actions();
    new SIMPINBY_Mail_Actions();
    new SIMPINBY_Ajax_Actions();
});

add_action('template_redirect', function () {

    $token = sanitize_text_field(get_query_var('simpinby_invoice'));

    if (!$token) return;

    // Validate token format
    if (!preg_match('/^[a-zA-Z0-9]+$/', $token)) {
        wp_die("Invalid invoice token");
    }

    global $wpdb;

    $invoice_table = $wpdb->prefix . 'simpinby_invoices';
    $items_table   = $wpdb->prefix . 'simpinby_invoice_items';
    $customers     = $wpdb->prefix . 'simpinby_customers';

    /**
     * FETCH INVOICE
     */
    $invoice = $wpdb->get_row(
        $wpdb->prepare(
            "SELECT inv.*, 
                c.name    AS customer_name,
                c.phone   AS customer_phone,
                c.address AS customer_address,
                c.email   AS customer_email
            FROM $invoice_table inv
            LEFT JOIN $customers c ON c.id = inv.customer_id
            WHERE inv.public_token = %s
            LIMIT 1",
            $token
        ),
        ARRAY_A
    );

    if (empty($invoice) || empty($invoice['id'])) {
        wp_die("Invalid invoice link");
    }

    do_action('simpinby_invoice_viewed', $invoice['id']);

    $items = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT * FROM $items_table WHERE invoice_id=%d",
            $invoice['id']
        ),
        ARRAY_A
    );

    $pdf = isset($_GET['pdf']) ? intval($_GET['pdf']) : 0;

    if ($pdf === 1) {

        if (!class_exists('SIMPINBY_PDF')) {
            require_once SIMPINBY_PLUGIN_PATH . 'includes/class-simpinby-pdf.php';
        }

        // Clean buffers
        while (ob_get_level()) {
            ob_end_clean();
        }

        header('Content-Type: application/pdf');
        header('Content-Disposition: inline; filename="invoice-' . $invoice['id'] . '.pdf"');

        SIMPINBY_PDF::download_invoice_pdf($invoice['id']);
        exit;
    }
    include SIMPINBY_PLUGIN_PATH . 'public/invoice-public.php';
    exit;
});

add_action('wp_enqueue_scripts', function () {
    if (get_query_var('simpinby_invoice')) {
        wp_enqueue_style(
            'simpinby-public-css',
            SIMPINBY_PLUGIN_URL . 'public/assets/public.css',
            [],
            SIMPINBY_VERSION
        );
    }
});

add_action("admin_init", function () {
    SIMPINBY_Invoice::handle_create_invoice();
});