<?php
/**
 * Plugin Name: CT Adjustment System (Editor + Logger Combined)
 * Description: Edit quantity from items page + automatic adjustment logging (no main plugin change).
 * Version: 1.0
 */

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

/**
 * --------------------------------------------------
 * 1. CREATE ADJUSTMENT TABLE
 * --------------------------------------------------
 */
register_activation_hook(__FILE__, function () {

    global $wpdb;

    $table = $wpdb->prefix . 'consumables_adjustment_logs';
    $charset = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE IF NOT EXISTS $table (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        item_code VARCHAR(100),
        item_name VARCHAR(255),
        old_qty DECIMAL(12,2),
        new_qty DECIMAL(12,2),
        qty_change DECIMAL(12,2),
        reason TEXT,
        user_id BIGINT,
        created_at DATETIME,
        PRIMARY KEY (id)
    ) $charset;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
});

/**
 * --------------------------------------------------
 * 2. UI: ADD EDIT BUTTON IN 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, item_name, balance FROM $table");

    $data = [];

    foreach ($items as $i) {
        $data[$i->item_code] = [
            'id' => $i->id,
            'item_name' => $i->item_name,
            'balance' => $i->balance
        ];
    }
?>
<script>
document.addEventListener('DOMContentLoaded', function () {

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

    // add column
    let header = document.querySelector('.widefat thead tr');
    if (header && !document.getElementById('adj-header')) {
        let th = document.createElement('th');
        th.innerText = "Adjust";
        th.id = "adj-header";
        header.appendChild(th);
    }

    // add buttons
    document.querySelectorAll('.widefat tbody tr').forEach(function (row) {

        if (row.querySelector('.adj-btn')) return;

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

        let code = codeCell.innerText.trim();
        let item = data[code];

        if (!item) return;

        let td = document.createElement('td');

        td.innerHTML = `
            <button class="button adj-btn"
                data-id="${item.id}"
                data-code="${code}"
                data-name="${item.item_name}"
                data-balance="${item.balance}">
                Edit Qty
            </button>
        `;

        row.appendChild(td);
    });

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

    modal.innerHTML = `
        <h3>Adjust Quantity</h3>

        <label>New Balance</label>
        <input type="number" id="newBal" style="width:100%;padding:8px;">

        <br><br>

        <label>Reason</label>
        <textarea id="reason" style="width:100%;padding:8px;"></textarea>

        <br><br>

        <button id="saveAdj" class="button button-primary">Save</button>
        <button id="closeAdj" class="button">Close</button>
    `;

    document.body.appendChild(modal);

    let current = null;
    let oldBal = 0;

    document.addEventListener('click', function (e) {

        if (e.target.classList.contains('adj-btn')) {

            current = e.target.dataset.id;
            oldBal = parseFloat(e.target.dataset.balance);

            document.getElementById('newBal').value = oldBal;
            document.getElementById('reason').value = '';

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

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

    document.getElementById('saveAdj').onclick = function () {

        let newBal = parseFloat(document.getElementById('newBal').value);
        let reason = document.getElementById('reason').value.trim();

        if (reason === '') {
            alert('Reason required');
            return;
        }

        fetch(ajaxurl + '?action=ct_adjust_save', {
            method: 'POST',
            headers: {'Content-Type':'application/x-www-form-urlencoded'},
            body:
                'id=' + current +
                '&old=' + oldBal +
                '&new=' + newBal +
                '&reason=' + encodeURIComponent(reason)
        })
        .then(r => r.json())
        .then(res => {
            if (res.success) {
                alert('Updated');
                location.reload();
            } else {
                alert(res.data);
            }
        });
    };

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

/**
 * --------------------------------------------------
 * 3. AJAX SAVE + LOG
 * --------------------------------------------------
 */
add_action('wp_ajax_ct_adjust_save', function () {

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

    global $wpdb;

    $items = $wpdb->prefix . 'consumables_items';
    $logs  = $wpdb->prefix . 'consumables_adjustment_logs';

    $id = intval($_POST['id']);
    $old = floatval($_POST['old']);
    $new = floatval($_POST['new']);
    $reason = sanitize_text_field($_POST['reason']);

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

    // update balance
    $wpdb->update(
        $items,
        ['balance' => $new],
        ['id' => $id],
        ['%f'],
        ['%d']
    );

    // get item
    $item = $wpdb->get_row(
        $wpdb->prepare("SELECT item_code,item_name FROM $items WHERE id=%d", $id)
    );

    if (!$item) {
        wp_send_json_error('Item not found');
    }

    $change = $new - $old;

    // log
    $wpdb->insert($logs, [
        'item_code'   => $item->item_code,
        'item_name'   => $item->item_name,
        'old_qty'     => $old,
        'new_qty'     => $new,
        'qty_change'  => $change,
        'reason'      => $reason,
        'user_id'     => get_current_user_id(),
        'created_at'  => current_time('mysql')
    ]);

    wp_send_json_success(true);
});

/**
 * --------------------------------------------------
 * 4. ADJUSTMENT REPORT MENU
 * --------------------------------------------------
 */
add_action('admin_menu', function () {

    add_submenu_page(
        'ct_items',
        'Adjustment Report',
        'Adjustment Report',
        'manage_options',
        'ct_adjustment_report',
        function () {

            global $wpdb;

            $logs = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}consumables_adjustment_logs ORDER BY id DESC");
            ?>

            <div class="wrap">
                <h1>Adjustment Report</h1>

                <table class="widefat striped">
                    <thead>
                        <tr>
                            <th>Item Code</th>
                            <th>Item Name</th>
                            <th>Old</th>
                            <th>New</th>
                            <th>Change</th>
                            <th>Reason</th>
                            <th>User</th>
                            <th>Date</th>
                        </tr>
                    </thead>
                    <tbody>

                    <?php foreach ($logs as $l): ?>
                        <tr>
                            <td><?= esc_html($l->item_code) ?></td>
                            <td><?= esc_html($l->item_name) ?></td>
                            <td><?= esc_html($l->old_qty) ?></td>
                            <td><?= esc_html($l->new_qty) ?></td>
                            <td style="color:<?= ($l->qty_change >= 0 ? 'green':'red') ?>">
                                <?= esc_html($l->qty_change) ?>
                            </td>
                            <td><?= esc_html($l->reason) ?></td>
                            <td><?= esc_html($l->user_id) ?></td>
                            <td><?= esc_html($l->created_at) ?></td>
                        </tr>
                    <?php endforeach; ?>

                    </tbody>
                </table>
            </div>

            <?php
        }
    );
});