<?php
if (!defined('ABSPATH')) exit;

global $wpdb;

$cur = simpinby_get_currency();
$CURRENCY = isset($cur["symbol"]) ? $cur["symbol"] : "₹";

$invoice_table = esc_sql( $wpdb->prefix . 'simpinby_invoices' );
$items_table   = esc_sql( $wpdb->prefix . 'simpinby_invoice_items' );


// =============================
// Stats
// =============================
$total_invoices = (int) $wpdb->get_var(
    $wpdb->prepare(
        "SELECT COUNT(*) FROM {$invoice_table} WHERE is_archived = %d",
        0
    )
);


$total_paid = (int) $wpdb->get_var(
    $wpdb->prepare(
        "SELECT COUNT(*) FROM {$invoice_table} WHERE is_archived = %d AND status = %s",
        0,
        'paid'
    )
);

$total_unpaid = (int) $wpdb->get_var(
    $wpdb->prepare(
        "SELECT COUNT(*) FROM {$invoice_table} WHERE is_archived = %d AND status = %s",
        0,
        'unpaid'
    )
);

$current_month = (int) wp_date('m');
$current_year  = (int) wp_date('Y');

$this_month_sales = (float) $wpdb->get_var(
    $wpdb->prepare(
        "
        SELECT IFNULL(SUM(total_amount),0)
        FROM {$invoice_table}
        WHERE is_archived = %d
        AND status = %s
        AND MONTH(created_at) = %d
        AND YEAR(created_at) = %d
        ",
        0,
        'paid',
        $current_month,
        $current_year
    )
);


$this_month_tax = (float) $wpdb->get_var(
    $wpdb->prepare(
        "
        SELECT IFNULL(SUM(total_tax),0)
        FROM {$invoice_table}
        WHERE is_archived = %d
        AND status = %s
        AND MONTH(created_at) = %d
        AND YEAR(created_at) = %d
        ",
        0,
        'paid',
        $current_month,
        $current_year
    )
);

$this_month_discount = (float) $wpdb->get_var(
    $wpdb->prepare(
        "
        SELECT IFNULL(SUM(discount),0)
        FROM {$invoice_table}
        WHERE is_archived = %d
        AND status = %s
        AND MONTH(created_at) = %d
        AND YEAR(created_at) = %d
        ",
        0,
        'paid',
        $current_month,
        $current_year
    )
);



// =============================
// Top selling products
// =============================
$top_products = $wpdb->get_results(
    $wpdb->prepare(
        "
        SELECT i.product_name, SUM(i.qty) as total_qty
        FROM {$items_table} i
        INNER JOIN {$invoice_table} inv ON inv.id = i.invoice_id
        WHERE inv.is_archived = %d
        AND inv.status = %s
        GROUP BY i.product_name
        ORDER BY total_qty DESC
        LIMIT %d
        ",
        0,
        'paid',
        5
    ),
    ARRAY_A
);



// =============================
// Recent invoices
// =============================
$recent = $wpdb->get_results(
    $wpdb->prepare(
        "
        SELECT id, invoice_number, total_amount, status, created_at
        FROM {$invoice_table}
        WHERE is_archived = %d
        ORDER BY id DESC
        LIMIT %d
        ",
        0,
        5
    ),
    ARRAY_A
);


// Percent Paid
$paid_percent = ($total_invoices > 0) ? round(($total_paid / $total_invoices) * 100) : 0;
?>


