<?php

namespace App\Libraries;

use App\Modules\Frontend\Models\BookingModel;
use App\Modules\Frontend\Models\TourModel;
use CodeIgniter\Email\Email;

class Invoice_lib
{
    protected $bookingModel;
    protected $tourModel;
    protected $email;

    public function __construct()
    {
        $this->bookingModel = new BookingModel();
        $this->tourModel = new TourModel();
        $this->email = service('email');
    }

    public function generateAndEmail(int $bookingId): bool
    {
        $booking = $this->bookingModel->find($bookingId);
        if (!$booking) return false;

        $tour = $this->tourModel->find($booking['tour_id']);
        if (!$tour) return false;

        // Render HTML template
        $html = view('Frontend/Views/invoices/template', [
            'booking' => $booking,
            'tour' => $tour,
            'settings' => setting() // helper function (defined below)
        ]);

        // Generate PDF
        $dompdf = new \Dompdf\Dompdf();
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        $pdfContent = $dompdf->output();
        $filename = "invoice_{$booking['invoice_ref']}.pdf";
        $filePath = WRITEPATH . 'invoices/' . $filename;

        if (!is_dir(WRITEPATH . 'invoices')) {
            mkdir(WRITEPATH . 'invoices', 0755, true);
        }

        file_put_contents($filePath, $pdfContent);

        // Send email
        $this->email->setFrom(setting('email.fromEmail'), setting('email.fromName'));
        $this->email->setTo($booking['email']);
        $this->email->setSubject('Your Mount Kenya Trek Invoice #' . $booking['invoice_ref']);
        $this->email->setMessage("Thank you for your booking! Your invoice is attached.");
        $this->email->attach($filePath);

        if ($this->email->send()) {
            log_message('info', "Invoice email sent to {$booking['email']} for #{$booking['invoice_ref']}");
            return true;
        } else {
            log_message('error', "Failed to send invoice email: " . $this->email->printDebugger());
            return false;
        }
    }
}