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

global $wpdb;

/**
 * ------------------------------------------------------------------
 * Validate Invoice ID + Permission
 * ------------------------------------------------------------------
 */
$invoice_id = isset($_GET['id']) 
    ? absint( wp_unslash( $_GET['id'] ) ) 
    : 0;

if ( ! $invoice_id ) {
    wp_die( esc_html__( 'Invalid invoice ID.', 'simpinby-invoice-manager' ) );
}

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

if (
    ! isset( $_GET['_wpnonce'] ) ||
    ! wp_verify_nonce(
        sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ),
        'simpinby_view_invoice_' . $invoice_id
    )
) {
    wp_die( esc_html__( 'Security check failed.', 'simpinby-invoice-manager' ) );
}



/**
 * ------------------------------------------------------------------
 * Secure Actions (PDF Download / Send Email)
 * ------------------------------------------------------------------
 */
$action = '';

$download_pdf = isset( $_GET['download_pdf'] )
    ? sanitize_text_field( wp_unslash( $_GET['download_pdf'] ) )
    : '';

$send_email = isset( $_GET['send_email'] )
    ? sanitize_text_field( wp_unslash( $_GET['send_email'] ) )
    : '';

if ( $download_pdf === '1' ) {
    $action = 'download_pdf';
}

if ( $send_email === '1' ) {
    $action = 'send_email';
}


if ($action) {
    $nonce_action = 'simpinby_' . $action . '_' . $invoice_id;

    if (
    ! isset( $_GET['_wpnonce'] ) ||
    ! wp_verify_nonce(
        sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ),
        $nonce_action
    )
    ) {
        wp_die( esc_html__( 'Security check failed.', 'simpinby-invoice-manager' ) );
    }

}

/**
 * ------------------------------------------------------------------
 * Fetch Data
 * ------------------------------------------------------------------
 */
$cur      = simpinby_get_currency();
$CURRENCY = $cur['symbol'];

$invoice_table = $wpdb->prefix . 'simpinby_invoices';
$items_table   = $wpdb->prefix . 'simpinby_invoice_items';
$customers     = $wpdb->prefix . 'simpinby_customers';

$invoice = $wpdb->get_row(
    $wpdb->prepare(
        "
        SELECT inv.*, 
               c.name    AS customer_name,
               c.phone   AS customer_phone,
               c.address AS customer_address,
               c.email   AS customer_email
        FROM {$invoice_table} inv
        LEFT JOIN {$customers} c ON c.id = inv.customer_id
        WHERE inv.id = %d
        ",
        $invoice_id
    ),
    ARRAY_A
);

if (!$invoice) {
    wp_die( esc_html__( 'Invoice not found.', 'simpinby-invoice-manager' ) );
}


if (empty($invoice['public_token'])) {
    $public_token = wp_generate_password(20, false);

    $wpdb->update(
        $invoice_table,
        ["public_token" => $public_token],
        ["id" => $invoice_id],
        ["%s"],
        ["%d"]
    );

    $invoice['public_token'] = $public_token;
}


// Public invoice URL
$public_url = site_url("/invoice/" . $invoice['public_token']);


$items = $wpdb->get_results(
    $wpdb->prepare(
        "SELECT * FROM {$items_table} WHERE invoice_id = %d",
        $invoice_id
    ),
    ARRAY_A
);

/**
 * ------------------------------------------------------------------
 * Company / PDF Settings
 * ------------------------------------------------------------------
 */
$pdf_settings = get_option('simpinby_pdf_settings', []);

$company_name    = $pdf_settings['company_name'] ?? '';
$company_phone   = $pdf_settings['company_phone'] ?? '';
$company_email   = $pdf_settings['company_email'] ?? '';
$company_address = $pdf_settings['company_address'] ?? '';
$company_website = $pdf_settings['company_website'] ?? '';
$company_logo    = $pdf_settings['logo_url'] ?? '';
?>

