<?php
/**
 * Plugin Name: Consumables Item Editor (Price + Unit)
 * Description: Adds editable Price and Unit fields to consumables items without modifying main plugin.
 * Version: 1.0
 */

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

/**
 * --------------------------------------------------
 * 1. Add columns if not exist
 * --------------------------------------------------
 */
register_activation_hook(__FILE__, function () {
    global $wpdb;

    $table = $wpdb->prefix . 'consumables_items';

    $price_exists = $wpdb->get_var("SHOW COLUMNS FROM {$table} LIKE 'price'");
    if (!$price_exists) {
        $wpdb->query("ALTER TABLE {$table} ADD price DECIMAL(12,2) NOT NULL DEFAULT 0.00");
    }

    $unit_exists = $wpdb->get_var("SHOW COLUMNS FROM {$table} LIKE 'unit'");
    if (!$unit_exists) {
        $wpdb->query("ALTER TABLE {$table} ADD unit VARCHAR(40) NOT NULL DEFAULT 'pcs'");
    }
});

/**
 * --------------------------------------------------
 * 2. Add Edit button + columns in All Items page
 * --------------------------------------------------
 */
add_action('admin_footer', function () {

    if (!isset($_GET['page']) || $_GET['page'] !== 'ct_items') return;

    global $wpdb;
    $table = $wpdb->prefix . 'consumables_items';

    $items = $wpdb->get_results("SELECT id, item_code, price, unit FROM {$table}");

    $data = [];
    foreach ($items as $i) {
        $data[$i->item_code] = [
            'id'    => $i->id,
            'price' => $i->price,
            'unit'  => $i->unit
        ];
    }

    ?>
    <script>
    document.addEventListener('DOMContentLoaded', function () {

        let data = <?php echo json_encode($data); ?>;

        // Add table headers
        let header = document.querySelector('.widefat thead tr');
        if (header) {
            let th1 = document.createElement('th');
            th1.innerText = "Price (RM)";
            header.appendChild(th1);

            let th3 = document.createElement('th');
            th3.innerText = "Edit";
            header.appendChild(th3);
        }

        // Add rows
        document.querySelectorAll('.widefat tbody tr').forEach(function (row) {

            let codeCell = row.querySelector('td');
            if (!codeCell) return;

            let code = codeCell.innerText.trim();

            let item = data[code] || {price:0, unit:'pcs', id:0};

            // Price
            let tdPrice = document.createElement('td');
            tdPrice.innerText = parseFloat(item.price).toFixed(2);
            row.appendChild(tdPrice);

            // Edit button
            let tdEdit = document.createElement('td');
            tdEdit.innerHTML = `
                <button class="button edit-item-btn"
                    data-id="${item.id}"
                    data-price="${item.price}"
                    data-unit="${item.unit}">
                    Edit
                </button>
            `;
            row.appendChild(tdEdit);
        });

        // Modal
        let modal = document.createElement('div');
        modal.style = `
            display:none;
            position:fixed;
            top:50%;
            left:50%;
            transform:translate(-50%,-50%);
            background:#fff;
            padding:20px;
            border:1px solid #ccc;
            z-index:99999;
            width:320px;
        `;

        modal.innerHTML = `
            <h3>Edit Item</h3>

            <label>Price (RM)</label>
            <input type="number" step="0.01" id="editPrice" style="width:100%;padding:8px;">

            <br><br>

            <label>Unit</label>
            <select id="editUnit" style="width:100%;padding:8px;">
                <option value="pcs">pcs</option>
                <option value="kg">kg</option>
                <option value="mtr">mtr</option>
                <option value="ltr">ltr</option>
                <option value="box">box</option>
                <option value="custom">custom</option>
            </select>

            <input type="text" id="customUnit" placeholder="Custom unit"
                style="width:100%;padding:8px;margin-top:6px;display:none;">

            <br><br>

            <button id="saveItem" class="button button-primary">Save</button>
            <button id="closeModal" class="button">Close</button>
        `;

        document.body.appendChild(modal);

        let currentId = null;

        // Open modal
        document.addEventListener('click', function (e) {
            if (e.target.classList.contains('edit-item-btn')) {

                currentId = e.target.dataset.id;

                document.getElementById('editPrice').value = e.target.dataset.price;
                document.getElementById('editUnit').value = e.target.dataset.unit;

                modal.style.display = 'block';
            }
        });

        // Unit toggle
        document.getElementById('editUnit').addEventListener('change', function () {
            document.getElementById('customUnit').style.display =
                this.value === 'custom' ? 'block' : 'none';
        });

        // Close
        document.getElementById('closeModal').onclick = function () {
            modal.style.display = 'none';
        };

        // Save
        document.getElementById('saveItem').onclick = function () {

            let price = document.getElementById('editPrice').value;
            let unitSelect = document.getElementById('editUnit').value;
            let customUnit = document.getElementById('customUnit').value;

            let unit = (unitSelect === 'custom') ? customUnit : unitSelect;

            fetch(ajaxurl + '?action=ct_update_item', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'id=' + currentId + '&price=' + price + '&unit=' + unit
            })
            .then(res => res.json())
            .then(res => {
                if (res.success) {
                    alert('Updated successfully');
                    location.reload();
                } else {
                    alert('Failed: ' + res.data);
                }
            });
        };

    });
    </script>
    <?php
});

/**
 * --------------------------------------------------
 * 3. AJAX: Save Price + Unit
 * --------------------------------------------------
 */
add_action('wp_ajax_ct_update_item', function () {

    if (!current_user_can('manage_options')) {
        wp_send_json_error('No permission');
    }

    global $wpdb;

    $id    = intval($_POST['id']);
    $price = floatval($_POST['price']);
    $unit  = sanitize_text_field($_POST['unit']);

    if (!$id) {
        wp_send_json_error('Invalid ID');
    }

    $table = $wpdb->prefix . 'consumables_items';

    $updated = $wpdb->update(
        $table,
        [
            'price' => $price,
            'unit'  => $unit
        ],
        ['id' => $id],
        ['%f','%s'],
        ['%d']
    );

    if ($updated === false) {
        wp_send_json_error($wpdb->last_error);
    }

    wp_send_json_success(true);
});