<?php

if (!defined('ABSPATH'))
exit;
class DevsAccounting_Shortcode {
    public function __construct() {
        add_shortcode('devsaccounting_invoice', [$this, 'devsaccounting_invoice_shortcode']);    
    }

    public function enqueue_shortcode_script(){
        add_filter('the_content', [$this, 'checkShortcodesAndEnqueueScript']);
    }

    public function checkShortcodesAndEnqueueScript($content) {
        $shortcodes_to_check = ['devsaccounting_invoice', 'devsaccounting_purchase'];
        
        // if (has_shortcode($content, $shortcode) && !is_page('login') && !is_page('register')) {
         
        //     wp_enqueue_style(
        //         'devs-accounting-front-style', 
        //         DEVSACCOUNTING_URL . 'build/index.css'
        //     );
        // }
    
        
        // if (is_page('login') || is_page('register') || is_user_logged_in()) {
        //     wp_enqueue_style(
        //         'devs-accounting-front-style', 
        //         DEVSACCOUNTING_URL . 'build/index.css'
        //     );
        // }
        $shortcodes_exists = false;

        foreach ($shortcodes_to_check as $shortcode) {
            if (has_shortcode($content, $shortcode)) {
                $shortcodes_exists = true;
                break;
            }
        }
        if ($shortcodes_exists) {
            wp_enqueue_script('devs-accounting-front-js', DEVSACCOUNTING_URL . 'build/frontend.js', ['wp-element'],
                  wp_rand(), 
                  true);
            wp_enqueue_style('devs-accounting-front-style', DEVSACCOUNTING_URL . 'build/index.css');
          }
          wp_localize_script('devs-accounting-front-js', 'devsAccountingApi', [
            'apiUrl' => home_url('/wp-json'),
            'nonce' => wp_create_nonce('wp_rest'),
          ]);
        return $content;
    }

