<?php
/**
 * Email Service
 * Handles all email notifications
 */

class EmailService {
    private $db;
    private $config;

    public function __construct($db, $config) {
        $this->db = $db;
        $this->config = $config;
    }

    /**
     * Send booking confirmation email
     */
    public function sendBookingConfirmation($booking_id) {
        try {
            $stmt = $this->db->prepare("
                SELECT b.*, g.email, g.name,
                       p.name as property_name, r.name as room_name
                FROM bookings b
                JOIN guests g ON b.guest_id = g.id
                JOIN properties p ON b.property_id = p.id
                LEFT JOIN rooms r ON b.room_id = r.id
                WHERE b.id = ?
            ");
            $stmt->execute([$booking_id]);
            $booking = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$booking) return false;

            $guest_link = $this->config['app']['url'] . '/guest-access.html?token=' . $booking['guest_token'];

            $subject = "Booking Confirmation - " . $booking['property_name'];
            $body = "Hello " . $booking['name'] . ",\n\n";
            $body .= "Thank you for booking with us!\n\n";
            $body .= "Property: " . $booking['property_name'] . "\n";
            $body .= "Room: " . $booking['room_name'] . "\n";
            $body .= "Check-In: " . date('M d, Y', strtotime($booking['check_in'])) . "\n";
            $body .= "Check-Out: " . date('M d, Y', strtotime($booking['check_out'])) . "\n";
            $body .= "Nights: " . $booking['nights'] . "\n";
            $body .= "Total: $" . number_format($booking['price'], 2) . "\n\n";
            $body .= "View your booking: " . $guest_link . "\n\n";
            $body .= "Reference: " . $booking['booking_reference'] . "\n";

            return $this->send($booking['email'], $booking['name'], $subject, $body);

        } catch (Exception $e) {
            error_log('Booking email error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Send invoice email
     */
    public function sendInvoice($invoice_id) {
        try {
            $stmt = $this->db->prepare("
                SELECT i.*, g.email, g.name, p.name as property_name
                FROM folio_charges i
                JOIN bookings b ON i.booking_id = b.id
                JOIN guests g ON b.guest_id = g.id
                JOIN properties p ON b.property_id = p.id
                WHERE i.id = ?
            ");
            $stmt->execute([$invoice_id]);
            $invoice = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$invoice) return false;

            $subject = "Invoice #" . $invoice['invoice_number'];
            $body = "Invoice for " . $invoice['name'] . "\n\n";
            $body .= "Invoice #: " . $invoice['invoice_number'] . "\n";
            $body .= "Property: " . $invoice['property_name'] . "\n";
            $body .= "Amount: $" . number_format($invoice['amount'], 2) . "\n";
            $body .= "Tax: $" . number_format($invoice['tax_amount'], 2) . "\n";
            $body .= "Total: $" . number_format($invoice['total'], 2) . "\n";
            $body .= "Due Date: " . date('M d, Y', strtotime($invoice['due_date'])) . "\n";

            return $this->send($invoice['email'], $invoice['name'], $subject, $body);

        } catch (Exception $e) {
            error_log('Invoice email error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Send check-in reminder
     */
    public function sendCheckInReminder($booking_id) {
        try {
            $stmt = $this->db->prepare("
                SELECT b.*, g.email, g.name, p.name as property_name, p.address
                FROM bookings b
                JOIN guests g ON b.guest_id = g.id
                JOIN properties p ON b.property_id = p.id
                WHERE b.id = ?
            ");
            $stmt->execute([$booking_id]);
            $booking = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$booking) return false;

            $subject = "Check-In Tomorrow";
            $body = "Hello " . $booking['name'] . ",\n\n";
            $body .= "Your check-in is tomorrow!\n\n";
            $body .= "Property: " . $booking['property_name'] . "\n";
            $body .= "Address: " . $booking['address'] . "\n";
            $body .= "Check-In Time: 3:00 PM\n\n";
            $body .= "We look forward to seeing you!\n";

            return $this->send($booking['email'], $booking['name'], $subject, $body);

        } catch (Exception $e) {
            error_log('Check-in reminder error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Send payment reminder
     */
    public function sendPaymentReminder($invoice_id) {
        try {
            $stmt = $this->db->prepare("
                SELECT i.*, g.email, g.name
                FROM folio_charges i
                JOIN bookings b ON i.booking_id = b.id
                JOIN guests g ON b.guest_id = g.id
                WHERE i.id = ? AND i.status = 'pending'
            ");
            $stmt->execute([$invoice_id]);
            $invoice = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$invoice) return false;

            $subject = "Payment Reminder - Invoice #" . $invoice['invoice_number'];
            $body = "Hello " . $invoice['name'] . ",\n\n";
            $body .= "This is a reminder that payment is due on " . date('M d, Y', strtotime($invoice['due_date'])) . ".\n\n";
            $body .= "Amount Due: $" . number_format($invoice['total'], 2) . "\n";
            $body .= "Invoice #: " . $invoice['invoice_number'] . "\n\n";
            $body .= "Please process payment as soon as possible.\n";

            return $this->send($invoice['email'], $invoice['name'], $subject, $body);

        } catch (Exception $e) {
            error_log('Payment reminder error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Send video call invitation
     */
    public function sendVideoCallInvitation($call_id, $staff_email, $staff_name) {
        try {
            $subject = "Video Call Invitation";
            $body = "Hello " . $staff_name . ",\n\n";
            $body .= "You've been invited to join a team video call.\n\n";
            $body .= "Please log in to your account to see the call details.\n";

            return $this->send($staff_email, $staff_name, $subject, $body);

        } catch (Exception $e) {
            error_log('Video call email error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Generic send email (using PHP mail function)
     */
    private function send($to_email, $to_name, $subject, $body) {
        try {
            $headers = "From: " . ($this->config['email']['from_address'] ?? 'noreply@hostiva.com') . "\r\n";
            $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

            $result = mail($to_email, $subject, $body, $headers);

            if ($result) {
                error_log("Email sent to $to_email: $subject");
            } else {
                error_log("Failed to send email to $to_email");
            }

            return $result;

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