<?php
if (!defined('ABSPATH')) die('Restricted Access');
if (!current_user_can('manage_options')) {
    wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'ai-flash-tune'));
}
$aiflt_page_title = __('AI Usage & Reports', 'ai-flash-tune');
$usage_stats = class_exists('AIFLT_AI_Usage_Log') ? AIFLT_AI_Usage_Log::stats(30) : ['total'=>0,'success'=>0,'error'=>0,'local'=>0];
$logs = class_exists('AIFLT_AI_Usage_Log') ? AIFLT_AI_Usage_Log::recent(50) : [];
$reports = class_exists('AIFLT_AI_Report_Log') ? AIFLT_AI_Report_Log::recent(30) : [];
?>
<div class="ai-flash-tune-admin-wrapper aiflt-admin-page-ai-usage-reports">
  <?php include(AIFLT_PLUGIN_PATH . 'includes/admin/ai-flash-tune-admin-sidebar.php'); ?>
  <div class="ai-flash-tune-main-content">
    <div class="ai-flash-tune-page-content-wrapper">
  <div class="ai-flash-tune-page-header ai-flash-tune-mb-8">
    <div>
      <h1><?php echo esc_html__('AI Usage & Reports', 'ai-flash-tune'); ?></h1>
      <p><?php echo esc_html__('Review provider calls, token usage, saved AI outputs, local fallbacks, and errors from one audit screen.', 'ai-flash-tune'); ?></p>
    </div>
  </div>

  <div class="aiflt-usage-stats-grid ai-flash-tune-mb-8">
    <div class="ai-flash-tune-card"><span><?php echo esc_html__('Total actions', 'ai-flash-tune'); ?></span><strong><?php echo esc_html(number_format_i18n($usage_stats['total'] ?? 0)); ?></strong><p><?php echo esc_html__('OpenAI/Zywrap/local attempts in the last 30 days.', 'ai-flash-tune'); ?></p></div>
    <div class="ai-flash-tune-card"><span><?php echo esc_html__('Successful AI calls', 'ai-flash-tune'); ?></span><strong><?php echo esc_html(number_format_i18n($usage_stats['success'] ?? 0)); ?></strong><p><?php echo esc_html__('Counts toward the monthly free AI action limit.', 'ai-flash-tune'); ?></p></div>
    <div class="ai-flash-tune-card"><span><?php echo esc_html__('Errors / blocked', 'ai-flash-tune'); ?></span><strong><?php echo esc_html(number_format_i18n($usage_stats['error'] ?? 0)); ?></strong><p><?php echo esc_html__('Missing consent, quota reached, API errors, and invalid responses.', 'ai-flash-tune'); ?></p></div>
    <div class="ai-flash-tune-card"><span><?php echo esc_html__('Local fallbacks', 'ai-flash-tune'); ?></span><strong><?php echo esc_html(number_format_i18n($usage_stats['local'] ?? 0)); ?></strong><p><?php echo esc_html__('Safe guidance generated without external AI.', 'ai-flash-tune'); ?></p></div>
  </div>

  <div class="ai-flash-tune-card aiflt-usage-card ai-flash-tune-mb-8">
    <div class="aift-card-heading-row">
      <div>
        <span class="aiflt-kicker"><?php echo esc_html__('Provider audit', 'ai-flash-tune'); ?></span>
        <h3><?php echo esc_html__('AI usage log', 'ai-flash-tune'); ?></h3>
        <p><?php echo esc_html__('Use this for debugging, limits, and cost review. Prompt bodies and customer personal data are not stored here.', 'ai-flash-tune'); ?></p>
      </div>
    </div>
    <div class="aiflt-table-wrap">
      <table class="widefat striped">
        <thead><tr>
          <th><?php echo esc_html__('Date', 'ai-flash-tune'); ?></th>
          <th><?php echo esc_html__('Provider', 'ai-flash-tune'); ?></th>
          <th><?php echo esc_html__('Action', 'ai-flash-tune'); ?></th>
          <th><?php echo esc_html__('Status', 'ai-flash-tune'); ?></th>
          <th><?php echo esc_html__('Model / wrapper', 'ai-flash-tune'); ?></th>
          <th><?php echo esc_html__('Tokens', 'ai-flash-tune'); ?></th>
          <th><?php echo esc_html__('Duration', 'ai-flash-tune'); ?></th>
          <th><?php echo esc_html__('Message', 'ai-flash-tune'); ?></th>
        </tr></thead>
        <tbody>
        <?php if (empty($logs)) : ?><tr><td colspan="8"><?php echo esc_html__('No AI usage rows yet.', 'ai-flash-tune'); ?></td></tr>
        <?php else : foreach ($logs as $row) : ?>
          <tr>
            <td><?php echo esc_html($row['created_at'] ?? ''); ?></td>
            <td><span class="aiflt-status-pill"><?php echo esc_html($row['provider'] ?? ''); ?></span></td>
            <td><strong><?php echo esc_html($row['action_key'] ?? ''); ?></strong></td>
            <td><?php echo esc_html($row['status'] ?? ''); ?></td>
            <td><?php echo esc_html($row['model'] ?? ''); ?><br><span class="description"><?php echo esc_html($row['wrapper_code'] ?? ''); ?></span></td>
            <td><?php echo esc_html(number_format_i18n(absint($row['total_tokens'] ?? 0))); ?><br><span class="description"><?php
                  /* translators: 1: prompt token count, 2: completion token count. */
                  printf(esc_html__('prompt %1$s / output %2$s', 'ai-flash-tune'), esc_html(number_format_i18n(absint($row['prompt_tokens'] ?? 0))), esc_html(number_format_i18n(absint($row['completion_tokens'] ?? 0))));
                ?></span></td>
            <td><?php echo esc_html(number_format_i18n(absint($row['duration_ms'] ?? 0))); ?> ms</td>
            <td><?php echo esc_html(wp_trim_words((string)($row['message'] ?? ''), 22)); ?></td>
          </tr>
        <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <div class="ai-flash-tune-card aiflt-usage-card">
    <div class="aift-card-heading-row">
      <div>
        <span class="aiflt-kicker"><?php echo esc_html__('Persistent AI outputs', 'ai-flash-tune'); ?></span>
        <h3><?php echo esc_html__('Saved AI reports and local fallback outputs', 'ai-flash-tune'); ?></h3>
        <p><?php echo esc_html__('Generated reports are saved so page refresh does not remove the latest result. Use saved outputs for review only; they do not automatically change the store.', 'ai-flash-tune'); ?></p>
      </div>
    </div>
    <div class="aiflt-table-wrap">
      <table class="widefat striped">
        <thead><tr>
          <th><?php echo esc_html__('Date', 'ai-flash-tune'); ?></th>
          <th><?php echo esc_html__('Action', 'ai-flash-tune'); ?></th>
          <th><?php echo esc_html__('Provider', 'ai-flash-tune'); ?></th>
          <th><?php echo esc_html__('Status', 'ai-flash-tune'); ?></th>
          <th><?php echo esc_html__('Context', 'ai-flash-tune'); ?></th>
          <th><?php echo esc_html__('Preview', 'ai-flash-tune'); ?></th>
        </tr></thead>
        <tbody>
        <?php if (empty($reports)) : ?><tr><td colspan="6"><?php echo esc_html__('No saved reports yet.', 'ai-flash-tune'); ?></td></tr>
        <?php else : foreach ($reports as $row) : ?>
          <tr>
            <td><?php echo esc_html($row['created_at'] ?? ''); ?></td>
            <td><strong><?php echo esc_html($row['title'] ?: ($row['action_key'] ?? '')); ?></strong><br><span class="description"><?php echo esc_html($row['action_key'] ?? ''); ?></span></td>
            <td><?php echo esc_html($row['provider'] ?? ''); ?></td>
            <td><?php echo esc_html($row['status'] ?? ''); ?></td>
            <td><?php echo esc_html($row['context_key'] ?? ''); ?></td>
            <td><details><summary><?php echo esc_html__('View saved output', 'ai-flash-tune'); ?></summary><div class="aiflt-saved-output"><?php echo wp_kses_post(class_exists('AIFLT_AI_Report_Log') ? AIFLT_AI_Report_Log::render_content((string)($row['content'] ?? $row['message'] ?? '')) : nl2br(wp_trim_words((string)($row['content'] ?? $row['message'] ?? ''), 280))); ?></div></details></td>
          </tr>
        <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
    </div>
  </div>