    public function devsaccounting_invoice_shortcode($atts) {
        if (is_page('login') || is_page('register')) {
            return ''; 
        }

        /*global $wpdb;        
        
        // Define default attributes and parse incoming attributes
        $atts = shortcode_atts(
            ['uuid' => 56], // Default UUID
            $atts,
            'devsaccounting_invoice'
        );

        // $uuid = intval($atts['uuid']);
        $uuid = isset($_GET['inv']) ? sanitize_text_field($_GET['inv']) : null;
        // echo $uuid;exit;
        // if ($uuid <= 0) {
        //     return 'Invalid invoice UUID.';
        // }

        // Table names
        $table_name_invoices = $wpdb->prefix . 'dac_invoices';
        $table_name_invoice_items = $wpdb->prefix . 'dac_invoice_items';
        $table_name_contacts = $wpdb->prefix . 'dac_contacts';
        
        // Fetch the invoice with related data
        $invoice = $wpdb->get_row($wpdb->prepare(
            "SELECT invoices.*, invoice_items.invoice_items_data AS item_data, 
            contacts.name AS contact_name, contacts.email AS contact_email
            FROM $table_name_invoices AS invoices
            INNER JOIN $table_name_contacts AS contacts 
            ON invoices.contact_id = contacts.id 
            INNER JOIN $table_name_invoice_items AS invoice_items 
            ON invoices.id = invoice_items.invoice_no   
            WHERE invoices.invoice_no = %s", 
            $uuid
        ));


        // $transactionObj = new DevsAccounting_Transactions();

        // $transactions = $transactionObj->get_single_transaction_invoice(array('id' => $invoice->id));

        // // Extract data from WP_REST_Response object
        // $transactionData = $transactions->get_data(); // Use get_data() to get the actual data

        // $totalAmount = 0;

        // // Loop through the data array and sum the amount
        // foreach ($transactionData as $item) {
        //     $totalAmount += $item->amount;
        //     print_r($totalAmount);
        // }


        $transactionObj = new DevsAccounting_Transactions();

        $transactions = $transactionObj->get_single_transaction_invoice(array('id' => $invoice->id));
        $totalAmount = 0;
        if (!empty($transactions) && !is_wp_error($transactions)) {
            // Use array_reduce to sum the amounts
            $totalAmount = array_reduce($transactions->data, function($sum, $item) {
                return $sum + $item->amount;
            }, 0); // Initial sum is 0
        }        
        $settings = get_option('devsaccounting_settings');

        // Check if the settings are valid JSON
        $settings_data = json_decode($settings, true);

        if (json_last_error() !== JSON_ERROR_NONE || empty($settings_data)) {
            // If the JSON is invalid or empty, handle the error or use a default value
            $settings_data = []; // Default value if JSON is invalid or not available
        } */
        // Start output buffering
        ob_start();

        ?>
        <div class="devs-accounting-wrapper">
            <div id="devsaccounting-publicInvoice"></div>
        </div>
        <?php


        /*if ($invoice) {
            ?>
            <div class="devs-accounting-wrapper">
                <div class="max-w-9xl px-4 sm:px-6 lg:px-8 mx-auto my-4 sm:my-10">
                    <div class="sm:w-11/12 lg:w-4/4 mx-auto">
                        <div class="flex flex-col p-4 sm:p-10 bg-white shadow-md rounded-xl">
                            <div class="flex justify-between">
                                <div>
                                    <p class="mt-2 text-lg md:text-xl font-semibold text-blue-600">
                                        <?php echo isset($settings_data['company_name']) ? esc_html($settings_data['company_name']) : ''; ?>
                                    </p>
                                    <p class="mt-2 text-md font-semibold">
                                        <?php echo isset($settings_data['address']) ? esc_html($settings_data['address']) : ''; ?>
                                    </p>
                                    <p class="mt-2 text-md font-semibold">
                                        <?php echo isset($settings_data['phone']) ? esc_html($settings_data['phone']) : '';  ?>
                                    </p>
                                    <p class="mt-2 text-xl font-semibold">
                                        Invoice to:
                                    </p>
                                    <p class="mt-2 text-md font-semibold">
                                    <?php echo esc_html($invoice->contact_name); ?>
                                    </p>
                                    <p class="mt-2 text-md font-semibold">
                                    <?php echo esc_html($invoice->contact_email); ?>
                                    </p>
                                </div>
                                <div class="text-end">
                                    <p class="text-2xl md:text-3xl font-semibold text-gray-800">
                                        <?php echo esc_html($invoice->invoice_no); ?>
                                    </p>
                                </div>
                            </div>

                            <div class="mt-8 grid grid-cols-2 gap-3">
                                <div></div>
                                <div class="text-end space-y-2">
                                    <dl class="grid grid-cols-2 gap-x-3">
                                        <dt class="font-semibold text-gray-800">Invoice date:</dt>
                                        <dd class="text-gray-500"><?php echo esc_html(gmdate('M d, Y', strtotime($invoice->issued_at))); ?></dd>
                                    </dl>
                                    <dl class="grid grid-cols-2 gap-x-3">
                                        <dt class="font-semibold text-gray-800">Due date:</dt>
                                        <dd class="text-gray-500"><?php echo esc_html(gmdate('M d, Y', strtotime($invoice->due_at))); ?></dd>
                                    </dl>
                                </div>
                            </div>

                            <div class="mt-6 border border-gray-200 p-4 rounded-lg space-y-4">
                                <div class="grid grid-cols-4">
                                    <div class="sm:col-span-2 text-xs font-medium text-gray-500 uppercase">
                                        Item
                                    </div>
                                    <div class="text-start text-xs font-medium text-gray-500 uppercase">Qty</div>
                                    <div class="text-end text-xs font-medium text-gray-500 uppercase">Rate</div>
                                </div>
                                <div class="block border-b border-gray-200"></div>
                                
                                <?php 
                                $item_data = json_decode($invoice->item_data, true);
                                $subtotal = 0; // Initialize subtotal
                                if (is_array($item_data)) {
                                    foreach ($item_data as $item) {
                                        $line_total = $item['quantity'] * $item['sale_price'];
                                        $subtotal += $line_total; // Calculate subtotal
                                        $total = $subtotal-$invoice->discount;
                                        ?>
                                        <div class="grid grid-cols-4">
                                            <div class="col-span-2">
                                                <?php echo esc_html($item['name']); ?>
                                            </div>
                                            <div>
                                                <?php echo esc_html($item['quantity']); ?>
                                            </div>
                                            <div class="text-end">
                                                <?php echo esc_html(number_format($item['sale_price'], 2)); ?>
                                            </div>
                                        </div>
                                        <?php
                                    }
                                } else {
                                    echo "<p> No items found in this invoice.</p>";
                                }
                                ?>
                            </div>

                            <div class="mt-8 flex sm:justify-end">
                                <div class="w-full max-w-2xl sm:text-end space-y-2">
                                    <div class="grid grid-cols-1 sm:grid-cols-1 gap-3 sm:gap-2">
                                        <dl class="grid sm:grid-cols-5 gap-x-3">
                                            <dt class="col-span-3 font-semibold text-gray-800">Subtotal:</dt>
                                            <dd class="col-span-2 text-gray-500"><?php echo esc_html(number_format($subtotal, 2)); ?></dd>
                                        </dl>
                                        <?php if ($invoice->discount > 0): ?>
                                            <dl class="grid sm:grid-cols-5 gap-x-3">
                                                <dt class="col-span-3 font-semibold text-gray-800">Discount:</dt>
                                                <dd class="col-span-2 text-gray-500"><?php echo esc_html(number_format($invoice->discount, 2)); ?></dd>
                                            </dl>
                                        <?php endif; ?>

                                        <dl class="grid sm:grid-cols-5 gap-x-3">
                                            <dt class="col-span-3 font-semibold text-gray-800">Total:</dt>
                                            <dd class="col-span-2 text-gray-500"><?php echo esc_html(number_format($total, 2)); ?></dd> <!-- Assuming no additional charges -->
                                        </dl>
                                        <dl class="grid sm:grid-cols-5 gap-x-3">
                                            <dt class="col-span-3 font-semibold text-gray-800">Paid:</dt>
                                            <dd class="col-span-2 text-gray-500"><?php echo esc_html(number_format($total-($total-$totalAmount), 2)); ?></dd> <!-- Assuming no additional charges -->
                                        </dl>
                                        <dl class="grid sm:grid-cols-5 gap-x-3">
                                            <dt class="col-span-3 font-semibold text-gray-800">Dues:</dt>
                                            <dd class="col-span-2 text-gray-500"><?php echo esc_html(number_format($total-$totalAmount, 2)); ?></dd> <!-- Assuming no additional charges -->
                                        </dl>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php
        } else {
            // If no invoice found
            ?>
            <div class="my-unique-plugin-wrapper-class">
                No invoice found for UUID: <?php echo esc_html($uuid); ?>
            </div>
            <?php
        }
*/
        // Return the buffered content
        return ob_get_clean();
    }
}

// Instantiate the class
$devsaccounting_shortcode = new DevsAccounting_Shortcode();
