<?php
// app/Core/Mailer.php - Email Sending Class - PRODUCTION READY

class Mailer {
    private $from_email;
    private $from_name;
    private $smtp_host;
    private $smtp_port;
    private $smtp_username;
    private $smtp_password;
    
    public function __construct() {
        $this->from_email = MAIL_FROM_EMAIL;
        $this->from_name = MAIL_FROM_NAME;
        $this->smtp_host = MAIL_HOST;
        $this->smtp_port = MAIL_PORT;
        $this->smtp_username = MAIL_USERNAME;
        $this->smtp_password = MAIL_PASSWORD;
    }
    
    /**
     * Send welcome email
     */
    public function sendWelcomeEmail($to, $name, $user_type = 'customer') {
        $subject = "Welcome to " . APP_NAME;
        $body = $this->getTemplate('welcome', [
            'first_name' => $name,
            'email' => $to,
            'user_type' => $user_type,
            'app_name' => APP_NAME,
            'app_url' => APP_URL
        ]);
        
        return $this->send($to, $subject, $body);
    }
    
    /**
     * Send email verification
     */
    public function sendVerificationEmail($to, $name, $token, $user_type = 'customer') {
        $subject = "Verify Your Email Address";
        $verification_url = APP_URL . "/auth/verify-email.php?token=" . $token;
        
        $body = $this->getTemplate('verify-email', [
            'first_name' => $name,
            'email' => $to,
            'user_type' => $user_type,
            'verification_url' => $verification_url,
            'app_name' => APP_NAME
        ]);
        
        return $this->send($to, $subject, $body);
    }
    
    /**
     * Send password reset email
     */
    public function sendPasswordResetEmail($to, $name, $token) {
        $subject = "Reset Your Password";
        $reset_url = APP_URL . "/auth/reset-password.php?token=" . $token;
        
        $body = $this->getTemplate('password-reset', [
            'first_name' => $name,
            'email' => $to,
            'reset_url' => $reset_url,
            'ip_address' => $_SERVER['REMOTE_ADDR'] ?? 'Unknown',
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown',
            'app_name' => APP_NAME
        ]);
        
        return $this->send($to, $subject, $body);
    }
    
    /**
     * Send vendor approval email
     */
    public function sendVendorApprovalEmail($to, $business_name) {
        $subject = "Vendor Account Approved - " . APP_NAME;
        
        $body = $this->getTemplate('vendor-approved', [
            'business_name' => $business_name,
            'email' => $to,
            'app_name' => APP_NAME,
            'app_url' => APP_URL
        ]);
        
        return $this->send($to, $subject, $body);
    }
    
    /**
     * Send vendor rejection email
     */
    public function sendVendorRejectionEmail($to, $business_name, $reason) {
        $subject = "Vendor Application Status - " . APP_NAME;
        
        $body = $this->getTemplate('vendor-rejected', [
            'business_name' => $business_name,
            'email' => $to,
            'reason' => $reason,
            'app_name' => APP_NAME,
            'app_url' => APP_URL
        ]);
        
        return $this->send($to, $subject, $body);
    }
    
    /**
     * Send order confirmation to customer - PRODUCTION
     */
    public function sendOrderConfirmation($orderData) {
        $subject = "Order Confirmed - #{$orderData['order_number']} - " . APP_NAME;
        
        $body = $this->getTemplate('order-confirmation', [
            'customer_name' => $orderData['customer_name'],
            'order_number' => $orderData['order_number'],
            'order_id' => $orderData['id'],
            'item_title' => $orderData['item_title'],
            'vendor_name' => $orderData['vendor_name'],
            'start_date' => $orderData['start_date'],
            'end_date' => $orderData['end_date'],
            'total_days' => $orderData['rental_days'],
            'quantity' => $orderData['quantity'],
            'status' => $orderData['status'],
            'daily_rate' => $orderData['daily_rate'] ?? 0,
            'subtotal' => $orderData['subtotal'],
            'platform_commission' => $orderData['platform_fee'] ?? 0,
            'tax_amount' => 0,
            'deposit_amount' => $orderData['security_deposit'] ?? 0,
            'total_amount' => $orderData['total_amount'],
            'vendor_contact' => [
                'phone' => $orderData['vendor_phone'] ?? '',
                'email' => $orderData['vendor_email'] ?? ''
            ],
            'vendor_location' => [
                'city' => $orderData['vendor_city'] ?? '',
                'state' => $orderData['vendor_state'] ?? ''
            ],
            'app_name' => APP_NAME,
            'app_url' => APP_URL
        ]);
        
        return $this->send($orderData['customer_email'], $subject, $body);
    }
    
