<?php
session_start();
include 'layouts/dbconn.php';
require_once 'fpdf/fpdf.php';
require_once 'vendor/phpmailer/src/PHPMailer.php';
require_once 'vendor/phpmailer/src/SMTP.php';
require_once 'vendor/phpmailer/src/Exception.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'error' => 'Not authenticated']);
    exit;
}

try {
    $voucher_no = $_POST['voucher_no'] ?? '';
    $email = $_POST['email'] ?? '';

    if (!$voucher_no || !$email) {
        throw new Exception('Missing required parameters');
    }

    // Load email settings
    $sql = "SELECT setting_key, setting_value FROM settings WHERE setting_key IN 
            ('email_host', 'email_port', 'email_username', 'email_password', 
             'email_sender', 'system_name')";
    $result = $conn->query($sql);
    $settings = [];
    while ($row = $result->fetch_assoc()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }

    // Start transaction
    $conn->begin_transaction();

    try {
        // Fetch voucher details
        $sql = "SELECT v.*, bp.cheque_no, bp.cheque_date 
                FROM payment_vouchers v
                JOIN bills_payment bp ON v.payment_no = bp.payment_no
                WHERE v.voucher_no = ?";
                
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('s', $voucher_no);
        $stmt->execute();
        $voucher = $stmt->get_result()->fetch_assoc();

        if (!$voucher) {
            throw new Exception('Voucher not found');
        }

        // Generate PDF
        class VoucherPDF extends FPDF {
            function Header() {
                $this->SetFont('Arial', 'B', 15);
                $this->Cell(0, 10, 'Payment Voucher', 0, 1, 'C');
                $this->Ln(5);
            }

            function Footer() {
                $this->SetY(-15);
                $this->SetFont('Arial', 'I', 8);
                $this->Cell(0, 10, 'Page '.$this->PageNo(), 0, 0, 'C');
            }
        }

        $pdf = new VoucherPDF();
        $pdf->AddPage();
        $pdf->SetFont('Arial', '', 12);

        // Add voucher details to PDF
        $pdf->Cell(40, 10, 'Voucher No:', 0);
        $pdf->Cell(0, 10, $voucher['voucher_no'], 0, 1);

        $pdf->Cell(40, 10, 'Date:', 0);
        $pdf->Cell(0, 10, date('d/m/Y', strtotime($voucher['voucher_date'])), 0, 1);

        $pdf->Cell(40, 10, 'Pay To:', 0);
        $pdf->Cell(0, 10, $voucher['recipient_name'], 0, 1);

        $pdf->Cell(40, 10, 'Cheque No:', 0);
        $pdf->Cell(0, 10, $voucher['cheque_no'], 0, 1);

        $pdf->Ln(5);

        // Fetch voucher items
        $sql = "SELECT * FROM payment_voucher_items WHERE voucher_id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('i', $voucher['voucher_id']);
        $stmt->execute();
        $items = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

        // Add items table
        $pdf->SetFont('Arial', 'B', 12);
        $pdf->Cell(40, 10, 'Claim No', 1);
        $pdf->Cell(40, 10, 'Invoice No', 1);
        $pdf->Cell(70, 10, 'Description', 1);
        $pdf->Cell(40, 10, 'Amount', 1, 1, 'R');

        $pdf->SetFont('Arial', '', 12);
        $total = 0;
        foreach ($items as $item) {
            $pdf->Cell(40, 10, $item['claim_no'], 1);
            $pdf->Cell(40, 10, $item['invoice_no'], 1);
            $pdf->Cell(70, 10, $item['description'], 1);
            $pdf->Cell(40, 10, number_format($item['amount'], 2), 1, 1, 'R');
            $total += $item['amount'];
        }

        // Total
        $pdf->SetFont('Arial', 'B', 12);
        $pdf->Cell(150, 10, 'Total Amount:', 1);
        $pdf->Cell(40, 10, number_format($total, 2), 1, 1, 'R');

        $pdf_content = $pdf->Output('S');

        // Initialize PHPMailer
        $mail = new PHPMailer(true);

        // Server settings
        $mail->isSMTP();
        $mail->Host = $settings['email_host'];
        $mail->SMTPAuth = true;
        $mail->Username = $settings['email_username'];
        $mail->Password = $settings['email_password'];
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = intval($settings['email_port']);

        // Recipients
        $mail->setFrom($settings['email_sender'], $settings['system_name']);
        $mail->addAddress($email);

        // Attachment
        $mail->addStringAttachment($pdf_content, "voucher_{$voucher_no}.pdf");

        // Content
        $mail->isHTML(true);
        $mail->Subject = "Payment Voucher - {$voucher_no}";
        $mail->Body = "
            <p>Dear Sir/Madam,</p>
            <p>Please find attached the payment voucher {$voucher_no}.</p>
            <p>Amount: " . number_format($voucher['total_amount'], 2) . "</p>
            <p>Date: " . date('d/m/Y', strtotime($voucher['voucher_date'])) . "</p>
            <p>Best regards,<br>{$settings['system_name']}</p>
        ";

        $mail->send();

        // Commit transaction
        $conn->commit();

        echo json_encode([
            'success' => true,
            'message' => 'Voucher emailed successfully'
        ]);

    } catch (Exception $e) {
        $conn->rollback();
        throw $e;
    }

} catch (Exception $e) {    
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

$conn->close();
?>