<div class="wrap">
    <h1 style="margin-bottom:10px;">
        <?php echo esc_html__('Invoice:', 'simpinby-invoice-manager'); ?>
        <?php echo esc_html($invoice['invoice_number']); ?>
    </h1>

    <?php
      $mail_status = isset( $_GET['mail'] )
      ? sanitize_key( wp_unslash( $_GET['mail'] ) )
      : '';
    ?>

    <?php if ($mail_status === 'sent') : ?>
        <div class="notice notice-success is-dismissible">
            <p><strong><?php esc_html_e('Success!', 'simpinby-invoice-manager'); ?></strong>
                <?php esc_html_e('Invoice email sent.', 'simpinby-invoice-manager'); ?></p>
        </div>
    <?php elseif ($mail_status === 'failed') : ?>
        <div class="notice notice-error is-dismissible">
            <p><strong><?php esc_html_e('Failed!', 'simpinby-invoice-manager'); ?></strong>
                <?php esc_html_e('Email not sent. Please check SMTP settings.', 'simpinby-invoice-manager'); ?></p>
        </div>
    <?php endif; ?>

    <p style="margin-top:10px;">
        <a href="<?php echo esc_url(admin_url('admin.php?page=simpinby-invoices')); ?>" class="button">
            ← <?php esc_html_e('Back', 'simpinby-invoice-manager'); ?>
        </a>

        <a href="<?php echo esc_url(
            wp_nonce_url(
                admin_url("admin.php?page=simpinby-invoices&action=view&id={$invoice_id}&download_pdf=1"),
                'simpinby_download_pdf_' . $invoice_id
            )
        ); ?>" class="button button-primary">
            <?php esc_html_e('Download PDF', 'simpinby-invoice-manager'); ?>
        </a>

        <a href="<?php echo esc_url(
            wp_nonce_url(
                admin_url("admin.php?page=simpinby-invoices&action=view&id={$invoice_id}&send_email=1"),
                'simpinby_send_email_' . $invoice_id
            )
        ); ?>" class="button button-primary">
            <?php esc_html_e('Send Email', 'simpinby-invoice-manager'); ?>
        </a>

        <a href="<?php echo esc_url($public_url); ?>" target="_blank" class="button">
            <?php esc_html_e('View Public', 'simpinby-invoice-manager'); ?>
        </a>

        <?php if (!empty($invoice['customer_phone'])):

          $phone = preg_replace('/[^0-9]/', '', $invoice['customer_phone']);

          if (strlen($phone) === 10) {
              $phone = "91" . $phone;
          }

          $date = !empty($invoice['created_at']) 
              ? date_i18n(get_option('date_format'), strtotime($invoice['created_at'])) 
              : '';

          // Message
          $message  = "*{$company_name}*\n";
          $message .= "Invoice #: {$invoice['invoice_number']}\n";

          if ($date) {
              $message .= "Date: {$date}\n";
          }

          $message .= "\n*Bill To:* {$invoice['customer_name']}\n";

          if (!empty($invoice['status'])) {
              $message .= ($invoice['status'] === 'paid') 
                  ? "✅ Paid\n" 
                  : "⚠️ Payment Pending\n";
          }

          $message .= "\n*Amount:* {$CURRENCY} " . number_format($invoice['total_amount'], 2) . "\n";

          if (!empty($invoice['tax_name']) && $invoice['total_tax'] > 0) {
              $message .= "Tax ({$invoice['tax_percent']}%): {$CURRENCY} " . number_format($invoice['total_tax'], 2) . "\n";
          }

          if (!empty($invoice['discount']) && $invoice['discount'] > 0) {
              $message .= "Discount: {$CURRENCY} " . number_format($invoice['discount'], 2) . "\n";
          }

          $message .= "\n📄 View Invoice: {$public_url}\n";

          if (!empty($company_phone)) {
              $message .= "\n📞 {$company_phone}";
          }

          $message .= "\n\nThank you for your business";

          $encoded_message = rawurlencode($message);

          // URLs
          $wa_web = "https://web.whatsapp.com/send?phone={$phone}&text={$encoded_message}";
          $wa_app = "https://wa.me/{$phone}?text={$encoded_message}";
      ?>

      
      <a href="<?php echo esc_attr($wa_web); ?>" 
        target="_blank"
        data-app="<?php echo esc_attr($wa_app); ?>"
        class="button button-secondary simpinby-wa-btn">
          <?php esc_html_e('Send WhatsApp', 'simpinby-invoice-manager'); ?>
      </a>

      <script>
      document.addEventListener("DOMContentLoaded", function () {
          var btn = document.querySelector(".simpinby-wa-btn");

          if (!btn) return;

          var isMobile = /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);

          if (isMobile) {
              btn.setAttribute("href", btn.getAttribute("data-app"));
              btn.removeAttribute("target"); // open app
          }
      });
      </script>

    <?php endif; ?>
    </p>
  <!-- HEADER CARD -->
  <div style="display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:10px; background:#fff; border:1px solid #ddd; padding:12px 14px; border-radius:12px; margin-top:12px;">
    <div>
      <h2 style="margin:0; font-size:18px;"><?php echo esc_html($company_name ?: "Company"); ?></h2>

      <div style="color:#555; font-size:12px; margin-top:4px; line-height:1.4;">
        <b>Invoice #:</b> <?php echo esc_html($invoice["invoice_number"]); ?> &nbsp; | &nbsp;
        <b>Date:</b> <?php echo esc_html( date_i18n( get_option( 'date_format' ), strtotime( $invoice['created_at'] ) ) ); ?>
      </div>
    </div>

    <?php if (!empty($company_logo)): ?>
      <div style="text-align:right;">
        <img src="<?php echo esc_url($company_logo); ?>" style="max-height:55px; max-width:160px; object-fit:contain;">
      </div>
    <?php endif; ?>
  </div>

  <!-- FROM + BILL TO -->
  <div style="display:flex; gap:12px; flex-wrap:wrap; margin-top:12px;">

    <!-- FROM -->
    <div style="flex:1; min-width:320px; background:#fff; border:1px solid #ddd; padding:12px 14px; border-radius:12px;">
      <h3 style="margin:0 0 8px 0; font-size:14px;">From</h3>

      <div style="font-size:13px; line-height:1.35;">
        <div><b><?php echo esc_html($company_name); ?></b></div>

        <?php if (!empty($company_address)): ?>
          <div><?php echo nl2br(esc_html($company_address)); ?></div>
        <?php endif; ?>

        <?php if (!empty($company_phone)): ?>
          <div><b>Phone:</b> <?php echo esc_html($company_phone); ?></div>
        <?php endif; ?>

        <?php if (!empty($company_email)): ?>
          <div><b>Email:</b> <?php echo esc_html($company_email); ?></div>
        <?php endif; ?>

        <?php if (!empty($company_website)): ?>
          <div><b>Web:</b> <?php echo esc_html($company_website); ?></div>
        <?php endif; ?>
      </div>
    </div>

    <!-- BILL TO -->
    <div style="flex:1; min-width:320px; background:#fff; border:1px solid #ddd; padding:12px 14px; border-radius:12px;">
      <h3 style="margin:0 0 8px 0; font-size:14px;">Bill To</h3>

      <div style="font-size:13px; line-height:1.35;">
        <div><b><?php echo esc_html($invoice["customer_name"]); ?></b></div>

        <?php if (!empty($invoice["customer_phone"])): ?>
          <div><b>Phone:</b> <?php echo esc_html($invoice["customer_phone"]); ?></div>
        <?php endif; ?>

        <?php if (!empty($invoice["customer_email"])): ?>
          <div><b>Email:</b> <?php echo esc_html($invoice["customer_email"]); ?></div>
        <?php endif; ?>

        <?php if (!empty($invoice["customer_address"])): ?>
          <div><?php echo nl2br(esc_html($invoice["customer_address"])); ?></div>
        <?php endif; ?>
      </div>
    </div>

  </div>

  <!-- STATUS CARD -->
  <div style="background:#fff; border:1px solid #ddd; padding:12px 14px; border-radius:12px; margin-top:12px;">
    <h3 style="margin:0 0 8px 0; font-size:14px;">Invoice Info</h3>

    <div style="display:flex; gap:20px; flex-wrap:wrap; font-size:13px; align-items:center;">
      <div>
        <b>Status:</b>
        <?php if ($invoice["status"] === "paid"): ?>
          <span style="display:inline-block; padding:3px 10px; border-radius:20px; background:#e7f7ee; color:#137333; font-weight:700;">
            PAID
          </span>
        <?php else: ?>
          <span style="display:inline-block; padding:3px 10px; border-radius:20px; background:#fde8e8; color:#b42318; font-weight:700;">
            UNPAID
          </span>
        <?php endif; ?>
      </div>

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

  <!-- ITEMS -->
  <div style="margin-top:12px;">
    <h2 style="margin:0 0 8px 0;">Invoice Items</h2>

    <table class="widefat striped">
      <thead>
        <tr>
          <th>Product</th>
          <th style="width:90px;">Qty</th>
          <th style="width:140px;">Price</th>
          <th style="width:140px;">Total</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($items as $it): ?>
          <tr>
            <td><?php echo esc_html($it["product_name"]); ?></td>
            <td><?php echo esc_html($it["qty"]); ?></td>
            <td><?php echo esc_html($CURRENCY); ?> <?php echo esc_html(number_format((float)$it["price"], 2)); ?></td>
            <td><?php echo esc_html($CURRENCY); ?> <?php echo esc_html(number_format((float)$it["row_total"], 2)); ?></td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <!-- TOTALS -->
  <div style="display:flex; justify-content:flex-end; margin-top:12px;">
    <table class="widefat striped" style="max-width:420px;">
      <tbody>
        <tr>
          <th style="width:60%;">Subtotal</th>
          <td style="text-align:right;"><?php echo esc_html($CURRENCY); ?> <?php echo esc_html(number_format((float)$invoice["subtotal"], 2)); ?></td>
        </tr>

        <tr>
          <th>Discount</th>
          <td style="text-align:right;"><?php echo esc_html($CURRENCY); ?> <?php echo esc_html(number_format((float)$invoice["discount"], 2)); ?></td>
        </tr>

        <tr>
          <th>Tax</th>
          <td style="text-align:right;"><?php echo esc_html($CURRENCY); ?> <?php echo esc_html(number_format((float)$invoice["total_tax"], 2)); ?></td>
        </tr>

        <tr>
          <th><b>Total</b></th>
          <td style="text-align:right;"><b><?php echo esc_html($CURRENCY); ?> <?php echo esc_html(number_format((float)$invoice["total_amount"], 2)); ?></b></td>
        </tr>
      </tbody>
    </table>
  </div>

</div>
