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

if ( ! current_user_can( 'manage_options' ) ) {
    wp_die(
        esc_html__( 'Unauthorized access.', 'simpinby-invoice-manager' )
    );
}

global $wpdb;



$cur = simpinby_get_currency();
$CURRENCY = $cur["symbol"];

$invoice_table   = esc_sql( $wpdb->prefix . 'simpinby_invoices' );
$customers_table = esc_sql( $wpdb->prefix . 'simpinby_customers' );


// Pagination
$page = isset($_GET["paged"])
    ? max(1, absint( wp_unslash($_GET["paged"]) ))
    : 1;
$per_page = 10;
$offset = ($page - 1) * $per_page;

// Filters
$show = isset($_GET["show"])
    ? sanitize_text_field( wp_unslash($_GET["show"]) )
    : "active";

$search_by = isset($_GET["search_by"])
    ? sanitize_text_field( wp_unslash($_GET["search_by"]) )
    : "invoice_number";

$search = isset($_GET["s"])
    ? sanitize_text_field( wp_unslash($_GET["s"]) )
    : "";

$date_from = isset($_GET["date_from"])
    ? sanitize_text_field( wp_unslash($_GET["date_from"]) )
    : "";

$date_to = isset($_GET["date_to"])
    ? sanitize_text_field( wp_unslash($_GET["date_to"]) )
    : "";

// Validate allowed values
$allowed_show = ['active', 'archived'];
if ( ! in_array( $show, $allowed_show, true ) ) {
    $show = 'active';
}

$allowed_search_by = ['invoice_number', 'customer_name'];
if ( ! in_array( $search_by, $allowed_search_by, true ) ) {
    $search_by = 'invoice_number';
}



// Base WHERE + params
$where = "1=1";
$params = [];

// Active / Archived filter
if ($show === "archived") {
  $where .= " AND inv.is_archived=1";
} else {
  $where .= " AND inv.is_archived=0";
}

// Search filter
if (!empty($search)) {
  if ($search_by === "customer_name") {
    $where .= " AND c.name LIKE %s";
    $params[] = "%" . $wpdb->esc_like($search) . "%";
  } else {
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
    $where .= " AND inv.invoice_number LIKE %s";
    $params[] = "%" . $wpdb->esc_like($search) . "%";
  }
}

// Date range filter (created_at)
if (!empty($date_from)) {
  $where .= " AND DATE(inv.created_at) >= %s";
  $params[] = $date_from;
}

if (!empty($date_to)) {
  $where .= " AND DATE(inv.created_at) <= %s";
  $params[] = $date_to;
}

// Count widgets (only active invoices)
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$total_all = intval(
    $wpdb->get_var(
        $wpdb->prepare(
            "SELECT COUNT(*) FROM {$invoice_table} WHERE is_archived = %d",
            0
        )
    )
);

// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$total_paid = intval(
    $wpdb->get_var(
        $wpdb->prepare(
            "SELECT COUNT(*) FROM {$invoice_table} WHERE is_archived = %d AND status = %s",
            0,
            'paid'
        )
    )
);
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$total_unpaid = intval(
    $wpdb->get_var(
        $wpdb->prepare(
            "SELECT COUNT(*) FROM {$invoice_table} WHERE is_archived = %d AND status = %s",
            0,
            'unpaid'
        )
    )
);



// Total listing count (with filters)
$count_sql = "
    SELECT COUNT(*)
    FROM {$invoice_table} inv
    LEFT JOIN {$customers_table} c ON c.id = inv.customer_id
    WHERE {$where}
";

// Always prepare (even if empty)
$prepared_count_sql = $count_sql;

if ( ! empty( $params ) ) {
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
    $prepared_count_sql = $wpdb->prepare( $count_sql, $params );
}

$total_rows = intval(
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
    $wpdb->get_var( $prepared_count_sql )
);



$total_pages = ceil($total_rows / $per_page);

