<?php
require_once 'config/database.php';
require_once 'config/session.php';
require_once 'includes/simple_pdf.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

// Get invoice ID
$invoice_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$invoice_id) {
    die('Invalid invoice ID');
}

try {
    // Get database connection
    $pdo = getConnection();
    
    // Get invoice details
    $stmt = $pdo->prepare("
        SELECT i.*, c.name as customer_name, c.contact_number, c.email, c.address, c.gst_number
        FROM invoices i
        JOIN customers c ON i.customer_id = c.id
        WHERE i.id = ?
    ");
    $stmt->execute([$invoice_id]);
    $invoice = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$invoice) {
        die('Invoice not found');
    }
    
    // Get invoice items
    $stmt = $pdo->prepare("
        SELECT ii.*, m.name as material_name, m.description
        FROM invoice_items ii
        JOIN materials m ON ii.material_id = m.id
        WHERE ii.invoice_id = ?
        ORDER BY ii.id
    ");
    $stmt->execute([$invoice_id]);
    $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Prepare customer data
    $customer = [
        'name' => $invoice['customer_name'],
        'contact_number' => $invoice['contact_number'],
        'email' => $invoice['email'],
        'address' => $invoice['address'],
        'gst_number' => $invoice['gst_number']
    ];
    
    // Generate and download PDF
    SimplePDF::generateInvoicePDF($invoice, $items, $customer);
    
} catch (Exception $e) {
    die('Error generating PDF: ' . $e->getMessage());
}
?>