<div class="wrap simpinby-dashboard-wrap">

  <!-- Header -->
  <div class="simpinby-dashboard-header">
    <div class="simpinby-dashboard-title">
      <h1>Invoice Dashboard</h1>
      <p>Quick overview of invoices, payments and monthly revenue.</p>
    </div>
  </div>

  <!-- Cards -->
  <div class="simpinby-grid-cards">

    <div class="simpinby-card simpinby-col-3">
      <div class="simpinby-card-top">
        <p class="simpinby-card-title">Total Invoices</p>
        <span class="simpinby-badge simpinby-badge-blue">All</span>
      </div>
      <p class="simpinby-card-value"><?php echo esc_html($total_invoices); ?></p>
      <div class="simpinby-card-sub">All active invoices (not archived)</div>
    </div>

    <div class="simpinby-card simpinby-col-3">
      <div class="simpinby-card-top">
        <p class="simpinby-card-title">Paid Invoices</p>
        <span class="simpinby-badge simpinby-badge-green"><?php echo esc_html($paid_percent); ?>% Paid</span>
      </div>
      <p class="simpinby-card-value"><?php echo esc_html($total_paid); ?></p>

      <div class="simpinby-progress" aria-label="Paid Progress">
        <span style="width: <?php echo esc_attr($paid_percent); ?>%;"></span>
      </div>
      <div class="simpinby-card-sub">Invoices marked as paid</div>
    </div>

    <div class="simpinby-card simpinby-col-3">
      <div class="simpinby-card-top">
        <p class="simpinby-card-title">Unpaid Invoices</p>
        <span class="simpinby-badge simpinby-badge-red">Pending</span>
      </div>
      <p class="simpinby-card-value"><?php echo esc_html($total_unpaid); ?></p>
      <div class="simpinby-card-sub">Need payment follow-up</div>
    </div>

    <div class="simpinby-card simpinby-col-3">
      <div class="simpinby-card-top">
        <p class="simpinby-card-title">This Month Sales</p>
        <span class="simpinby-badge">Paid Only</span>
      </div>
      <p class="simpinby-card-value"><?php echo esc_html($CURRENCY); ?> <?php echo esc_html(number_format($this_month_sales, 2)); ?></p>
      <div class="simpinby-card-sub">Total revenue from paid invoices</div>
    </div>

    <div class="simpinby-card simpinby-col-4">
      <div class="simpinby-card-top">
        <p class="simpinby-card-title">This Month Tax</p>
        <span class="simpinby-badge">Collected</span>
      </div>
      <p class="simpinby-card-value"><?php echo esc_html($CURRENCY); ?> <?php echo esc_html(number_format($this_month_tax, 2)); ?></p>
      <div class="simpinby-card-sub">Tax collected on paid invoices</div>
    </div>

    <div class="simpinby-card simpinby-col-4">
      <div class="simpinby-card-top">
        <p class="simpinby-card-title">This Month Discount</p>
        <span class="simpinby-badge">Given</span>
      </div>
      <p class="simpinby-card-value"><?php echo esc_html($CURRENCY); ?> <?php echo esc_html(number_format($this_month_discount, 2)); ?></p>
      <div class="simpinby-card-sub">Total discount applied this month</div>
    </div>

    <div class="simpinby-card simpinby-col-4">
      <div class="simpinby-card-top">
        <p class="simpinby-card-title">Net (Sales - Discount)</p>
        <span class="simpinby-badge simpinby-badge-blue">Estimate</span>
      </div>
      <p class="simpinby-card-value">
        <?php
          $net = max(0, ($this_month_sales - $this_month_discount));
          echo esc_html($CURRENCY) . " " . esc_html(number_format($net, 2));
        ?>
      </p>
      <div class="simpinby-card-sub">Quick net estimate (before tax)</div>
    </div>

  </div>

  <!-- Panels -->
  <div class="simpinby-panels">

    <!-- Top Products -->
    <div class="simpinby-panel simpinby-col-6">
      <div class="simpinby-panel-head">
        <h2>Top Selling Products</h2>
        <span class="simpinby-badge">Top 5</span>
      </div>

      <div class="simpinby-panel-body">
        <?php if (empty($top_products)): ?>
          <p class="simpinby-muted">No data yet.</p>
        <?php else: ?>
          <table class="simpinby-table">
            <thead>
              <tr>
                <th>Product</th>
                <th style="width:140px;">Qty Sold</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($top_products as $p): ?>
                <tr>
                  <td>
                    <strong><?php echo esc_html($p["product_name"]); ?></strong>
                  </td>
                  <td>
                    <span class="simpinby-badge"><?php echo esc_html($p["total_qty"]); ?></span>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        <?php endif; ?>
      </div>
    </div>

    <!-- Recent Invoices -->
    <div class="simpinby-panel simpinby-col-6">
      <div class="simpinby-panel-head">
        <h2>Recent Invoices</h2>
        <a class="simpinby-btn" style="padding:7px 10px;" href="?page=simpinby-invoices">View All</a>
      </div>

      <div class="simpinby-panel-body">
        <?php if (empty($recent)): ?>
          <p class="simpinby-muted">No invoices found.</p>
        <?php else: ?>
          <table class="simpinby-table">
            <thead>
              <tr>
                <th>Invoice</th>
                <th style="width:150px;">Total</th>
                <th style="width:130px;">Status</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($recent as $r): ?>
                <tr>
                  <td>
                    <a href="<?php echo esc_url(
                          admin_url(
                              'admin.php?page=simpinby-invoices&action=view&id=' . absint( $r['id'] )
                          )
                      ); ?>" style="font-weight:900;">
                      <?php echo esc_html($r["invoice_number"]); ?>
                    </a>
                    <div class="simpinby-muted">
                      <?php echo esc_html(
                            wp_date(
                                'd M Y',
                                strtotime( $r['created_at'] )
                            )
                        );
                      ?>
                    </div>
                  </td>

                  <td>
                    <strong><?php echo esc_html($CURRENCY); ?> <?php echo esc_html(number_format((float)$r["total_amount"], 2)); ?></strong>
                  </td>

                  <td>
                    <?php if ($r["status"] === "paid"): ?>
                      <span class="simpinby-status-pill simpinby-status-paid">PAID</span>
                    <?php else: ?>
                      <span class="simpinby-status-pill simpinby-status-unpaid">UNPAID</span>
                    <?php endif; ?>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        <?php endif; ?>
      </div>
    </div>

  </div>

</div>