// Fetch invoices (with filters)
$list_sql = "
    SELECT inv.*, c.name as customer_name, c.phone as customer_phone
    FROM {$invoice_table} inv
    LEFT JOIN {$customers_table} c ON c.id = inv.customer_id
    WHERE {$where}
    ORDER BY inv.id DESC
    LIMIT %d OFFSET %d
";

$list_params   = $params;
$list_params[] = $per_page;
$list_params[] = $offset;
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$prepared_list_sql = $wpdb->prepare(
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
    $list_sql,
    $list_params
);

// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$invoices = $wpdb->get_results(
   // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
    $prepared_list_sql,
    ARRAY_A
);




?>

<div class="wrap">
  <h1 class="wp-heading-inline">Manage Invoices</h1>

  <a class="page-title-action" href="<?php echo esc_url( admin_url("admin.php?page=simpinby-invoices&action=create") ); ?>">
    + Create Invoice
  </a>

  <hr class="wp-header-end">

  <!-- Widgets -->
  <!-- Widgets -->

<?php
$paid_percent = ($total_all > 0) ? round(($total_paid / $total_all) * 100) : 0;
?>

<div class="simpinby-widgets-grid">

  <!-- Total -->
  <div class="simpinby-widget-card simpinby-col-4">
    <div class="simpinby-widget-top">
      <p class="simpinby-widget-title">Total Invoices</p>
      <span class="simpinby-widget-badge simpinby-widget-badge-blue">Active</span>
    </div>
    <p class="simpinby-widget-value" id="simpinby_total_all"><?php echo esc_html($total_all); ?></p>
    <div class="simpinby-widget-sub">All active invoices (not archived)</div>
  </div>

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

    <div class="simpinby-widget-progress" aria-label="Paid Progress">
      <span id="simpinby_paid_progress_bar" style="width: <?php echo esc_attr($paid_percent); ?>%;"></span>
    </div>

    <div class="simpinby-widget-sub">Invoices marked as paid</div>
  </div>

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

