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

class SIMPINBY_Mail {

  public static function send_invoice_email($invoice_id, $to_email) {
    global $wpdb;

    if (!$to_email || !is_email($to_email)) {
      return ["success" => false, "message" => "Invalid customer email."];
    }

    $invoice_table = $wpdb->prefix . "simpinby_invoices";
    $customers     = $wpdb->prefix . "simpinby_customers";

    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    $invoice = $wpdb->get_row(
      $wpdb->prepare(
        "SELECT inv.*, c.name as customer_name, 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) {
      return ["success" => false, "message" => "Invoice not found."];
    }

    // Load mail settings
    $mail = get_option("simpinby_mail_settings", [
      "subject" => "Your Invoice {invoice_number}",
      "message" => "Hello {customer_name},\nPlease find invoice attached."
    ]);

    $subject = $mail["subject"];
    $message = $mail["message"];

    // Replace variables
    $subject = str_replace("{customer_name}", $invoice["customer_name"], $subject);
    $subject = str_replace("{invoice_number}", $invoice["invoice_number"], $subject);
    $subject = str_replace("{invoice_total}", number_format((float)$invoice["total_amount"], 2), $subject);
    $subject = str_replace("{invoice_date}", wp_date(get_option('date_format'),strtotime($invoice["created_at"])), $subject);

    $message = str_replace("{customer_name}", $invoice["customer_name"], $message);
    $message = str_replace("{invoice_number}", $invoice["invoice_number"], $message);
    $message = str_replace("{invoice_total}", number_format((float)$invoice["total_amount"], 2), $message);
    $message = str_replace("{invoice_date}", wp_date(get_option('date_format'),strtotime($invoice["created_at"])), $message);

    // Generate PDF temporarily
    $pdf_path = self::generate_pdf_temp($invoice_id, $invoice["invoice_number"]);

    if (!$pdf_path) {
      return ["success" => false, "message" => "Failed to generate PDF."];
    }

    $headers = ["Content-Type: text/plain; charset=UTF-8"];
    $attachments = [$pdf_path];

    $sent = wp_mail($to_email, $subject, $message, $headers, $attachments);


    // Cleanup temp file
    if (file_exists($pdf_path)) {
      wp_delete_file($pdf_path);
    }

    if ($sent) {
      return ["success" => true, "message" => "Invoice email sent successfully."];
    }
    

    return ["success" => false, "message" => "Email sending failed. Check SMTP configuration."];
  }

  private static function generate_pdf_temp($invoice_id, $invoice_number) {
    // We will reuse Dompdf HTML template but save as file
    if (!class_exists("SIMPINBY_PDF")) return false;

    $upload_dir = wp_upload_dir();
    $dir = trailingslashit($upload_dir["basedir"]) . "simpinby-invoice-manager/";

    if (!file_exists($dir)) {
      wp_mkdir_p($dir);
    }

    $clean_invoice_number = sanitize_file_name($invoice_number);
    $file_path = $dir . $clean_invoice_number . ".pdf";


    // Build HTML same as SIMPINBY_PDF
    global $wpdb;

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

    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    $invoice = $wpdb->get_row(
      $wpdb->prepare(
        "SELECT inv.*, c.name as customer_name, c.phone as customer_phone, c.address as customer_address
        FROM {$invoice_table} inv
        LEFT JOIN {$customers} c ON c.id = inv.customer_id
        WHERE inv.id = %d",
        $invoice_id
      ),
      ARRAY_A
    );


    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    $items = $wpdb->get_results(
      $wpdb->prepare(
        "SELECT * FROM {$items_table} WHERE invoice_id = %d",
        $invoice_id
      ),
      ARRAY_A
    );


    $pdf_settings = get_option("simpinby_pdf_settings", [
      "company_name" => "My Company",
      "footer_text" => "Thank you for your business!",
      "logo_url" => ""
    ]);

    ob_start();
    include SIMPINBY_PLUGIN_PATH . "templates/invoice-pdf-template.php";
    $html = ob_get_clean();

    // Dompdf render to file
    $options = new \Dompdf\Options();
    $options->set('isRemoteEnabled', true);
    $options->set('defaultFont', 'DejaVu Sans');

    $dompdf = new \Dompdf\Dompdf($options);
    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();

    $output = $dompdf->output();
    file_put_contents($file_path, $output);

    return $file_path;
  }
}