</div>
<style>
.aiflt-admin-page-ai-usage-reports .ai-flash-tune-main-content{min-width:0;width:100%;}
.aiflt-admin-page-ai-usage-reports .ai-flash-tune-page-content-wrapper{max-width:100%;overflow:hidden;}
.aiflt-admin-page-ai-usage-reports .aiflt-table-wrap{overflow-x:auto;}

.aiflt-usage-stats-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:16px}.aiflt-usage-stats-grid .ai-flash-tune-card{border-radius:20px;padding:18px}.aiflt-usage-stats-grid span{display:block;font-size:11px;text-transform:uppercase;letter-spacing:.1em;color:#64748b;font-weight:900}.aiflt-usage-stats-grid strong{font-size:26px;color:#0f172a}.aiflt-usage-stats-grid p{margin:6px 0 0;color:#64748b}.aiflt-status-pill{display:inline-flex;padding:5px 10px;border-radius:999px;background:#eef2ff;color:#3730a3;font-size:12px;font-weight:800}.aiflt-saved-output{max-height:280px;overflow:auto;padding:12px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:12px;line-height:1.55}.aiflt-table-wrap table td{vertical-align:top}@media(max-width:1000px){.aiflt-usage-stats-grid{grid-template-columns:1fr 1fr}}@media(max-width:640px){.aiflt-usage-stats-grid{grid-template-columns:1fr}}
</style>
