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

class SIMPINBY_Invoice {

  public static function handle_create_invoice() {
    if (!isset($_POST['simpinby_save_invoice']) && !isset($_POST['simpinby_save_send_invoice'])) {
      return;
    }

    if (!current_user_can("manage_options")) return;

    if (
    ! isset($_POST['_wpnonce']) ||
    ! wp_verify_nonce(
        sanitize_text_field( wp_unslash($_POST['_wpnonce']) ),
            'simpinby_create_invoice'
        )
    ) {
        wp_die('Security check failed');
    }


    global $wpdb;

    $customers_table = $wpdb->prefix . "simpinby_customers";
    $products_table  = $wpdb->prefix . "simpinby_products";
    $invoice_table   = $wpdb->prefix . "simpinby_invoices";
    $items_table     = $wpdb->prefix . "simpinby_invoice_items";

    // ----------------------------
    // 1) Get Settings
    // ----------------------------
    $invoice_num_settings = get_option("simpinby_invoice_number_settings", [
      "prefix" => "INV",
      "padding" => 6,
      "start_number" => 1
    ]);

    $prefix  = sanitize_text_field($invoice_num_settings["prefix"] ?? "INV");
    $padding = intval($invoice_num_settings["padding"] ?? 6);

    if ($padding < 1) $padding = 1;
    if ($padding > 12) $padding = 12;

    // ----------------------------
    // 2) Get Form Data
    // ----------------------------
    $customer_id = isset($_POST["customer_id"])
    ? absint( wp_unslash($_POST["customer_id"]) )
    : 0;
    $customer_name = isset($_POST["customer_name"])
    ? sanitize_text_field( wp_unslash($_POST["customer_name"]) )
    : "";

    $customer_phone = isset($_POST["customer_phone"])
    ? sanitize_text_field( wp_unslash($_POST["customer_phone"]) )
    : "";

    $customer_address = isset($_POST["customer_address"])
    ? sanitize_textarea_field( wp_unslash($_POST["customer_address"]) )
    : "";

    $customer_email = isset($_POST["customer_email"])
    ? sanitize_email( wp_unslash($_POST["customer_email"]) )
    : "";


    $tax_id = isset($_POST["tax_id"])
    ? sanitize_text_field( wp_unslash($_POST["tax_id"]) )
    : "";

    $discount = isset($_POST["discount"])
    ? floatval( wp_unslash($_POST["discount"]) )
    : 0;


    $items = isset($_POST["items"]) && is_array($_POST["items"])
    ? wp_unslash($_POST["items"])
    : [];


    if ($customer_name === "") {
      wp_die("Customer name is required.");
    }

    if (empty($items)) {
      wp_die("At least one invoice item is required.");
    }

    // ----------------------------
    // 3) Resolve Tax Details
    // ----------------------------
    $tax_settings = get_option("simpinby_tax_settings", ["default_tax_id" => "", "taxes" => []]);
    $taxes = $tax_settings["taxes"] ?? [];

    $tax_name = "";
    $tax_percent = 0;

    foreach ($taxes as $t) {
      if ($t["id"] === $tax_id) {
        $tax_name = sanitize_text_field($t["name"]);
        $tax_percent = floatval($t["percent"]);
        break;
      }
    }

    // ----------------------------
    // 4) Create or Update Customer
    // ----------------------------
    if ($customer_id > 0) {
      // Update existing customer (optional)
      $wpdb->update(
          $customers_table,
          [
              "name" => $customer_name,
              "phone" => $customer_phone,
              "email" => $customer_email,
              "address" => $customer_address
          ],
          ["id" => $customer_id],
          ["%s", "%s", "%s", "%s"],
          ["%d"]
      );

    } else {
      // Create new customer
     $wpdb->insert(
      $customers_table,
          [
              "name" => $customer_name,
              "phone" => $customer_phone,
              "email" => $customer_email,
              "address" => $customer_address
          ],
          ["%s", "%s", "%s", "%s"]
     );

      $customer_id = $wpdb->insert_id;
    }

    // ----------------------------
    // 5) Calculate Totals
    // ----------------------------
    $subtotal = 0;
    $clean_items = [];

    foreach ($items as $row) {

      $product_id = isset($row["product_id"])
          ? absint($row["product_id"])
          : 0;

      $product_name = isset($row["product_name"])
          ? sanitize_text_field($row["product_name"])
          : "";

      $qty = isset($row["qty"])
          ? absint($row["qty"])
          : 1;

      $price = isset($row["price"])
          ? floatval($row["price"])
          : 0;

      if ($product_name === "") continue;
      if ($qty < 1) $qty = 1;
      if ($price < 0) $price = 0;

      $row_total = $qty * $price;
      $subtotal += $row_total;

      $clean_items[] = [
        "product_id" => $product_id,
        "product_name" => $product_name,
        "qty" => $qty,
        "price" => $price,
        "row_total" => $row_total
      ];
    }

    if (empty($clean_items)) {
      wp_die("Please add valid invoice items.");
    }

    if ($discount < 0) $discount = 0;
    if ($discount > $subtotal) $discount = $subtotal;

    $after_discount = $subtotal - $discount;
    $total_tax = ($after_discount * $tax_percent) / 100;
    $total_amount = $after_discount + $total_tax;

    // ----------------------------
    // 6) Insert Invoice First (no invoice_number yet)
    // ----------------------------
    $wpdb->insert(
        $invoice_table,
        [
            "invoice_number" => "",
            "customer_id" => $customer_id,
            "status" => "unpaid",
            "is_archived" => 0,
            "tax_name" => $tax_name,
            "tax_percent" => $tax_percent,
            "discount" => $discount,
            "subtotal" => $subtotal,
            "total_tax" => $total_tax,
            "total_amount" => $total_amount
        ],
        ["%s","%d","%s","%d","%s","%f","%f","%f","%f","%f"]
    );


    $invoice_id = $wpdb->insert_id;

    if (!$invoice_id) {
      wp_die("Invoice creation failed.");
    }

    // ----------------------------
    // 7) Generate Safe Invoice Number
    // Using invoice_id ensures no duplicates
    // ----------------------------
    $invoice_number = $prefix . "-" . str_pad($invoice_id, $padding, "0", STR_PAD_LEFT);

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


    // ----------------------------
    // 8) Insert Invoice Items
    // ----------------------------
    foreach ($clean_items as $it) {

      // If product_id not provided, create product
      if ($it["product_id"] <= 0) {
        // check if product exists by name
        $existing = $wpdb->get_var(
          $wpdb->prepare("SELECT id FROM $products_table WHERE name=%s LIMIT 1", $it["product_name"])
        );

        if ($existing) {
          $it["product_id"] = intval($existing);
        } else {
          $wpdb->insert(
              $products_table,
              ["name" => $it["product_name"]],
              ["%s"]
          );

          $it["product_id"] = $wpdb->insert_id;
        }
      }

      $wpdb->insert(
          $items_table,
          [
              "invoice_id" => $invoice_id,
              "product_id" => $it["product_id"],
              "product_name" => $it["product_name"],
              "qty" => $it["qty"],
              "price" => $it["price"],
              "row_total" => $it["row_total"]
          ],
          ["%d","%d","%s","%d","%f","%f"]
      );

    }

    // ----------------------------
    // 9) Redirect after Save
    // ----------------------------
    $redirect_url = admin_url("admin.php?page=simpinby-invoices");

    // Save & Send
    if (isset($_POST["simpinby_save_send_invoice"])) {
    // get customer email from form
    $to_email = isset($_POST["customer_email"])
    ? sanitize_email( wp_unslash($_POST["customer_email"]) )
    : "";

    // Save email into customer table
    if ($to_email && is_email($to_email)) {
        $wpdb->update(
            $customers_table,
            ["email" => $to_email],
            ["id" => $customer_id],
            ["%s"],
            ["%d"]
        );
    }

    $res = SIMPINBY_Mail::send_invoice_email($invoice_id, $to_email);

      if ($res["success"]) {
          $redirect_url = admin_url(
              "admin.php?page=simpinby-invoices&action=view&id={$invoice_id}&mail=sent"
          );

          $redirect_url = add_query_arg(
              '_wpnonce',
              wp_create_nonce('simpinby_view_invoice_' . $invoice_id),
              $redirect_url
          );
      } else {
          $redirect_url = admin_url(
              "admin.php?page=simpinby-invoices&action=view&id={$invoice_id}&mail=failed"
          );

          $redirect_url = add_query_arg(
              '_wpnonce',
              wp_create_nonce('simpinby_view_invoice_' . $invoice_id),
              $redirect_url
          );
      }
    }

    wp_safe_redirect( esc_url_raw($redirect_url) );
    exit;
  }
}