    /**
     * Send order notification to vendor - PRODUCTION
     */
    public function sendVendorOrderNotification($orderData) {
        $subject = "New Order - #{$orderData['order_number']} - " . APP_NAME;
        
        // Use actual platform fee from order (based on item category)
        $platform_fee = $orderData['platform_fee'] ?? 0;
        $vendor_earnings = $orderData['subtotal'] - $platform_fee;
        
        // Calculate commission rate (percentage)
        $commission_rate = ($orderData['subtotal'] > 0) 
            ? ($platform_fee / $orderData['subtotal']) * 100 
            : 0;
        
        $body = $this->getTemplate('order-notification-vendor', [
            'vendor_name' => $orderData['vendor_name'],
            'order_number' => $orderData['order_number'],
            'order_id' => $orderData['id'],
            'item_title' => $orderData['item_title'],
            'customer_name' => $orderData['customer_name'],
            'customer_email' => $orderData['customer_email'],
            'customer_phone' => $orderData['customer_phone'] ?? 'Not provided',
            'start_date' => $orderData['start_date'],
            'end_date' => $orderData['end_date'],
            'total_days' => $orderData['rental_days'],
            'quantity' => $orderData['quantity'],
            'status' => $orderData['status'],
            'total_amount' => $orderData['subtotal'],
            'commission_rate' => $commission_rate,
            'commission_amount' => $platform_fee,
            'vendor_earnings' => $vendor_earnings,
            'customer_message' => $orderData['special_instructions'] ?? '',
            'app_name' => APP_NAME,
            'app_url' => APP_URL
        ]);
        
        return $this->send($orderData['vendor_email'], $subject, $body);
    }
    
    /**
     * Get email template
     */
    public function getTemplate($template_name, $data) {
        $template_path = ROOT_PATH . "/templates/email/{$template_name}.php";
        
        if (!file_exists($template_path)) {
            log_message("Email template not found: {$template_name}", 'error');
            return $this->getDefaultTemplate($data);
        }
        
        extract($data);
        ob_start();
        include $template_path;
        $content = ob_get_clean();
        
        return $content;
    }
    
    /**
     * Get default email template
     */
    private function getDefaultTemplate($data) {
        $message = isset($data['message']) ? $data['message'] : 'You have a new notification from ' . APP_NAME;
        
        return "
        <html>
        <body style='font-family: Arial, sans-serif; line-height: 1.6; color: #333;'>
            <div style='max-width: 600px; margin: 0 auto; padding: 20px;'>
                <h2 style='color: #2ecc71;'>" . APP_NAME . "</h2>
                <p>{$message}</p>
                <p>Best regards,<br>" . APP_NAME . " Team</p>
            </div>
        </body>
        </html>
        ";
    }
    
    /**
     * Send test email
     */
    public function sendTestEmail($to) {
        $subject = "Test Email from " . APP_NAME;
        $body = "
        <html>
        <body style='font-family: Arial, sans-serif;'>
            <h2>Test Email</h2>
            <p>This is a test email from your rentidium application.</p>
            <p>If you received this, your email configuration is working correctly!</p>
        </body>
        </html>
        ";
        
        return $this->send($to, $subject, $body);
    }

