<?php
/**
 * Plugin Name: Digital Purchase Request Form
 * Description: Simple digital PR form using existing QR consumable items, with custom item option and printable approval form via frontend shortcode. Includes Wide Desktop Breakout and Fix for Number Inputs.
 * Version: 2.4.0
 * Author: JSkills Finance
 */

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

register_activation_hook(__FILE__, 'dpr_install');

function dpr_install() {
    global $wpdb;
    $charset = $wpdb->get_charset_collate();

    $requests = $wpdb->prefix . 'dpr_requests';
    $items = $wpdb->prefix . 'dpr_request_items';

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';

    dbDelta("CREATE TABLE $requests (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        request_no VARCHAR(50) NOT NULL,
        request_date DATETIME NOT NULL,
        requestor_name VARCHAR(150) NOT NULL,
        department VARCHAR(150) NOT NULL,
        required_date DATE NULL,
        purpose TEXT NOT NULL,
        remarks TEXT NULL,
        status VARCHAR(50) NOT NULL DEFAULT 'Submitted',
        created_by BIGINT UNSIGNED NULL,
        created_at DATETIME NOT NULL,
        updated_at DATETIME NULL,
        PRIMARY KEY (id),
        UNIQUE KEY request_no (request_no)
    ) $charset;");

    dbDelta("CREATE TABLE $items (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        request_id BIGINT UNSIGNED NOT NULL,
        consumable_item_id BIGINT UNSIGNED NULL,
        item_name VARCHAR(255) NOT NULL,
        unit VARCHAR(50) NULL,
        qty_requested DECIMAL(15,2) NOT NULL DEFAULT 0,
        item_type VARCHAR(50) NOT NULL DEFAULT 'Existing',
        remarks TEXT NULL,
        PRIMARY KEY (id),
        KEY request_id (request_id)
    ) $charset;");
}

function dpr_get_consumable_items_frontend() {
    global $wpdb;
    $table = $wpdb->prefix . 'consumables_items';

    if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) !== $table) {
        return [];
    }

    $columns = $wpdb->get_results("SHOW COLUMNS FROM $table");
    $col_names = array_map(fn($c) => $c->Field, $columns);

    $name_col = in_array('item_name', $col_names) ? 'item_name' : (in_array('name', $col_names) ? 'name' : '');
    $unit_col = in_array('unit', $col_names) ? 'unit' : (in_array('uom', $col_names) ? 'uom' : '');
    $stock_col = in_array('current_stock', $col_names) ? 'current_stock' : (in_array('balance', $col_names) ? 'balance' : (in_array('quantity', $col_names) ? 'quantity' : ''));

    if (!$name_col) return [];

    $select = "id, `$name_col` AS item_name";
    $select .= $unit_col ? ", `$unit_col` AS unit" : ", '' AS unit";
    $select .= $stock_col ? ", `$stock_col` AS current_stock" : ", '' AS current_stock";

    return $wpdb->get_results("SELECT $select FROM $table ORDER BY `$name_col` ASC");
}

