<?php

declare(strict_types=1);

namespace Instinctor\Services;

use Instinctor\Core\Config;
use Instinctor\Core\DB;
use Instinctor\Core\Auth;
use Instinctor\Core\Mailer;


if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * Order Note Service
 * Manages order notes (internal and customer-facing)
 */
class OrderNoteService
{
    public static function getNotes(int $orderId, bool $customerOnly = false): array
    {
        $p = DB::prefix();
        
        $where = $customerOnly ? " AND is_customer_note = 1" : "";
        
        return DB::get_results(DB::prepare(
            "SELECT n.*, u.display_name as created_by_name 
             FROM {$p}instinctor_order_notes n
             LEFT JOIN {$p}users u ON n.created_by = u.ID
             WHERE n.order_id = %d $where
             ORDER BY n.created_at DESC",
            $orderId
        ));
    }

    public static function getNote(int $id): ?object
    {
        $p = DB::prefix();
        return DB::get_row(DB::prepare(
            "SELECT * FROM {$p}instinctor_order_notes WHERE id = %d",
            $id
        ));
    }

    public static function addNote(int $orderId, string $note, bool $isCustomerNote = false, bool $sendEmail = false): int
    {
        
        DB::insert(
            DB::prefix() . 'instinctor_order_notes',
            [
                'order_id' => $orderId,
                'note' => sanitize_textarea_field($note),
                'is_customer_note' => $isCustomerNote ? 1 : 0,
                'created_by' => Auth::userId() ?: null,
            ],
            ['%d', '%s', '%d', '%d']
        );
        
        $noteId = (int) DB::insert_id();
        
        // Send email to customer if requested
        if ($noteId && $isCustomerNote && $sendEmail) {
            self::sendNoteEmail($orderId, $note);
        }
        
        return $noteId;
    }

    public static function deleteNote(int $id): bool
    {
        return DB::delete(
            DB::prefix() . 'instinctor_order_notes',
            ['id' => $id],
            ['%d']
        ) !== false;
    }

    public static function addSystemNote(int $orderId, string $note): int
    {
        
        DB::insert(
            DB::prefix() . 'instinctor_order_notes',
            [
                'order_id' => $orderId,
                'note' => $note,
                'is_customer_note' => 0,
                'created_by' => null, // System note
            ],
            ['%d', '%s', '%d', '%d']
        );
        
        return (int) DB::insert_id();
    }

    private static function sendNoteEmail(int $orderId, string $note): void
    {
        $p = DB::prefix();
        
        $order = DB::get_row(DB::prepare(
            "SELECT * FROM {$p}instinctor_orders WHERE id = %d",
            $orderId
        ));
        
        if (!$order) {
            return;
        }
        
        $billing = json_decode($order->billing_address, true) ?: [];
        $customerName = trim(($billing['first_name'] ?? '') . ' ' . ($billing['last_name'] ?? ''));
        
        // Resolve email from customers table, fallback to billing JSON
        $customerEmail = '';
        if ($order->customer_id) {
            $customerEmail = DB::get_var(DB::prepare(
                "SELECT email FROM {$p}instinctor_customers WHERE id = %d",
                $order->customer_id
            )) ?: '';
        }
        if (empty($customerEmail)) {
            $customerEmail = $billing['email'] ?? '';
        }
        if (empty($customerEmail)) {
            return;
        }
        
        /* translators: %s: order number. */
        $subject = sprintf( __( 'Note added to your order #%s', 'instinctor' ), $order->order_number );

        $heading = __( 'A note has been added to your order', 'instinctor' );

        /* translators: 1: customer name, 2: order number, 3: note text. */
        $body = sprintf(
            __( "Hi %1\$s,\n\nThe following note has been added to your order #%2\$s:\n\n%3\$s\n\nIf you have any questions, please don't hesitate to contact us.", 'instinctor' ),
            $customerName,
            $order->order_number,
            $note
        );

$html = self::buildEmailHtml($heading, $body);
        
        $headers = [
            'Content-Type: text/html; charset=UTF-8',
            'From: ' . get_bloginfo('name') . ' <' . Config::get('admin_email') . '>',
        ];
        
        Mailer::send($customerEmail, $subject, $html);
    }

    private static function buildEmailHtml(string $heading, string $body): string
    {
        $storeName = get_bloginfo('name');
        $storeUrl = home_url();
        $bodyHtml = nl2br(esc_html($body));
        
        return '<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"></head>
<body style="margin:0; padding:0; background:#f5f5f7; font-family:-apple-system,BlinkMacSystemFont,sans-serif;">
    <table width="100%" cellpadding="0" cellspacing="0" style="background:#f5f5f7; padding:40px 20px;">
        <tr><td align="center">
            <table width="600" cellpadding="0" cellspacing="0" style="background:#fff; border-radius:8px; overflow:hidden;">
                <tr><td style="padding:32px 40px; background:#1d1d1f; color:#fff;">
                    <h1 style="margin:0; font-size:24px;">' . esc_html($heading) . '</h1>
                </td></tr>
                <tr><td style="padding:32px 40px; font-size:15px; line-height:1.6; color:#1d1d1f;">
                    ' . $bodyHtml . '
                </td></tr>
                <tr><td style="padding:24px 40px; background:#f5f5f7; text-align:center; font-size:13px; color:#86868b;">
                    <a href="' . esc_url($storeUrl) . '" style="color:#1d1d1f; text-decoration:none;">' . esc_html($storeName) . '</a>
                </td></tr>
            </table>
        </td></tr>
    </table>
</body>
</html>';
    }
}
