<?php
/**
 * svc-notify.php — اعلان ایمیل/SMS گزارش فنی
 */
if ( ! defined( 'ABSPATH' ) ) exit;

class Svc_Notify {

    public static function send_report_finalized( array $report ): array {
        $sent = [ 'email' => false, 'sms' => false ];
        $phone = preg_replace( '/\D+/', '', $report['phone'] ?? '' );
        $email = sanitize_email( $report['email'] ?? '' );

        require_once ACC_PATH . 'includes/helpers/service-report-render.php';
        $url = Service_Report_Render::public_url( $report['public_token'] ?? '' );
        $no  = $report['report_no'] ?? '';
        $total = number_format( (float) ( $report['total'] ?? 0 ), 0, '.', ',' );

        $body = "گزارش فنی {$no} صادر شد.\nمبلغ: {$total} ریال\nمشاهده: {$url}";

        if ( $email && function_exists( 'wp_mail' ) ) {
            $sent['email'] = (bool) wp_mail(
                $email,
                'گزارش فنی خدمات — ' . $no,
                $body,
                [ 'Content-Type: text/plain; charset=UTF-8' ]
            );
        }

        if ( strlen( $phone ) >= 10 ) {
            $sent['sms'] = self::_send_sms( $phone, mb_substr( $body, 0, 160 ) );
        }

        return $sent;
    }

    public static function send_cost_approval_request( string $phone, string $email, string $code, float $amount ): void {
        $msg = "برآورد هزینه پرونده {$code}: " . number_format( $amount, 0, '.', ',' ) . " ریال — لطفاً در ویجت تأیید کنید.";
        if ( $email && function_exists( 'wp_mail' ) ) {
            wp_mail( $email, 'تأیید هزینه خدمات', $msg );
        }
        if ( $phone ) {
            self::_send_sms( preg_replace( '/\D+/', '', $phone ), $msg );
        }
    }

    private static function _send_sms( string $phone, string $message ): bool {
        $phone = preg_replace( '/\D+/', '', $phone );
        if ( strlen( $phone ) < 10 ) return false;

        $log_dir = ACC_PATH . 'logs';
        if ( ! is_dir( $log_dir ) ) {
            @mkdir( $log_dir, 0755, true );
        }
        $line = date( 'Y-m-d H:i:s' ) . " SMS → {$phone}: {$message}\n";
        @file_put_contents( $log_dir . '/svc-sms.log', $line, FILE_APPEND );

        $hook = apply_filters( 'acc_svc_send_sms', null, $phone, $message );
        return $hook === true;
    }
}