add_action('template_redirect', function() {
    if (isset($_GET['dpr_action']) && $_GET['dpr_action'] === 'print') {
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        
        if (!is_user_logged_in()) {
            wp_die('You must be logged in to print forms.');
        }

        if (!isset($_GET['_wpnonce']) || !wp_verify_nonce($_GET['_wpnonce'], 'dpr_print_' . $id)) {
            wp_die('Security check failed or print link expired.');
        }

        global $wpdb;
        $request_table = $wpdb->prefix . 'dpr_requests';
        $item_table = $wpdb->prefix . 'dpr_request_items';

        $request = $wpdb->get_row($wpdb->prepare("SELECT * FROM $request_table WHERE id = %d", $id));
        if (!$request) wp_die('Request not found.');

        $items = $wpdb->get_results($wpdb->prepare("SELECT * FROM $item_table WHERE request_id = %d", $id));
        
        ?>
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Print PR - <?php echo esc_html($request->request_no); ?></title>
            <style>
                body { font-family: Arial, sans-serif; font-size: 13px; color:#000; margin:30px; line-height: 1.4; }
                .header { text-align:center; margin-bottom:25px; }
                .header h1 { margin:0; font-size:20px; text-transform:uppercase; }
                .header h2 { margin:5px 0 0; font-size:16px; font-weight:normal; }
                table { width:100%; border-collapse:collapse; margin-bottom:18px; }
                th, td { border:1px solid #000; padding:7px; vertical-align:top; text-align: left; }
                .no-border td { border:none; padding:4px; }
                .label { font-weight:bold; width:18%; }
                .signature td { height:110px; text-align:center; vertical-align:bottom; }
                .note { font-size:11px; margin-top:10px; color: #333; }
                .print-btn { margin-bottom:20px; padding: 8px 16px; background: #0073aa; color: #fff; border: none; cursor: pointer; border-radius: 4px; font-weight: bold;}
                @media print {
                    .print-btn { display:none; }
                    body { margin:10mm; }
                }
            </style>
        </head>
        <body>
        <button class="print-btn" onclick="window.print()">Print This Form</button>

        <div class="header">
            <h1>Johor Skills Development Centre Sdn Bhd</h1>
            <h2>Purchase Request / Consumable Request Form</h2>
        </div>

        <table class="no-border">
            <tr>
                <td class="label">Request No.</td>
                <td>: <?php echo esc_html($request->request_no); ?></td>
                <td class="label">Request Date</td>
                <td>: <?php echo esc_html(date('d/m/Y', strtotime($request->request_date))); ?></td>
            </tr>
            <tr>
                <td class="label">Requestor</td>
                <td>: <?php echo esc_html($request->requestor_name); ?></td>
                <td class="label">Department</td>
                <td>: <?php echo esc_html($request->department); ?></td>
            </tr>
            <tr>
                <td class="label">Required Date</td>
                <td>: <?php echo $request->required_date ? esc_html(date('d/m/Y', strtotime($request->required_date))) : '-'; ?></td>
                <td class="label">Status</td>
                <td>: <?php echo esc_html($request->status); ?></td>
            </tr>
        </table>

        <table>
            <tr>
                <th style="width:20%">Request For / Purpose</th>
                <td><?php echo nl2br(esc_html($request->purpose)); ?></td>
            </tr>
            <tr>
                <th>Remarks</th>
                <td><?php echo nl2br(esc_html($request->remarks)); ?></td>
            </tr>
        </table>

        <table>
            <thead>
                <tr>
                    <th style="width:5%">No.</th>
                    <th>Item</th>
                    <th style="width:12%">Unit</th>
                    <th style="width:12%">Qty</th>
                    <th style="width:18%">Item Type</th>
                    <th style="width:25%">Remarks</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($items): foreach ($items as $index => $item): ?>
                    <tr>
                        <td><?php echo intval($index + 1); ?></td>
                        <td><?php echo esc_html($item->item_name); ?></td>
                        <td><?php echo esc_html($item->unit); ?></td>
                        <td><?php echo esc_html($item->qty_requested); ?></td>
                        <td><?php echo esc_html($item->item_type); ?></td>
                        <td><?php echo esc_html($item->remarks); ?></td>
                    </tr>
                <?php endforeach; else: ?>
                    <tr><td colspan="6">No item listed.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>

        <p class="note">
            <strong>Note:</strong> This form is for request recording only. Stock balance will not be reduced by this request. Stock issuance must be recorded separately through the QR OUT transaction.
        </p>

        <table class="signature">
            <tr>
                <th>Requested By</th>
                <th>Verified By</th>
                <th>Approved By</th>
            </tr>
            <tr>
                <td>
                    Signature: ___________________<br><br>
                    Name: _______________________<br><br>
                    Date: ________________________
                </td>
                <td>
                    Signature: ___________________<br><br>
                    Name: _______________________<br><br>
                    Date: ________________________
                </td>
                <td>
                    Signature: ___________________<br><br>
                    Name: _______________________<br><br>
                    Date: ________________________
                </td>
            </tr>
        </table>
        </body>
        </html>
        <?php
        exit;
    }
});

add_shortcode('dpr_form', function() {
    if (!is_user_logged_in()) {
        return '<p class="dpr-alert dpr-alert-danger">You must be logged in to view and submit purchase requests.</p>';
    }

    global $wpdb;
    $output = '';
    $current_user = wp_get_current_user();
    $consumables = dpr_get_consumable_items_frontend();

    $request_table = $wpdb->prefix . 'dpr_requests';
    $item_table = $wpdb->prefix . 'dpr_request_items';

    if (isset($_GET['dpr_action_status']) && isset($_GET['req_id']) && isset($_GET['_wpnonce'])) {
        $req_id = intval($_GET['req_id']);
        if (current_user_can('manage_options') && wp_verify_nonce($_GET['_wpnonce'], 'dpr_status_' . $req_id)) {
            $new_status = ($_GET['dpr_action_status'] === 'complete') ? 'Completed' : 'Submitted';
            $wpdb->update($request_table, ['status' => $new_status, 'updated_at' => current_time('mysql')], ['id' => $req_id]);
            $output .= '<div class="dpr-alert dpr-alert-success">Request status successfully changed to <strong>' . $new_status . '</strong>.</div>';
        }
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['dpr_frontend_nonce'])) {
        if (!wp_verify_nonce($_POST['dpr_frontend_nonce'], 'dpr_save_frontend_request')) {
            $output .= '<div class="dpr-alert dpr-alert-danger">Security validation failed. Please try again.</div>';
        } else {
            $wpdb->insert($request_table, [
                'request_no' => 'PENDING',
                'request_date' => current_time('mysql'),
                'requestor_name' => sanitize_text_field($_POST['requestor_name']),
                'department' => sanitize_text_field($_POST['department']),
                'required_date' => !empty($_POST['required_date']) ? sanitize_text_field($_POST['required_date']) : null,
                'purpose' => sanitize_textarea_field($_POST['purpose']),
                'remarks' => sanitize_textarea_field($_POST['remarks']),
                'status' => 'Submitted',
                'created_by' => $current_user->ID,
                'created_at' => current_time('mysql')
            ]);

            $request_id = $wpdb->insert_id;
            $request_no = 'PR-' . date('Y') . '-' . str_pad($request_id, 4, '0', STR_PAD_LEFT);
            $wpdb->update($request_table, ['request_no' => $request_no], ['id' => $request_id]);

            if (!empty($_POST['item_name']) && is_array($_POST['item_name'])) {
                foreach ($_POST['item_name'] as $i => $name) {
                    $name = sanitize_text_field($name);
                    if ($name === '') continue;

                    $item_id = intval($_POST['consumable_item_id'][$i] ?? 0);
                    $item_type = $item_id > 0 ? 'Existing Item' : 'Custom / New Item';

                    $wpdb->insert($item_table, [
                        'request_id' => $request_id,
                        'consumable_item_id' => $item_id > 0 ? $item_id : null,
                        'item_name' => $name,
                        'unit' => sanitize_text_field($_POST['unit'][$i] ?? ''),
                        'qty_requested' => floatval($_POST['qty_requested'][$i] ?? 0),
                        'item_type' => $item_type,
                        'remarks' => sanitize_textarea_field($_POST['item_remarks'][$i] ?? '')
                    ]);
                }
            }

            $print_url = add_query_arg(['dpr_action' => 'print', 'id' => $request_id], home_url($_SERVER['REQUEST_URI']));
            $nonce_print_url = wp_nonce_url($print_url, 'dpr_print_' . $request_id);

            $output .= '<div class="dpr-alert dpr-alert-success">';
            $output .= '<strong>Success!</strong> Request successfully submitted with number: <strong>' . esc_html($request_no) . '</strong>.<br>';
            $output .= '<a target="_blank" class="dpr-print-link-btn" href="' . esc_url($nonce_print_url) . '">🖨️ Click Here to Print Form Approval</a>';
            $output .= '</div>';
        }
    }

    $page_url = home_url($_SERVER['REQUEST_URI']);
    if (current_user_can('manage_options')) {
        $logs = $wpdb->get_results("SELECT * FROM $request_table ORDER BY id DESC");
    } else {
        $logs = $wpdb->get_results($wpdb->prepare("SELECT * FROM $request_table WHERE created_by = %d ORDER BY id DESC", $current_user->ID));
    }

    ob_start();
    ?>
    <style>
        :root {
            --dpr-primary: #0056b3;
            --dpr-primary-hover: #004085;
            --dpr-bg: #ffffff;
            --dpr-bg-alt: #f8f9fa;
            --dpr-border: #e2e8f0;
            --dpr-text: #334155;
            --dpr-text-muted: #64748b;
            --dpr-success: #22c55e;
            --dpr-warning: #f59e0b;
        }
        
        /* Breakout layout container strategy to force full screen span across boxed themes */
        .dpr-frontend-wrap {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            color: var(--dpr-text);
            line-height: 1.5;
            margin-bottom: 50px;
            width: 100% !important;
            max-width: 1250px !important;
            margin-left: auto !important;
            margin-right: auto !important;
            box-sizing: border-box;
        }
        .dpr-card {
            background: var(--dpr-bg);
            border: 1px solid var(--dpr-border);
            border-radius: 8px;
            box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05);
            padding: 30px;
            margin-bottom: 40px;
        }
        .dpr-section-title {
            font-size: 24px;
            font-weight: 700;
            margin-top: 0;
            margin-bottom: 22px;
            color: #1e293b;
            border-bottom: 2px solid var(--dpr-bg-alt);
            padding-bottom: 12px;
        }
        .dpr-form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 24px;
            margin-bottom: 24px;
        }
        .dpr-form-group {
            display: flex;
            flex-direction: column;
        }
        .dpr-form-group.full-width {
            grid-column: 1 / -1;
        }
        .dpr-label {
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 8px;
            color: #475569;
        }
        .dpr-input, .dpr-select, .dpr-textarea {
            width: 100% !important;
            padding: 12px 16px !important;
            border: 1px solid #cbd5e1 !important;
            border-radius: 6px !important;
            background-color: #fff !important;
            font-size: 15px !important;
            color: var(--dpr-text) !important;
            box-sizing: border-box;
            transition: border-color 0.2s, box-shadow 0.2s;
        }
        
        /* Fix native HTML5 browser numeric spin actions from conflict overrides */
        .dpr-input-number {
            -moz-appearance: textfield !important; /* Firefox fallback */
        }
        .dpr-input-number::-webkit-outer-spin-button,
        .dpr-input-number::-webkit-inner-spin-button {
            -webkit-appearance: inner-spin-button !important;
            opacity: 1 !important;
            background: transparent;
            height: auto;
        }

        .dpr-input:focus, .dpr-select:focus, .dpr-textarea:focus {
            border-color: var(--dpr-primary) !important;
            outline: none !important;
            box-shadow: 0 0 0 3px rgba(0,86,179,0.15) !important;
        }
        
        /* Table Layout Engine */
        .dpr-table-container {
            overflow-x: auto;
            margin-bottom: 20px;
            border: 1px solid var(--dpr-border);
            border-radius: 6px;
        }
        .dpr-table {
            width: 100%;
            border-collapse: collapse;
            background: #fff;
            margin: 0 !important;
        }
        .dpr-table th {
            background: var(--dpr-bg-alt);
            color: #475569;
            font-weight: 600;
            padding: 14px 16px;
            font-size: 14px;
            border-bottom: 2px solid var(--dpr-border);
            text-align: left;
        }
        .dpr-table td {
            padding: 14px 16px;
            border-bottom: 1px solid var(--dpr-border);
            font-size: 15px;
            vertical-align: middle;
        }
        
        /* Mobile Device Flex-Stack System Rules */
        @media (max-width: 850px) {
            .dpr-table-responsive-stack thead {
                display: none;
            }
            .dpr-table-responsive-stack tbody tr {
                display: block;
                background: #f8f9fa;
                border: 1px solid var(--dpr-border);
                border-radius: 8px;
                padding: 18px;
                margin-bottom: 18px;
            }
            .dpr-table-responsive-stack tbody td {
                display: flex;
                flex-direction: column;
                padding: 8px 0;
                border: none;
                width: 100% !important;
            }
            .dpr-table-responsive-stack tbody td::before {
                content: attr(data-label);
                font-size: 11px;
                font-weight: 700;
                color: var(--dpr-text-muted);
                margin-bottom: 5px;
                text-transform: uppercase;
                letter-spacing: 0.5px;
            }
            .dpr-table-responsive-stack tbody td.dpr-actions-cell {
                flex-direction: row;
                justify-content: flex-end;
                border-top: 1px dashed var(--dpr-border);
                margin-top: 12px;
                padding-top: 12px;
            }
            .dpr-table-responsive-stack tbody td.dpr-actions-cell::before {
                display: none;
            }
        }

        .dpr-btn {
            background: var(--dpr-primary);
            color: #fff !important;
            border: none;
            padding: 12px 24px;
            font-size: 15px;
            font-weight: 600;
            border-radius: 6px;
            cursor: pointer;
            transition: background 0.2s;
            display: inline-flex;
            align-items: center;
            text-decoration: none !important;
        }
        .dpr-btn:hover {
            background: var(--dpr-primary-hover);
        }
        .dpr-btn-secondary {
            background: #64748b;
        }
        .dpr-btn-secondary:hover {
            background: #475569;
        }
        .dpr-btn-sm {
            padding: 8px 14px;
            font-size: 13px;
            border-radius: 4px;
            margin: 2px;
        }
        .dpr-btn-success { background: var(--dpr-success); }
        .dpr-btn-success:hover { background: #16a34a; }
        .dpr-btn-danger { background: #ef4444; }
        .dpr-btn-danger:hover { background: #dc2626; }
        
        .dpr-badge {
            display: inline-block;
            padding: 4px 12px;
            font-size: 12px;
            font-weight: 600;
            border-radius: 50px;
            text-align: center;
        }
        .dpr-badge-submitted { background: #fef3c7; color: #d97706; }
        .dpr-badge-completed { background: #dcfce7; color: #15803d; }

        .dpr-alert {
            padding: 16px;
            border-radius: 6px;
            margin-bottom: 25px;
            font-size: 15px;
            border-left: 4px solid transparent;
        }
        .dpr-alert-success {
            background: #dcfce7;
            color: #14532d;
            border-left-color: var(--dpr-success);
        }
        .dpr-alert-danger {
            background: #fee2e2;
            color: #7f1d1d;
            border-left-color: #ef4444;
        }
        .dpr-print-link-btn {
            display: inline-block;
            margin-top: 10px;
            font-weight: bold;
            color: #15803d;
            text-decoration: underline;
        }
        .dpr-remove-btn {
            background: #fee2e2;
            border: 1px solid #fecaca;
            color: #ef4444;
            font-weight: bold;
            font-size: 14px;
            padding: 8px 14px;
            border-radius: 4px;
            cursor: pointer;
            width: 100%;
            text-align: center;
        }
        .dpr-remove-btn:hover {
            background: #fca5a5;
            color: #b91c1c;
        }
        .dpr-desc-text {
            font-size: 13px;
            color: var(--dpr-text-muted);
            margin-top: -10px;
            margin-bottom: 20px;
        }
    </style>

    <div class="dpr-frontend-wrap">
        
        <div class="dpr-card">
            <h2 class="dpr-section-title">New Purchase Request</h2>
            <form method="post">
                <?php wp_nonce_field('dpr_save_frontend_request', 'dpr_frontend_nonce'); ?>

                <div class="dpr-form-grid">
                    <div class="dpr-form-group">
                        <label class="dpr-label">Requestor Name</label>
                        <input type="text" name="requestor_name" class="dpr-input" value="<?php echo esc_attr($current_user->display_name); ?>" required>
                    </div>
                    <div class="dpr-form-group">
                        <label class="dpr-label">Department</label>
                        <select name="department" class="dpr-select" required>
                            <option value="">-- Select Department --</option>
                            <option>Welding</option>
                            <option>Electrical</option>
                            <option>Automation</option>
                            <option>CNC / Machining</option>
                            <option>Office Management</option>
                            <option>Finance</option>
                            <option>Admin / HR</option>
                            <option>Facilities</option>
                            <option>Business Development</option>
                            <option>Student Affairs</option>
                            <option>Others</option>
                        </select>
                    </div>
                    <div class="dpr-form-group">
                        <label class="dpr-label">Required Date</label>
                        <input type="date" name="required_date" class="dpr-input">
                    </div>
                </div>

                <div class="dpr-form-group full-width" style="margin-bottom: 20px;">
                    <label class="dpr-label">Request For / Purpose</label>
                    <textarea name="purpose" rows="3" class="dpr-textarea" placeholder="Explain the purpose of this order..." required></textarea>
                </div>

                <div class="dpr-form-group full-width" style="margin-bottom: 30px;">
                    <label class="dpr-label">Remarks</label>
                    <textarea name="remarks" rows="2" class="dpr-textarea" placeholder="Additional internal notes..."></textarea>
                </div>

                <h3 style="font-size:20px; font-weight:700; margin-bottom:5px; color:#1e293b;">Requested Items</h3>
                <p class="dpr-desc-text">Search items from warehouse. Fields sit side-by-side in full view on desktops, and stack on mobiles.</p>

                <datalist id="dpr-frontend-consumable-list">
                    <?php foreach ($consumables as $c): ?>
                        <option 
                            value="<?php echo esc_attr($c->item_name); ?>"
                            data-id="<?php echo esc_attr($c->id); ?>"
                            data-unit="<?php echo esc_attr($c->unit); ?>"
                            data-stock="<?php echo esc_attr($c->current_stock); ?>">
                        </option>
                    <?php endforeach; ?>
                </datalist>

                <div class="dpr-table-container" style="border:none;">
                    <table id="dpr-frontend-items" class="dpr-table dpr-table-responsive-stack">
                        <thead>
                            <tr>
                                <th style="width:35%;">Item Name</th>
                                <th style="width:15%;">Unit</th>
                                <th style="width:15%;">Qty</th>
                                <th style="width:15%;">Stock Balance</th>
                                <th style="width:17%;">Item Remarks</th>
                                <th style="width:3%;"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td data-label="Item Name">
                                    <input type="text" name="item_name[]" class="dpr-f-input dpr-input" list="dpr-frontend-consumable-list" placeholder="Type to search item..." required>
                                    <input type="hidden" name="consumable_item_id[]" class="dpr-f-id">
                                </td>
                                <td data-label="Unit"><input type="text" name="unit[]" class="dpr-f-unit dpr-input" placeholder="pcs"></td>
                                <td data-label="Requested Quantity"><input type="number" step="0.01" min="0" name="qty_requested[]" class="dpr-input dpr-input-number" placeholder="0.00" required></td>
                                <td data-label="Warehouse Stock Balance"><input type="text" class="dpr-f-stock dpr-input" style="background:#f1f5f9 !important;" readonly placeholder="-"></td>
                                <td data-label="Item Remarks"><input type="text" name="item_remarks[]" class="dpr-input" placeholder="Notes..."></td>
                                <td class="dpr-actions-cell"><button type="button" class="dpr-remove-btn remove-f-row">Remove</button></td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <button type="button" id="add-f-row" class="dpr-btn dpr-btn-secondary dpr-btn-sm" style="margin-bottom: 25px;">+ Add Additional Item</button>
                
                <div style="border-top:1px solid var(--dpr-border); padding-top:20px; text-align:right;">
                    <button type="submit" class="dpr-btn">Submit Purchase Request</button>
                </div>
            </form>
        </div>

        <div class="dpr-card">
            <h2 class="dpr-section-title">Purchase Request Logs & History</h2>
            <div class="dpr-table-container">
                <table class="dpr-table">
                    <thead>
                        <tr>
                            <th>PR Number</th>
                            <th>Date</th>
                            <th>Requestor</th>
                            <th>Department</th>
                            <th>Purpose</th>
                            <th style="text-align:center;">Status</th>
                            <th style="text-align:center; width:220px;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($logs)): foreach ($logs as $log): 
                            $print_log_url = add_query_arg(['dpr_action' => 'print', 'id' => $log->id], $page_url);
                            $nonce_print_log = wp_nonce_url($print_log_url, 'dpr_print_' . $log->id);
                            $status_class = ($log->status === 'Completed') ? 'dpr-badge-completed' : 'dpr-badge-submitted';
                        ?>
                            <tr>
                                <td><strong><?php echo esc_html($log->request_no); ?></strong></td>
                                <td style="color:var(--dpr-text-muted); font-size:13px;"><?php echo esc_html(date('d/m/Y', strtotime($log->request_date))); ?></td>
                                <td><?php echo esc_html($log->requestor_name); ?></td>
                                <td><?php echo esc_html($log->department); ?></td>
                                <td style="font-size:13px; color: #475569;"><?php echo esc_html(wp_trim_words($log->purpose, 8)); ?></td>
                                <td style="text-align:center;">
                                    <span class="dpr-badge <?php echo $status_class; ?>">
                                        <?php echo esc_html($log->status); ?>
                                    </span>
                                </td>
                                <td style="text-align:center;">
                                    <a target="_blank" href="<?php echo esc_url($nonce_print_log); ?>" class="dpr-btn dpr-btn-sm">Print</a>
                                    
                                    <?php if (current_user_can('manage_options')): ?>
                                        <?php if ($log->status !== 'Completed'): ?>
                                            <a href="<?php echo esc_url(wp_nonce_url(add_query_arg(['dpr_action_status' => 'complete', 'req_id' => $log->id], $page_url), 'dpr_status_' . $log->id)); ?>" class="dpr-btn dpr-btn-sm dpr-btn-success">Complete</a>
                                        <?php else: ?>
                                            <a href="<?php echo esc_url(wp_nonce_url(add_query_arg(['dpr_action_status' => 'reopen', 'req_id' => $log->id], $page_url), 'dpr_status_' . $log->id)); ?>" class="dpr-btn dpr-btn-sm dpr-btn-danger">Reopen</a>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; else: ?>
                            <tr><td colspan="7" style="padding:30px; text-align:center; color:var(--dpr-text-muted);">No logs or request history found matching your account profiles.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
    (function() {
        const listOptions = Array.from(document.querySelectorAll('#dpr-frontend-consumable-list option')).map(opt => ({
            name: opt.value,
            id: opt.dataset.id || '',
            unit: opt.dataset.unit || '',
            stock: opt.dataset.stock || ''
        }));

        document.addEventListener('input', function(e) {
            if (e.target.classList.contains('dpr-f-input')) {
                const row = e.target.closest('tr');
                const matched = listOptions.find(x => x.name.toLowerCase() === e.target.value.toLowerCase());
                
                row.querySelector('.dpr-f-id').value = matched ? matched.id : '';
                row.querySelector('.dpr-f-unit').value = matched ? matched.unit : '';
                row.querySelector('.dpr-f-stock').value = matched ? matched.stock : '';
            }
        });

        document.getElementById('add-f-row').addEventListener('click', function() {
            const tbody = document.querySelector('#dpr-frontend-items tbody');
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td data-label="Item Name">
                    <input type="text" name="item_name[]" class="dpr-f-input dpr-input" list="dpr-frontend-consumable-list" placeholder="Type to search item..." required>
                    <input type="hidden" name="consumable_item_id[]" class="dpr-f-id">
                </td>
                <td data-label="Unit"><input type="text" name="unit[]" class="dpr-f-unit dpr-input" placeholder="pcs"></td>
                <td data-label="Requested Quantity"><input type="number" step="0.01" min="0" name="qty_requested[]" class="dpr-input dpr-input-number" placeholder="0.00" required></td>
                <td data-label="Warehouse Stock Balance"><input type="text" class="dpr-f-stock dpr-input" style="background:#f1f5f9 !important;" readonly placeholder="-"></td>
                <td data-label="Item Remarks"><input type="text" name="item_remarks[]" class="dpr-input" placeholder="Notes..."></td>
                <td class="dpr-actions-cell"><button type="button" class="dpr-remove-btn remove-f-row">Remove</button></td>
            `;
            tbody.appendChild(tr);
        });

        document.addEventListener('click', function(e) {
            if (e.target.classList.contains('remove-f-row')) {
                const rows = document.querySelectorAll('#dpr-frontend-items tbody tr');
                if (rows.length > 1) {
                    e.target.closest('tr').remove();
                }
            }
        });
    })();
    </script>
    <?php
    return $output . ob_get_clean();
});