<?php
session_start();
require_once '../config/config.php';
require_once '../config/email_helper.php';
require_once '../receipts/PDFGenerator.php';

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

if (!isset($_SESSION['admin_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$invoice_id = $_GET['id'] ?? null;
$send_email = $_GET['send_email'] ?? false;

if (!$invoice_id) {
    echo json_encode(['success' => false, 'message' => 'Invoice ID is required']);
    exit();
}

try {
    $conn = new PDO($dsn, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Get invoice data with member information
    $stmt = $conn->prepare("
        SELECT 
            i.*,
            m.first_name,
            m.last_name,
            m.kso_id,
            m.email,
            m.phone,
            m.address
        FROM invoices i
        LEFT JOIN members m ON i.member_id = m.id
        WHERE i.id = ?
    ");
    $stmt->execute([$invoice_id]);
    $invoice = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$invoice) {
        echo json_encode(['success' => false, 'message' => 'Invoice not found']);
        exit();
    }
    
    // Decode items JSON
    $items = json_decode($invoice['items'], true) ?? [];
    
    // Prepare data for PDF generation
    $pdfData = [
        'number' => $invoice['invoice_number'],
        'date' => $invoice['created_at'],
        'due_date' => $invoice['due_date'],
        'member_name' => $invoice['first_name'] . ' ' . $invoice['last_name'],
        'kso_id' => $invoice['kso_id'],
        'email' => $invoice['email'],
        'phone' => $invoice['phone'],
        'address' => $invoice['address'],
        'items' => $items,
        'subtotal' => $invoice['subtotal'],
        'tax_amount' => $invoice['tax_amount'],
        'total_amount' => $invoice['total_amount'],
        'status' => $invoice['status'],
        'notes' => $invoice['notes'],
        'include_qr' => true,
        'digital_signature' => true
    ];
    
    // Generate PDF and save to temporary file
    $pdf = new InvoicePDFGenerator();
    $pdf->generateInvoice($pdfData);
    
    // Create temp file for email attachment
    $tempFile = tempnam(sys_get_temp_dir(), 'invoice_');
    file_put_contents($tempFile, $pdf->Output('', 'S'));
    
    // Send email with PDF attachment
    if ($send_email && !empty($invoice['email'])) {
        $emailResult = sendInvoiceEmailHelper($invoice, $tempFile);
        
        if ($emailResult['success']) {
            // Log the email send event
            $logStmt = $conn->prepare("
                INSERT INTO email_logs (recipient, subject, status, created_at)
                VALUES (?, ?, 'sent', NOW())
            ");
            $logStmt->execute([
                $invoice['email'],
                'Invoice #' . $invoice['invoice_number']
            ]);
            
            echo json_encode(['success' => true, 'message' => 'Invoice PDF emailed successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to send email: ' . $emailResult['message']]);
        }
    } else {
        // Just output the PDF file
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="invoice_' . $invoice['invoice_number'] . '.pdf"');
        readfile($tempFile);
    }
    
    // Clean up temp file
    unlink($tempFile);
    
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error generating PDF: ' . $e->getMessage()]);
}
?>