    /**
     * Send email using SMTP - PRODUCTION VERSION
     */
    public function send($to, $subject, $body, $is_html = true) {
        try {
            if ($is_html) {
                $body = $this->wrapInBasicTemplate($body);
            }
            
            $headers = "From: {$this->from_name} <{$this->from_email}>\r\n";
            $headers .= "Reply-To: {$this->from_email}\r\n";
            $headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";
            $headers .= "MIME-Version: 1.0\r\n";
            
            if ($is_html) {
                $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
            } else {
                $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
            }
            
            // Try SMTP first
            $result = $this->sendViaSMTP($to, $subject, $body, $headers);
            
            if ($result) {
                log_message("Email sent successfully to: {$to}", 'info');
                return true;
            }
            
            // Fallback to PHP mail() if SMTP fails
            log_message("SMTP failed, trying PHP mail() for: {$to}", 'warning');
            $result = mail($to, $subject, $body, $headers);
            
            if ($result) {
                log_message("Email sent via PHP mail() to: {$to}", 'info');
                return true;
            }
            
            log_message("All email methods failed for: {$to}", 'error');
            return false;
            
        } catch (Exception $e) {
            log_message("Email error: " . $e->getMessage(), 'error');
            return false;
        }
    }
    
    /**
     * Send email via SMTP using socket - WITH TIMEOUT HANDLING
     */
    private function sendViaSMTP($to, $subject, $body, $headers) {
        // Set connection timeout
        $timeout = 10;
        
        // Suppress connection warnings
        $smtp = @fsockopen($this->smtp_host, $this->smtp_port, $errno, $errstr, $timeout);
        
        if (!$smtp) {
            log_message("SMTP Connection failed: {$errstr} ({$errno})", 'warning');
            return false;
        }
        
        // Set stream timeout
        stream_set_timeout($smtp, $timeout);
        
        try {
            // Read server response
            if (!$this->getResponse($smtp)) {
                fclose($smtp);
                return false;
            }
            
            // Send EHLO
            fputs($smtp, "EHLO {$this->smtp_host}\r\n");
            if (!$this->getResponse($smtp)) {
                fclose($smtp);
                return false;
            }
            
            // Start TLS if using port 587
            if ($this->smtp_port == 587) {
                fputs($smtp, "STARTTLS\r\n");
                if (!$this->getResponse($smtp)) {
                    fclose($smtp);
                    return false;
                }
                
                if (!stream_socket_enable_crypto($smtp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
                    log_message("TLS encryption failed", 'warning');
                    fclose($smtp);
                    return false;
                }
                
                fputs($smtp, "EHLO {$this->smtp_host}\r\n");
                if (!$this->getResponse($smtp)) {
                    fclose($smtp);
                    return false;
                }
            }
            
            // Authenticate
            fputs($smtp, "AUTH LOGIN\r\n");
            if (!$this->getResponse($smtp)) {
                fclose($smtp);
                return false;
            }
            
            fputs($smtp, base64_encode($this->smtp_username) . "\r\n");
            if (!$this->getResponse($smtp)) {
                fclose($smtp);
                return false;
            }
            
            fputs($smtp, base64_encode($this->smtp_password) . "\r\n");
            $auth_response = $this->getResponse($smtp);
            
            if (!$auth_response || strpos($auth_response, '235') === false) {
                log_message("SMTP Authentication failed", 'warning');
                fclose($smtp);
                return false;
            }
            
            // Send MAIL FROM
            fputs($smtp, "MAIL FROM: <{$this->from_email}>\r\n");
            if (!$this->getResponse($smtp)) {
                fclose($smtp);
                return false;
            }
            
            // Send RCPT TO
            fputs($smtp, "RCPT TO: <{$to}>\r\n");
            if (!$this->getResponse($smtp)) {
                fclose($smtp);
                return false;
            }
            
            // Send DATA
            fputs($smtp, "DATA\r\n");
            if (!$this->getResponse($smtp)) {
                fclose($smtp);
                return false;
            }
            
            // Send headers and body
            fputs($smtp, "To: {$to}\r\n");
            fputs($smtp, "Subject: {$subject}\r\n");
            fputs($smtp, $headers);
            fputs($smtp, "\r\n");
            fputs($smtp, $body . "\r\n");
            fputs($smtp, ".\r\n");
            
            if (!$this->getResponse($smtp)) {
                fclose($smtp);
                return false;
            }
            
            // Send QUIT
            fputs($smtp, "QUIT\r\n");
            $this->getResponse($smtp);
            
            fclose($smtp);
            return true;
            
        } catch (Exception $e) {
            log_message("SMTP exception: " . $e->getMessage(), 'warning');
            if (is_resource($smtp)) {
                fclose($smtp);
            }
            return false;
        }
    }
    
    /**
     * Get SMTP server response - WITH TIMEOUT CHECK
     */
    private function getResponse($smtp) {
        $response = '';
        $timeout_count = 0;
        
        while ($line = fgets($smtp, 515)) {
            $response .= $line;
            
            // Check for timeout
            $info = stream_get_meta_data($smtp);
            if ($info['timed_out']) {
                log_message("SMTP timeout while reading response", 'warning');
                return false;
            }
            
            if (substr($line, 3, 1) == ' ') {
                break;
            }
            
            // Prevent infinite loop
            if (++$timeout_count > 100) {
                log_message("SMTP response loop timeout", 'warning');
                return false;
            }
        }
        
        return $response;
    }
    
    /**
     * Wrap content in basic HTML template
     */
    private function wrapInBasicTemplate($content) {
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <meta name='viewport' content='width=device-width, initial-scale=1.0'>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; background: #f4f4f4; margin: 0; padding: 0; }
                .container { max-width: 600px; margin: 20px auto; background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
                h1, h2 { color: #27ae60; }
                .button { display: inline-block; padding: 12px 24px; background: #27ae60; color: white !important; text-decoration: none; border-radius: 5px; margin: 10px 0; }
                .button:hover { background: #229954; }
                .footer { margin-top: 30px; padding-top: 20px; border-top: 1px solid #ddd; font-size: 12px; color: #666; text-align: center; }
            </style>
        </head>
        <body>
            <div class='container'>
                {$content}
                <div class='footer'>
                    <p>&copy; " . date('Y') . " " . APP_NAME . ". All rights reserved.</p>
                    <p>This is an automated email. Please do not reply.</p>
                </div>
            </div>
        </body>
        </html>
        ";
    }


    /**
     * ADD THESE 4 METHODS TO YOUR Mailer.php
     * Add them AFTER sendVendorOrderNotification() method (around line 175)
     */

    /**
     * Send order cancellation email to customer
     */
    public function sendOrderCancellationCustomer($orderData, $cancelInfo) {
        $subject = "Order Cancelled - #{$orderData['order_number']} - " . APP_NAME;
        
        $body = $this->getTemplate('order-cancellation-customer', [
            'customer_name' => $orderData['customer_name'],
            'order_number' => $orderData['order_number'],
            'item_title' => $orderData['item_title'],
            'cancelled_by' => $cancelInfo['cancelled_by_name'],
            'cancelled_by_type' => ucfirst($cancelInfo['cancelled_by']),
            'reason' => $cancelInfo['reason'],
            'refund_amount' => $orderData['refund_amount'],
            'app_name' => APP_NAME,
            'app_url' => APP_URL
        ]);
        
        return $this->send($orderData['customer_email'], $subject, $body);
    }

    /**
     * Send order cancellation email to vendor
     */
    public function sendOrderCancellationVendor($orderData, $cancelInfo) {
        $subject = "Order Cancelled - #{$orderData['order_number']} - " . APP_NAME;
        
        $body = $this->getTemplate('order-cancellation-vendor', [
            'vendor_name' => $orderData['vendor_name'],
            'order_number' => $orderData['order_number'],
            'item_title' => $orderData['item_title'],
            'customer_name' => $orderData['customer_name'],
            'cancelled_by' => $cancelInfo['cancelled_by_name'],
            'cancelled_by_type' => ucfirst($cancelInfo['cancelled_by']),
            'reason' => $cancelInfo['reason'],
            'app_name' => APP_NAME,
            'app_url' => APP_URL
        ]);
        
        return $this->send($orderData['vendor_email'], $subject, $body);
    }

    /**
     * Send order completion email to customer
     */
    public function sendOrderCompletionCustomer($orderData, $refundAmount) {
        $subject = "Order Completed - #{$orderData['order_number']} - " . APP_NAME;
        
        $body = $this->getTemplate('order-completion-customer', [
            'customer_name' => $orderData['customer_name'],
            'order_number' => $orderData['order_number'],
            'item_title' => $orderData['item_title'],
            'security_deposit' => $refundAmount,
            'app_name' => APP_NAME,
            'app_url' => APP_URL
        ]);
        
        return $this->send($orderData['customer_email'], $subject, $body);
    }

    /**
     * Send order completion email to vendor
     */
    public function sendOrderCompletionVendor($orderData, $earnings) {
        $subject = "Order Completed - #{$orderData['order_number']} - " . APP_NAME;
        
        $body = $this->getTemplate('order-completion-vendor', [
            'vendor_name' => $orderData['vendor_name'],
            'order_number' => $orderData['order_number'],
            'item_title' => $orderData['item_title'],
            'customer_name' => $orderData['customer_name'],
            'earnings' => $earnings,
            'app_name' => APP_NAME,
            'app_url' => APP_URL
        ]);
        
        return $this->send($orderData['vendor_email'], $subject, $body);
    }


        /**
     * Send new order notification to admin
     */
    public function sendAdminOrderNotification($orderData) {
        $subject = "New Order - #{$orderData['order_number']} - " . APP_NAME;

        $admin_email    = defined('ADMIN_EMAIL') ? ADMIN_EMAIL : 'admin@rentidium.ng';
        $vendor_earnings = $orderData['subtotal'] - ($orderData['platform_fee'] ?? 0);

        $body = $this->getTemplate('order-notification-admin', [
            'order_number'    => $orderData['order_number'],
            'order_id'        => $orderData['id'],
            'item_title'      => $orderData['item_title'],
            'customer_name'   => $orderData['customer_name'],
            'customer_email'  => $orderData['customer_email'],
            'customer_phone'  => $orderData['customer_phone'] ?? '',
            'vendor_name'     => $orderData['vendor_name'],
            'vendor_email'    => $orderData['vendor_email'],
            'vendor_phone'    => $orderData['vendor_phone'] ?? '',
            'start_date'      => $orderData['start_date'],
            'end_date'        => $orderData['end_date'],
            'total_days'      => $orderData['rental_days'],
            'quantity'        => $orderData['quantity'],
            'status'          => $orderData['status'],
            'payment_status'  => $orderData['payment_status'],
            'subtotal'        => $orderData['subtotal'],
            'security_deposit'=> $orderData['security_deposit'] ?? 0,
            'platform_fee'    => $orderData['platform_fee'] ?? 0,
            'vendor_earnings' => $vendor_earnings,
            'total_amount'    => $orderData['total_amount'],
            'app_name'        => APP_NAME,
            'app_url'         => APP_URL
        ]);

        return $this->send($admin_email, $subject, $body);
    }


    /**
     * Send withdrawal approved notification
     * 
     * @param array $withdrawalData Must contain: user_email, user_name, user_type, 
     *                              amount, reference, bank_name, account_number, 
     *                              account_name, processed_at
     * @return bool
     */
    public function sendWithdrawalApproved($withdrawalData) {
        $subject = "Withdrawal Approved - {$withdrawalData['reference']} - " . APP_NAME;
        
        $body = $this->getTemplate('withdrawal-approved', [
            'user_name'       => $withdrawalData['user_name'],
            'user_type'       => $withdrawalData['user_type'],
            'amount'          => $withdrawalData['amount'],
            'reference'       => $withdrawalData['reference'],
            'bank_name'       => $withdrawalData['bank_name'],
            'account_number'  => $withdrawalData['account_number'],
            'account_name'    => $withdrawalData['account_name'],
            'processed_date'  => $withdrawalData['processed_at'] ?? date('Y-m-d H:i:s'),
            'app_name'        => APP_NAME,
            'app_url'         => APP_URL
        ]);
        
        return $this->send($withdrawalData['user_email'], $subject, $body);
    }
    
    /**
     * Send withdrawal rejected notification
     * 
     * @param array $withdrawalData Must contain: user_email, user_name, user_type,
     *                              amount, reference, reason, processed_at
     * @return bool
     */
    public function sendWithdrawalRejected($withdrawalData) {
        $subject = "Withdrawal Request Rejected - {$withdrawalData['reference']} - " . APP_NAME;
        
        $body = $this->getTemplate('withdrawal-rejected', [
            'user_name'       => $withdrawalData['user_name'],
            'user_type'       => $withdrawalData['user_type'],
            'amount'          => $withdrawalData['amount'],
            'reference'       => $withdrawalData['reference'],
            'reason'          => $withdrawalData['reason'] ?? 'Not specified',
            'processed_date'  => $withdrawalData['processed_at'] ?? date('Y-m-d H:i:s'),
            'app_name'        => APP_NAME,
            'app_url'         => APP_URL
        ]);
        
        return $this->send($withdrawalData['user_email'], $subject, $body);
    }


    /**
     * Send order cancellation with penalty email to customer
     * 
     * @param array $orderData Must contain: customer_name, customer_email, order_number,
     *                        rental_amount, security_deposit, penalty_percentage,
     *                        penalty_amount, refund_amount, timing
     * @return bool
     */
    public function sendOrderCancellationWithPenalty($orderData) {
        $subject = "Order Cancelled - #{$orderData['order_number']} - " . APP_NAME;
        
        $body = $this->getTemplate('order-cancellation-penalty', [
            'customer_name'       => $orderData['customer_name'],
            'order_number'        => $orderData['order_number'],
            'rental_amount'       => $orderData['rental_amount'],
            'security_deposit'    => $orderData['security_deposit'],
            'penalty_percentage'  => $orderData['penalty_percentage'],
            'penalty_amount'      => $orderData['penalty_amount'],
            'refund_amount'       => $orderData['refund_amount'],
            'reason'              => $orderData['reason'] ?? 'Customer request',
            'timing'              => $orderData['timing'] ?? '',
            'app_name'            => APP_NAME,
            'app_url'             => APP_URL
        ]);
        
        return $this->send($orderData['customer_email'], $subject, $body);
    }



    /**
     * Send item approved notification to vendor.
     *
     * Called from: admin/item-approve.php
     *
     * @param array $itemData {
     *   vendor_name   string  Vendor business name
     *   vendor_email  string  Vendor email address
     *   item_id       int     Item ID
     *   item_title    string  Item title
     *   app_name      string  Platform name (usually APP_NAME)
     *   app_url       string  Platform URL  (usually APP_URL)
     * }
     * @return bool
     */
    // public function sendItemApproved(array $itemData): bool {
    //     $subject = "Your Item Has Been Approved — " . APP_NAME;
 
    //     $body = $this->getTemplate('item-approved', [
    //         'vendor_name'  => $itemData['vendor_name'],
    //         'vendor_email' => $itemData['vendor_email'],
    //         'item_id'      => $itemData['item_id'],
    //         'item_title'   => $itemData['item_title'],
    //         'app_name'     => APP_NAME,
    //         'app_url'      => APP_URL,
    //     ]);
 
    //     return $this->send($itemData['vendor_email'], $subject, $body);
    // }
 
 
    /**
     * Send item rejected notification to vendor.
     *
     * Called from: admin/item-reject.php
     *
     * @param array $itemData {
     *   vendor_name   string  Vendor business name
     *   vendor_email  string  Vendor email address
     *   item_id       int     Item ID
     *   item_title    string  Item title
     *   reason        string  Reason for rejection
     *   app_name      string  Platform name
     *   app_url       string  Platform URL
     * }
     * @return bool
     */
    // public function sendItemRejected(array $itemData): bool {
    //     $subject = "Item Listing Not Approved — " . APP_NAME;
 
    //     $body = $this->getTemplate('item-rejected', [
    //         'vendor_name'  => $itemData['vendor_name'],
    //         'vendor_email' => $itemData['vendor_email'],
    //         'item_id'      => $itemData['item_id'],
    //         'item_title'   => $itemData['item_title'],
    //         'reason'       => $itemData['reason'] ?? 'No specific reason provided.',
    //         'app_name'     => APP_NAME,
    //         'app_url'      => APP_URL,
    //     ]);
 
    //     return $this->send($itemData['vendor_email'], $subject, $body);
    // }
 
 
    /**
     * Send new item submission notification to admin.
     *
     * Called from: wherever a vendor saves/submits a new item
     * (e.g. vendor/item-add.php or the Item model's create() method).
     *
     * @param array $itemData {
     *   item_id        int     Item ID (just inserted)
     *   item_title     string  Item title
     *   category_name  string  Category name
     *   price_per_day  float   Daily rental price
     *   vendor_name    string  Vendor business name
     *   vendor_email   string  Vendor email address
     *   submitted_at   string  Datetime of submission (optional)
     * }
     * @return bool
     */
    // public function sendNewItemNotification(array $itemData): bool {
    //     $admin_email = defined('ADMIN_EMAIL') ? ADMIN_EMAIL : 'admin@' . parse_url(APP_URL, PHP_URL_HOST);
    //     $subject     = "New Item Submitted for Review — " . APP_NAME;
 
    //     $body = $this->getTemplate('item-new-submission', [
    //         'item_id'       => $itemData['item_id'],
    //         'item_title'    => $itemData['item_title'],
    //         'category_name' => $itemData['category_name'] ?? 'N/A',
    //         'price_per_day' => $itemData['price_per_day'] ?? 0,
    //         'vendor_name'   => $itemData['vendor_name'],
    //         'vendor_email'  => $itemData['vendor_email'],
    //         'submitted_at'  => $itemData['submitted_at'] ?? date('Y-m-d H:i:s'),
    //         'app_name'      => APP_NAME,
    //         'app_url'       => APP_URL,
    //     ]);
 
    //     return $this->send($admin_email, $subject, $body);
    // }


    /**
     * Notify vendor their new item listing was APPROVED.
     * Called from: admin/item-approve.php
     *
     * @param string $to           Vendor email address
     * @param string $vendor_name  Vendor business name
     * @param string $item_title   Item title
     * @return bool
     */
    public function sendItemApproved(string $to, string $vendor_name, string $item_title): bool
    {
        $subject = "Your Item Listing Has Been Approved — " . APP_NAME;
 
        $body = $this->getTemplate('item-approved', [
            'vendor_name' => $vendor_name,
            'item_title'  => $item_title,
            'app_name'    => APP_NAME,
            'app_url'     => APP_URL,
        ]);
 
        return $this->send($to, $subject, $body);
    }
 
 
    /**
     * Notify vendor their new item listing was REJECTED.
     * Called from: admin/item-reject.php
     *
     * @param string $to           Vendor email address
     * @param string $vendor_name  Vendor business name
     * @param string $item_title   Item title
     * @param string $reason       Reason for rejection
     * @return bool
     */
    public function sendItemRejected(string $to, string $vendor_name, string $item_title, string $reason): bool
    {
        $subject = "Your Item Listing Was Not Approved — " . APP_NAME;
 
        $body = $this->getTemplate('item-rejected', [
            'vendor_name' => $vendor_name,
            'item_title'  => $item_title,
            'reason'      => $reason,
            'app_name'    => APP_NAME,
            'app_url'     => APP_URL,
        ]);
 
        return $this->send($to, $subject, $body);
    }
 
 
    /**
     * Notify admin a new item has been submitted and needs review.
     * Called from: wherever a vendor saves a new item listing.
     *
     * @param string $item_id       Newly inserted item ID
     * @param string $item_title    Item title
     * @param string $category_name Category name
     * @param float  $price_per_day Daily rental price
     * @param string $vendor_name   Vendor business name
     * @param string $vendor_email  Vendor email address
     * @param string $submitted_at  Submission datetime (Y-m-d H:i:s)
     * @return bool
     */
    public function sendNewItemNotification(
        int    $item_id,
        string $item_title,
        string $category_name,
        float  $price_per_day,
        string $vendor_name,
        string $vendor_email,
        string $submitted_at = ''
    ): bool {
        $admin_email = defined('ADMIN_EMAIL') ? ADMIN_EMAIL : MAIL_FROM_EMAIL;
        $subject     = "New Item Submitted for Review — " . APP_NAME;
 
        $body = $this->getTemplate('item-new-submission', [
            'item_id'       => $item_id,
            'item_title'    => $item_title,
            'category_name' => $category_name,
            'price_per_day' => $price_per_day,
            'vendor_name'   => $vendor_name,
            'vendor_email'  => $vendor_email,
            'submitted_at'  => $submitted_at ?: date('Y-m-d H:i:s'),
            'app_name'      => APP_NAME,
            'app_url'       => APP_URL,
        ]);
 
        return $this->send($admin_email, $subject, $body);
    }
 
 
    /**
     * Notify vendor their item UPDATE was APPROVED.
     * Called from: admin/item-update-approve.php
     *
     * Reuses the item-approved template (same message applies).
     *
     * @param string $to           Vendor email address
     * @param string $vendor_name  Vendor business name
     * @param string $item_title   Item title
     * @return bool
     */
    public function sendItemUpdateApproved(string $to, string $vendor_name, string $item_title): bool
    {
        $subject = "Your Item Update Has Been Approved — " . APP_NAME;
 
        $body = $this->getTemplate('item-approved', [
            'vendor_name' => $vendor_name,
            'item_title'  => $item_title,
            'app_name'    => APP_NAME,
            'app_url'     => APP_URL,
        ]);
 
        return $this->send($to, $subject, $body);
    }
 
 
    /**
     * Notify vendor their item UPDATE was REJECTED.
     * Called from: admin/item-update-reject.php
     *
     * Reuses the item-rejected template (same message applies).
     *
     * @param string $to           Vendor email address
     * @param string $vendor_name  Vendor business name
     * @param string $item_title   Item title
     * @param string $reason       Reason for rejection
     * @return bool
     */
    public function sendItemUpdateRejected(string $to, string $vendor_name, string $item_title, string $reason): bool
    {
        $subject = "Your Item Update Was Not Approved — " . APP_NAME;
 
        $body = $this->getTemplate('item-rejected', [
            'vendor_name' => $vendor_name,
            'item_title'  => $item_title,
            'reason'      => $reason,
            'app_name'    => APP_NAME,
            'app_url'     => APP_URL,
        ]);
 
        return $this->send($to, $subject, $body);
    }
 
}