<?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 quotation ID
$quotation_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$quotation_id) {
    die('Invalid quotation ID');
}

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