<?php

class Mail {
    private $host;
    private $port;
    private $username;
    private $password;
    private $from;
    private $fromName;
    private $debug;

    public function __construct() {
        require_once __DIR__ . '/../config/email.php';

        $this->host = SMTP_HOST;
        $this->port = SMTP_PORT;
        $this->username = SMTP_USERNAME;
        $this->password = SMTP_PASSWORD;
        $this->from = SMTP_FROM_EMAIL;
        $this->fromName = SMTP_FROM_NAME;
        $this->debug = MAIL_DEBUG;
    }

    /**
     * Send email via SMTP
     */
    public function send($to, $subject, $message, $isHtml = true) {
        try {
            // Connect to SMTP server
            $smtp = fsockopen($this->host, $this->port, $errno, $errstr, 10);

            if (!$smtp) {
                throw new Exception("SMTP Connection failed: $errstr ($errno)");
            }

            // Set timeout
            stream_set_timeout($smtp, 10);

            // Get server response
            $response = fgets($smtp, 1024);
            $this->debug ? $this->log("Server: " . trim($response)) : null;

            // Send EHLO command
            $this->sendCommand($smtp, "EHLO " . gethostname());
            $this->readResponse($smtp);

            // Start TLS
            $this->sendCommand($smtp, "STARTTLS");
            $this->readResponse($smtp);

            // Enable crypto
            stream_context_set_option($smtp, 'ssl', 'allow_self_signed', true);
            stream_socket_enable_crypto($smtp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);

            // Send EHLO again after TLS
            $this->sendCommand($smtp, "EHLO " . gethostname());
            $this->readResponse($smtp);

            // Authenticate
            $this->sendCommand($smtp, "AUTH LOGIN");
            $this->readResponse($smtp);

            $this->sendCommand($smtp, base64_encode($this->username));
            $this->readResponse($smtp);

            $this->sendCommand($smtp, base64_encode($this->password));
            $this->readResponse($smtp);

            // Send email
            $this->sendCommand($smtp, "MAIL FROM: <" . $this->from . ">");
            $this->readResponse($smtp);

            $this->sendCommand($smtp, "RCPT TO: <" . $to . ">");
            $this->readResponse($smtp);

            $this->sendCommand($smtp, "DATA");
            $this->readResponse($smtp);

            // Build email header
            $headers = "From: " . $this->fromName . " <" . $this->from . ">\r\n";
            $headers .= "To: " . $to . "\r\n";
            $headers .= "Subject: " . $subject . "\r\n";
            $headers .= "MIME-Version: 1.0\r\n";

            if ($isHtml) {
                $headers .= "Content-type: text/html; charset=UTF-8\r\n";
            } else {
                $headers .= "Content-type: text/plain; charset=UTF-8\r\n";
            }

            $headers .= "X-Mailer: KasirMurah\r\n";

            // Send headers and message
            fwrite($smtp, $headers . "\r\n" . $message . "\r\n.\r\n");
            $this->readResponse($smtp);

            // Send QUIT
            $this->sendCommand($smtp, "QUIT");
            $this->readResponse($smtp);

            fclose($smtp);
            return true;

        } catch (Exception $e) {
            $this->log("Email error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * Send command to SMTP server
     */
    private function sendCommand($smtp, $command) {
        fwrite($smtp, $command . "\r\n");
        $this->debug ? $this->log("Command: " . $command) : null;
    }

    /**
     * Read response from SMTP server
     */
    private function readResponse($smtp) {
        $response = '';
        while ($line = fgets($smtp, 1024)) {
            $response .= $line;
            if (substr($line, 3, 1) == ' ') break;
        }
        $this->debug ? $this->log("Response: " . trim($response)) : null;
        return $response;
    }

    /**
     * Log debug messages
     */
    private function log($message) {
        error_log("[Mail] " . $message);
    }
}

?>
