<?php
/**
 * Email Helper - Klasa za upravljanje email notifikacijama
 */
class EmailHelper {
    private $site_name;
    private $site_email;
    public $admin_email;
    private $logo_url;
    
    public function __construct() {
        // Dohvatanje osnovnih postavki
        global $conn;
        $this->site_name = get_setting('site_name', 'Hugong Aparati');
        $this->site_email = get_setting('email_from', 'noreply@hugong-aparati.rs');
        $this->admin_email = get_setting('admin_email', 'as.asekulic@gmail.com');
        $this->logo_url = SITE_URL . 'https://test.hugong-aparati.rs/uploads/hugong-logo.png';
    }
    
    /**
     * Šalje email korisniku
     * 
     * @param string $to Email primaoca
     * @param string $subject Naslov emaila
     * @param string $html_content HTML sadržaj emaila
     * @param string $text_content Tekstualni sadržaj emaila
     * @param array $attachments Prilozi (opciono)
     * @return bool Uspeh operacije
     */
    public function sendEmail($to, $subject, $html_content, $text_content, $attachments = []) {
        // Generisanje graničnika za multipart sadržaj
        $boundary = md5(time());
        
        // Email headeri
        $headers = "From: {$this->site_name} <{$this->site_email}>\r\n";
        $headers .= "Reply-To: {$this->site_name} <{$this->admin_email}>\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: multipart/alternative; boundary=\"{$boundary}\"\r\n";
        
        // Telo emaila
        $message = "--{$boundary}\r\n";
        $message .= "Content-Type: text/plain; charset=UTF-8\r\n";
        $message .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
        $message .= $text_content . "\r\n\r\n";
        
        $message .= "--{$boundary}\r\n";
        $message .= "Content-Type: text/html; charset=UTF-8\r\n";
        $message .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
        $message .= $html_content . "\r\n\r\n";
        
        // Dodavanje priloga ako postoje
        if (!empty($attachments)) {
            foreach ($attachments as $attachment) {
                if (file_exists($attachment['path'])) {
                    $file_content = file_get_contents($attachment['path']);
                    $file_content = chunk_split(base64_encode($file_content));
                    
                    $message .= "--{$boundary}\r\n";
                    $message .= "Content-Type: {$attachment['type']}; name=\"{$attachment['name']}\"\r\n";
                    $message .= "Content-Disposition: attachment; filename=\"{$attachment['name']}\"\r\n";
                    $message .= "Content-Transfer-Encoding: base64\r\n\r\n";
                    $message .= $file_content . "\r\n\r\n";
                }
            }
        }
        
        $message .= "--{$boundary}--";
        
        // Slanje emaila
        $result = mail($to, $subject, $message, $headers);
        
        // Logiranje slanja emaila (opciono)
        $this->logEmail($to, $subject, $result);
        
        return $result;
    }
    
