<?php
/**
 * Plugin Name: Consumables Tracker – Excel Export Add-on
 * Description: Adds Excel (CSV) export for consumables item list and transaction reports without modifying the main plugin.
 * Version: 1.0
 * Author: Afif Azmi
 */

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

/**
 * Add menu under Tools
 */
add_action('admin_menu', function () {
    add_management_page(
        'Consumables Export',
        'Consumables Export',
        'manage_options',
        'consumables-export',
        'ct_export_page'
    );
});

/**
 * Export page UI
 */
function ct_export_page() {
    ?>
    <div class="wrap">
        <h1>Consumables – Export to Excel</h1>

        <p>
            <a href="<?php echo admin_url('admin-post.php?action=ct_export_items'); ?>"
               class="button button-primary">
                Export Consumable Item List
            </a>
        </p>

        <p>
            <a href="<?php echo admin_url('admin-post.php?action=ct_export_logs'); ?>"
               class="button">
                Export Transaction / Usage Report
            </a>
        </p>
    </div>
    <?php
}

/**
 * Export Items (Master List)
 */
add_action('admin_post_ct_export_items', function () {
    if (!current_user_can('manage_options')) exit;

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

    $rows = $wpdb->get_results("SELECT * FROM {$table}", ARRAY_A);

    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename=consumables_items_' . date('Ymd_His') . '.csv');

    $out = fopen('php://output', 'w');

    if (!empty($rows)) {
        fputcsv($out, array_keys($rows[0]));
        foreach ($rows as $row) {
            fputcsv($out, $row);
        }
    }

    fclose($out);
    exit;
});

/**
 * Export Logs / Report
 */
add_action('admin_post_ct_export_logs', function () {
    if (!current_user_can('manage_options')) exit;

    global $wpdb;

    // Try to auto-detect logs table
    $tables = $wpdb->get_col("SHOW TABLES LIKE '%consumables_logs%'");
    if (empty($tables)) exit('Logs table not found');

    $table = $tables[0];

    $rows = $wpdb->get_results("
        SELECT 
            item_code,
            item_name,
            qty,
            scan_action,
            po_number,
            purpose,
            user_id,
            created_at
        FROM {$table}
        ORDER BY created_at DESC
    ", ARRAY_A);

    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename=consumables_report_' . date('Ymd_His') . '.csv');

    $out = fopen('php://output', 'w');

    if (!empty($rows)) {
        fputcsv($out, array_keys($rows[0]));
        foreach ($rows as $row) {
            fputcsv($out, $row);
        }
    }

    fclose($out);
    exit;
});