</div>


  <!-- Active / Archived -->
  <p style="margin:10px 0;">
    <a class="button <?php echo $show === "active" ? "button-primary" : ""; ?>" href="<?php echo esc_url(admin_url("admin.php?page=simpinby-invoices&show=active")); ?>">
      Active
    </a>

    <a class="button <?php echo $show === "archived" ? "button-primary" : ""; ?>" href="<?php echo esc_url(admin_url("admin.php?page=simpinby-invoices&show=archived")); ?>">
      Archived
    </a>
  </p>

  <!-- NEW FILTER BAR -->
  <form method="get" style="background:#fff; border:1px solid #ddd; padding:12px; border-radius:10px; margin:12px 0; display:flex; gap:10px; flex-wrap:wrap; align-items:end;">
    <input type="hidden" name="page" value="simpinby-invoices">
    <input type="hidden" name="show" value="<?php echo esc_attr($show); ?>">

    <div>
      <label style="font-weight:600; font-size:13px;">Search By</label><br>
      <select name="search_by">
        <option value="invoice_number" <?php selected($search_by, "invoice_number"); ?>>Invoice Number</option>
        <option value="customer_name" <?php selected($search_by, "customer_name"); ?>>Customer Name</option>
      </select>
    </div>

    <div>
      <label style="font-weight:600; font-size:13px;">Search</label><br>
      <input type="text" name="s" value="<?php echo esc_attr($search); ?>" placeholder="Search..." style="min-width:220px;">
    </div>

    <div>
      <label style="font-weight:600; font-size:13px;">From</label><br>
      <input type="date" name="date_from" value="<?php echo esc_attr($date_from); ?>">
    </div>

    <div>
      <label style="font-weight:600; font-size:13px;">To</label><br>
      <input type="date" name="date_to" value="<?php echo esc_attr($date_to); ?>">
    </div>

    <div>
      <button type="submit" class="button button-primary">Filter</button>
      <a class="button" href="<?php echo esc_url(admin_url("admin.php?page=simpinby-invoices&show=" . $show)); ?>">Reset</a>
    </div>
  </form>

  <!-- Table -->
  <table class="widefat striped">
    <thead>
      <tr>
        <th>Invoice #</th>
        <th>Customer</th>
        <th>Date</th>
        <th>Total</th>
        <th>Tax</th>
        <th>Status</th>
        <th style="width:260px;">Actions</th>
      </tr>
    </thead>

    <tbody>
      <?php if (empty($invoices)): ?>
        <tr>
          <td colspan="7">No invoices found.</td>
        </tr>
      <?php else: ?>
        <?php foreach ($invoices as $inv): ?>
          <tr id="simpinby-invoice-row-<?php echo esc_attr($inv["id"]); ?>" data-status="<?php echo esc_attr($inv["status"]); ?>">
            <td><b><?php echo esc_html($inv["invoice_number"]); ?></b></td>

            <td>
              <?php echo esc_html($inv["customer_name"] ?: "N/A"); ?>
              <?php if (!empty($inv["customer_phone"])): ?>
                <br><small><?php echo esc_html($inv["customer_phone"]); ?></small>
              <?php endif; ?>
            </td>

            <td><?php echo esc_html( date_i18n( get_option('date_format'), strtotime($inv["created_at"]) ) ); ?></td>

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

            <td>
              <?php if (!empty($inv["tax_name"])): ?>
                <?php echo esc_html($inv["tax_name"]); ?> (<?php echo esc_html($inv["tax_percent"]); ?>%)
              <?php else: ?>
                -
              <?php endif; ?>
            </td>

            <td class="simpinby-status-text">
                <?php if ($inv["status"] === "paid"): ?>
                    <span style="color:green; font-weight:700;">PAID</span>
                <?php else: ?>
                    <span style="color:#d63638; font-weight:700;">UNPAID</span>
                <?php endif; ?>
            </td>


            <td>
             <?php
                $view_url = wp_nonce_url(
                    admin_url("admin.php?page=simpinby-invoices&action=view&id=" . absint($inv["id"])),
                    'simpinby_view_invoice_' . absint($inv["id"])
                );
                ?>

                <a class="button button-small" href="<?php echo esc_url($view_url); ?>">
                  View
                </a>
              <button type="button"
                class="button button-small simpinby-toggle-status"
                data-id="<?php echo esc_attr($inv["id"]); ?>"
                data-nonce="<?php echo esc_attr( wp_create_nonce('simpinby_ajax_nonce') ); ?>">
                <?php echo ($inv["status"] === "paid") ? "Mark Unpaid" : "Mark Paid"; ?>
              </button>


             <button type="button"
                class="button button-small simpinby-toggle-archive"
                data-id="<?php echo esc_attr($inv["id"]); ?>"
                data-nonce="<?php echo esc_attr( wp_create_nonce('simpinby_ajax_nonce') ); ?>"
                onclick="return confirm('Are you sure?');">
                <?php echo ($show !== "archived") ? "Archive" : "Unarchive"; ?>
             </button>


            </td>
          </tr>
        <?php endforeach; ?>
      <?php endif; ?>
    </tbody>
  </table>

  <!-- Pagination -->
  <?php if ($total_pages > 1): ?>
    <div style="margin-top:15px;">
      <?php
      for ($i = 1; $i <= $total_pages; $i++) {

        $args = [
          "page" => "simpinby-invoices",
          "show" => $show,
          "paged" => $i,
          "search_by" => $search_by,
          "s" => $search,
          "date_from" => $date_from,
          "date_to" => $date_to,
        ];

        $url = add_query_arg($args, admin_url("admin.php"));
        $class = ($i == $page) ? "button button-primary" : "button";

        echo '<a class="' . esc_attr($class) . '" style="margin-right:5px;" href="' . esc_url($url) . '">' . esc_html($i) . '</a>';
      }
      ?>
    </div>
  <?php endif; ?>

</div>