    /**
     * Generiše HTML šablon za email
     * 
     * @param string $content Glavni sadržaj emaila
     * @param string $title Naslov (opciono)
     * @return string HTML šablon
     */
    private function generateEmailTemplate($content, $title = '') {
        return '
        <!DOCTYPE html>
        <html lang="sr">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>' . ($title ?: $this->site_name) . '</title>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; }
                .email-container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .email-header { text-align: center; margin-bottom: 30px; }
                .email-header img { max-width: 200px; height: auto; }
                .email-content { background-color: #f9f9f9; padding: 30px; border-radius: 8px; }
                .email-footer { text-align: center; margin-top: 30px; font-size: 12px; color: #777; }
                .button { display: inline-block; background-color: #f6cc00; color: #333; padding: 12px 25px; text-decoration: none; border-radius: 4px; font-weight: bold; }
                h1 { color: #333; font-size: 24px; margin-bottom: 20px; }
                h2 { color: #333; font-size: 18px; margin-top: 30px; margin-bottom: 15px; }
                p { margin-bottom: 15px; }
                table { width: 100%; border-collapse: collapse; margin: 20px 0; }
                table th, table td { padding: 10px; text-align: left; border-bottom: 1px solid #ddd; }
                table th { background-color: #f2f2f2; }
                .total-row th, .total-row td { font-weight: bold; border-top: 2px solid #ddd; }
            </style>
        </head>
        <body>
            <div class="email-container">
                <div class="email-header">
                    <img src="' . $this->logo_url . '" alt="' . $this->site_name . '" />
                </div>
                <div class="email-content">
                    ' . $content . '
                </div>
                <div class="email-footer">
                    <p>&copy; ' . date('Y') . ' ' . $this->site_name . '. Sva prava zadržana.</p>
                    <p>Oskara Davičа 2, 34000 Kragujevac | 065/8-065-065</p>
                </div>
            </div>
        </body>
        </html>';
    }
    
    /**
     * Šalje potvrdu porudžbine kupcu
     * 
     * @param array $order Podaci o porudžbini
     * @param array $order_items Stavke porudžbine
     * @return bool Uspeh operacije
     */
    public function sendOrderConfirmationToCustomer($order, $order_items) {
        // Priprema podataka
        $order_number = $order['order_number'];
        $customer_name = $order['name'];
        
        // Konvertovanje imena u vokativ
        $vocative_name = to_vocative($customer_name);
        
        // Koristimo vokativ ako je dostupan, ili originalno ime ako nije
        $greeting_name = !empty($vocative_name) ? $vocative_name : $customer_name;
        
        $total = number_format($order['total'], 0, ',', '.') . ' RSD';
        
        // Generisanje tabele sa proizvodima
        $products_html = '<table>';
        $products_html .= '<tr><th>Proizvod</th><th>Količina</th><th>Cena</th><th>Ukupno</th></tr>';
        
        $products_text = "Poručeni proizvodi:\n\n";
        
        $items_total = 0;
        foreach ($order_items as $item) {
            $item_total = $item['price'] * $item['quantity'];
            $items_total += $item_total;
            
            $products_html .= '<tr>';
            $products_html .= '<td>' . htmlspecialchars($item['product_name']) . '</td>';
            $products_html .= '<td>' . $item['quantity'] . '</td>';
            $products_html .= '<td>' . number_format($item['price'], 0, ',', '.') . ' RSD</td>';
            $products_html .= '<td>' . number_format($item_total, 0, ',', '.') . ' RSD</td>';
            $products_html .= '</tr>';
            
            $products_text .= "- " . $item['product_name'] . " (x" . $item['quantity'] . ") - " . 
                             number_format($item_total, 0, ',', '.') . " RSD\n";
        }
        
        $products_html .= '<tr class="total-row"><th colspan="3">Ukupno</th><td>' . number_format($items_total, 0, ',', '.') . ' RSD</td></tr>';
        $products_html .= '</table>';
        
        $products_text .= "\nUkupno: " . number_format($items_total, 0, ',', '.') . " RSD\n";
        
        // Generisanje HTML sadržaja
        $html_content = $this->generateEmailTemplate('
            <h1>Potvrda porudžbine #' . $order_number . '</h1>
            <p>Pozdrav ' . htmlspecialchars($greeting_name) . ',</p>
            <p>Vaša porudžbina je uspešno primljena. Evo pregleda Vaše porudžbine:</p>
            
            <h2>Detalji porudžbine</h2>
            <p><strong>Broj porudžbine:</strong> ' . $order_number . '</p>
            <p><strong>Datum porudžbine:</strong> ' . date('d.m.Y. H:i', strtotime($order['created_at'])) . '</p>
            <p><strong>Status porudžbine:</strong> Na čekanju</p>
            
            <h2>Poručeni proizvodi</h2>
            ' . $products_html . '
            
            <h2>Podaci o isporuci</h2>
            <p><strong>Ime i prezime:</strong> ' . htmlspecialchars($order['name']) . '</p>
            <p><strong>Adresa:</strong> ' . htmlspecialchars($order['address']) . '</p>
            <p><strong>Grad:</strong> ' . htmlspecialchars($order['city']) . '</p>
            <p><strong>Poštanski broj:</strong> ' . htmlspecialchars($order['zip']) . '</p>
            <p><strong>Telefon:</strong> ' . htmlspecialchars($order['phone']) . '</p>
            <p><strong>Email:</strong> ' . htmlspecialchars($order['email']) . '</p>
            
            <h2>Način plaćanja</h2>
            <p>' . $this->getPaymentMethodName($order['payment_method']) . '</p>
            
            <p>Hvala Vam na poverenju! Uskoro ćemo Vas kontaktirati radi potvrde porudžbine.</p>
            <p>Za sva dodatna pitanja, možete nas kontaktirati na telefon 065/8-065-065.</p>
            
            <p>Srdačan pozdrav,<br>
            Tim ' . $this->site_name . '</p>
        ');
        
        // Generisanje text sadržaja
        $text_content = "Potvrda porudžbine #{$order_number}\n\n";
        $text_content .= "Poštovani/a {$greeting_name},\n\n";
        $text_content .= "Vaša porudžbina je uspešno primljena. Evo pregleda Vaše porudžbine:\n\n";
        $text_content .= "Detalji porudžbine:\n";
        $text_content .= "Broj porudžbine: {$order_number}\n";
        $text_content .= "Datum porudžbine: " . date('d.m.Y. H:i', strtotime($order['created_at'])) . "\n";
        $text_content .= "Status porudžbine: Na čekanju\n\n";
        $text_content .= $products_text . "\n";
        $text_content .= "Podaci o isporuci:\n";
        $text_content .= "Ime i prezime: {$order['name']}\n";
        $text_content .= "Adresa: {$order['address']}\n";
        $text_content .= "Grad: {$order['city']}\n";
        $text_content .= "Poštanski broj: {$order['zip']}\n";
        $text_content .= "Telefon: {$order['phone']}\n";
        $text_content .= "Email: {$order['email']}\n\n";
        $text_content .= "Način plaćanja: " . $this->getPaymentMethodName($order['payment_method']) . "\n\n";
        $text_content .= "Hvala Vam na poverenju! Uskoro ćemo Vas kontaktirati radi potvrde porudžbine.\n";
        $text_content .= "Za sva dodatna pitanja, možete nas kontaktirati na telefon 065/8-065-065.\n\n";
        $text_content .= "Srdačan pozdrav,\n";
        $text_content .= "Tim {$this->site_name} - AGRAS D.O.O.";
        
        // Slanje emaila
        return $this->sendEmail($order['email'], "Potvrda porudžbine #{$order_number} - {$this->site_name}", $html_content, $text_content);
    }
    
    /**
     * Šalje obaveštenje o novoj porudžbini prodavcu
     * 
     * @param array $order Podaci o porudžbini
     * @param array $order_items Stavke porudžbine
     * @return bool Uspeh operacije
     */
    public function sendNewOrderNotificationToAdmin($order, $order_items) {
        // Priprema podataka
        $order_number = $order['order_number'];
        $customer_name = $order['name'];
        $total = number_format($order['total'], 0, ',', '.') . ' RSD';
        
        // Generisanje tabele sa proizvodima
        $products_html = '<table>';
        $products_html .= '<tr><th>Proizvod</th><th>SKU</th><th>Količina</th><th>Cena</th><th>Ukupno</th></tr>';
        
        $products_text = "Poručeni proizvodi:\n\n";
        
        $items_total = 0;
        foreach ($order_items as $item) {
            $item_total = $item['price'] * $item['quantity'];
            $items_total += $item_total;
            
            $products_html .= '<tr>';
            $products_html .= '<td>' . htmlspecialchars($item['product_name']) . '</td>';
            $products_html .= '<td>' . htmlspecialchars($item['product_sku']) . '</td>';
            $products_html .= '<td>' . $item['quantity'] . '</td>';
            $products_html .= '<td>' . number_format($item['price'], 0, ',', '.') . ' RSD</td>';
            $products_html .= '<td>' . number_format($item_total, 0, ',', '.') . ' RSD</td>';
            $products_html .= '</tr>';
            
            $products_text .= "- " . $item['product_name'] . " (SKU: " . $item['product_sku'] . ") - " . 
                             $item['quantity'] . " x " . number_format($item['price'], 0, ',', '.') . " = " . 
                             number_format($item_total, 0, ',', '.') . " RSD\n";
        }
        
        $products_html .= '<tr class="total-row"><th colspan="4">Ukupno</th><td>' . number_format($items_total, 0, ',', '.') . ' RSD</td></tr>';
        $products_html .= '</table>';
        
        $products_text .= "\nUkupno: " . number_format($items_total, 0, ',', '.') . " RSD\n";
        
        // Generisanje HTML sadržaja
        $html_content = $this->generateEmailTemplate('
            <h1>Nova porudžbina #' . $order_number . '</h1>
            <p>Primljena je nova porudžbina od: <strong>' . htmlspecialchars($customer_name) . '</strong></p>
            
            <h2>Detalji porudžbine</h2>
            <p><strong>Broj porudžbine:</strong> ' . $order_number . '</p>
            <p><strong>Datum porudžbine:</strong> ' . date('d.m.Y. H:i', strtotime($order['created_at'])) . '</p>
            <p><strong>Ukupan iznos:</strong> ' . $total . '</p>
            
            <h2>Poručeni proizvodi</h2>
            ' . $products_html . '
            
            <h2>Podaci o kupcu</h2>
            <p><strong>Ime i prezime:</strong> ' . htmlspecialchars($order['name']) . '</p>
            <p><strong>Adresa:</strong> ' . htmlspecialchars($order['address']) . '</p>
            <p><strong>Grad:</strong> ' . htmlspecialchars($order['city']) . '</p>
            <p><strong>Poštanski broj:</strong> ' . htmlspecialchars($order['zip']) . '</p>
            <p><strong>Telefon:</strong> ' . htmlspecialchars($order['phone']) . '</p>
            <p><strong>Email:</strong> ' . htmlspecialchars($order['email']) . '</p>
            
            <h2>Način plaćanja</h2>
            <p>' . $this->getPaymentMethodName($order['payment_method']) . '</p>
            
            <h2>Napomena kupca</h2>
            <p>' . (empty($order['notes']) ? 'Nema napomene' : htmlspecialchars($order['notes'])) . '</p>
            
            <p><a href="' . ADMIN_URL . '/orders/view.php?id=' . $order['id'] . '" class="button">Pregledaj porudžbinu</a></p>
        ');
        
        // Generisanje text sadržaja
        $text_content = "Nova porudžbina #{$order_number}\n\n";
        $text_content .= "Primljena je nova porudžbina od: {$customer_name}\n\n";
        $text_content .= "Detalji porudžbine:\n";
        $text_content .= "Broj porudžbine: {$order_number}\n";
        $text_content .= "Datum porudžbine: " . date('d.m.Y. H:i', strtotime($order['created_at'])) . "\n";
        $text_content .= "Ukupan iznos: {$total}\n\n";
        $text_content .= $products_text . "\n";
        $text_content .= "Podaci o kupcu:\n";
        $text_content .= "Ime i prezime: {$order['name']}\n";
        $text_content .= "Adresa: {$order['address']}\n";
        $text_content .= "Grad: {$order['city']}\n";
        $text_content .= "Poštanski broj: {$order['zip']}\n";
        $text_content .= "Telefon: {$order['phone']}\n";
        $text_content .= "Email: {$order['email']}\n\n";
        $text_content .= "Način plaćanja: " . $this->getPaymentMethodName($order['payment_method']) . "\n\n";
        $text_content .= "Napomena kupca: " . (empty($order['notes']) ? 'Nema napomene' : $order['notes']) . "\n\n";
        $text_content .= "Pregledajte porudžbinu u admin panelu: " . ADMIN_URL . "/orders/view.php?id=" . $order['id'];
        
        // Slanje emaila
        return $this->sendEmail($this->admin_email, "Nova porudžbina #{$order_number} - {$this->site_name}", $html_content, $text_content);
    }
    
    /**
     * Šalje obaveštenje o promeni statusa porudžbine
     * 
     * @param array $order Podaci o porudžbini
     * @param string $new_status Novi status
     * @param string $old_status Stari status
     * @return bool Uspeh operacije
     */
public function sendOrderStatusUpdate($order, $new_status, $old_status) {
    // Priprema podataka
    $order_number = $order['order_number'];
    $customer_name = $order['name'];
    
    // Konvertovanje imena u vokativ
    $vocative_name = to_vocative($customer_name);
    
    // Koristimo vokativ ako je dostupan, ili originalno ime ako nije
    $greeting_name = !empty($vocative_name) ? $vocative_name : $customer_name;
    
    // Localized status names
    $status_names = [
        'pending' => 'Na čekanju',
        'processing' => 'U obradi',
        'shipped' => 'Poslato',
        'delivered' => 'Isporučeno',
        'completed' => 'Završeno',
        'canceled' => 'Otkazano',
        'refunded' => 'Refundirano',
        'u_obradi' => 'U obradi'
    ];
    
    $new_status_name = isset($status_names[$new_status]) ? $status_names[$new_status] : $new_status;
    $old_status_name = isset($status_names[$old_status]) ? $status_names[$old_status] : $old_status;
    
    // Custom messages based on status
    $status_message = '';
    $additional_info = '';
    
    switch($new_status) {
        case 'processing':
        case 'u_obradi':
            $status_message = 'Vaša porudžbina je trenutno u obradi. Uskoro ćemo je pripremiti za slanje.';
            break;
        case 'shipped':
            $status_message = 'Vaša porudžbina je poslata! Očekujte isporuku u narednih 1-3 radna dana.';
            
            // Add tracking info if available
            if (!empty($order['tracking_number']) && !empty($order['courier'])) {
                $additional_info = '<p><strong>Broj za praćenje:</strong> ' . $order['tracking_number'] . '<br>';
                $additional_info .= '<strong>Kurirska služba:</strong> ' . $order['courier'] . '</p>';
            }
            break;
        case 'delivered':
            $status_message = 'Vaša porudžbina je isporučena. Zahvaljujemo se na poverenju!';
            break;
        case 'canceled':
            $status_message = 'Vaša porudžbina je otkazana. Za sve dodatne informacije, kontaktirajte nas.';
            break;
        default:
            $status_message = 'Status Vaše porudžbine je promenjen na: ' . $new_status_name;
    }
    
    // Generisanje HTML sadržaja
    $html_content = $this->generateEmailTemplate('
        <h1>Ažuriranje statusa porudžbine #' . $order_number . '</h1>
        <p>Poštovani/a ' . htmlspecialchars($greeting_name) . ',</p>
        <p>Status Vaše porudžbine je promenjen sa <strong>' . $old_status_name . '</strong> na <strong>' . $new_status_name . '</strong>.</p>
        <p>' . $status_message . '</p>
        ' . $additional_info . '
        <h2>Detalji porudžbine</h2>
        <p><strong>Broj porudžbine:</strong> ' . $order_number . '</p>
        <p><strong>Datum porudžbine:</strong> ' . date('d.m.Y.', strtotime($order['created_at'])) . '</p>
        <p><strong>Ukupan iznos:</strong> ' . number_format($order['total'], 0, ',', '.') . ' RSD</p>
        
        <p>Za sve dodatne informacije, kontaktirajte nas na telefon 065/8-065-065.</p>
        
        <p>Srdačan pozdrav,<br>
        Tim ' . $this->site_name . '</p>
    ');
    
    // Generisanje text sadržaja
    $text_content = "Ažuriranje statusa porudžbine #{$order_number}\n\n";
    $text_content .= "Poštovani/a {$greeting_name},\n\n";
    $text_content .= "Status Vaše porudžbine je promenjen sa " . $old_status_name . " na {$new_status_name}.\n\n";
    $text_content .= $status_message . "\n\n";
    
    if (!empty($order['tracking_number']) && !empty($order['courier'])) {
        $text_content .= "Broj za praćenje: " . $order['tracking_number'] . "\n";
        $text_content .= "Kurirska služba: " . $order['courier'] . "\n\n";
    }
    
    $text_content .= "Detalji porudžbine:\n";
    $text_content .= "Broj porudžbine: {$order_number}\n";
    $text_content .= "Datum porudžbine: " . date('d.m.Y.', strtotime($order['created_at'])) . "\n";
    $text_content .= "Ukupan iznos: " . number_format($order['total'], 0, ',', '.') . " RSD\n\n";
    $text_content .= "Za sve dodatne informacije, kontaktirajte nas na telefon 065/8-065-065.\n\n";
    $text_content .= "Srdačan pozdrav,\n";
    $text_content .= "Tim {$this->site_name}";
    
    // Slanje emaila
    return $this->sendEmail($order['email'], "Status porudžbine #{$order_number} je promenjen - {$this->site_name}", $html_content, $text_content);
}
    
    /**
     * Dobija naziv načina plaćanja
     * 
     * @param string $payment_method Ključ načina plaćanja
     * @return string Naziv načina plaćanja
     */
    private function getPaymentMethodName($payment_method) {
        $methods = [
            'card' => 'Plaćanje karticom',
            'cash' => 'Plaćanje gotovinom prilikom preuzimanja',
            'bank' => 'Uplata na račun',
            'cheque' => 'Čekovi građana'
        ];
        
        return isset($methods[$payment_method]) ? $methods[$payment_method] : $payment_method;
    }
    
    /**
     * Logira slanje emaila
     * 
     * @param string $to Primalac
     * @param string $subject Naslov
     * @param bool $success Uspeh
     */
    private function logEmail($to, $subject, $success) {
        $log_message = date('Y-m-d H:i:s') . " - Email to: {$to}, Subject: {$subject}, Status: " . ($success ? 'Success' : 'Failed') . "\n";
        
        // Kreiranje logs direktorijuma ako ne postoji
        $log_dir = __DIR__ . '/../logs';
        if (!is_dir($log_dir)) {
            mkdir($log_dir, 0755, true);
        }
        
        // Zapisivanje u log fajl
        file_put_contents($log_dir . '/email.log', $log_message, FILE_APPEND);
    }
}