<?php
session_start();
include 'layouts/dbconn.php';
require 'fpdf/fpdf.php'; // For FPDF

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

try {
    // Get corporate details
    $sql = "SELECT * FROM corporate WHERE corp_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $_POST['corp_id']);
    $stmt->execute();
    $corporate = $stmt->get_result()->fetch_assoc();

    if (!$corporate) {
        throw new Exception('Corporate not found');
    }

    // Calculate premiums and prepare member data
    $members = [];
    $total_premium = 0;

    foreach ($_POST['members'] as $member) {
        $member_premium = 0;
        $benefits = [];

        // Get benefits details
        foreach ($member['benefits'] as $benefit_code) {
            $sql = "SELECT b.benefit, r.premium, r.limit
                    FROM benefit b
                    JOIN insuring_rates r ON b.code = r.benefit
                    WHERE b.code = ? AND r.corp_id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param('is', $benefit_code, $_POST['corp_id']);
            $stmt->execute();
            $benefit = $stmt->get_result()->fetch_assoc();

            if ($benefit) {
                $member_premium += $benefit['premium'];
                $benefits[] = [
                    'name' => $benefit['benefit'],
                    'limit' => $benefit['limit'],
                    'premium' => $benefit['premium']
                ];
            }
        }

        $members[] = [
            'relation' => $member['relation'],
            'age' => $member['age'],
            'benefits' => $benefits,
            'premium' => $member_premium
        ];

        $total_premium += $member_premium;
    }

    // Create PDF
    $pdf = new FPDF();

    // Add a page
    $pdf->AddPage();

    // Set font
    $pdf->SetFont('Helvetica', 'B', 20);

    // Add company logo if exists
    if (file_exists('assets/images/logo.png')) {
        $pdf->Image('assets/images/logo.png', 15, 15, 50);
        $pdf->Ln(20);
    }

    // Title
    $pdf->Cell(0, 15, 'INSURANCE QUOTATION', 0, 1, 'C');
    $pdf->SetFont('Helvetica', '', 10);
    $pdf->Ln(5);

    // Corporate Details Section
    $pdf->SetFont('Helvetica', 'B', 12);
    $pdf->Cell(0, 10, 'Corporate Details', 0, 1, 'L');
    $pdf->SetFont('Helvetica', '', 10);

    $pdf->SetFillColor(240, 240, 240);
    $pdf->Cell(40, 7, 'Corporate:', 0, 0, 'L');
    $pdf->Cell(0, 7, $corporate['corporate'], 0, 1, 'L');

    $pdf->Cell(40, 7, 'Scheme:', 0, 0, 'L');
    $pdf->Cell(0, 7, $corporate['scheme'], 0, 1, 'L');

    $pdf->Cell(40, 7, 'Valid Until:', 0, 0, 'L');
    $pdf->Cell(0, 7, date('d/m/Y', strtotime($_POST['valid_until'])), 0, 1, 'L');

    $pdf->Ln(5);

    // Members Details Section
    $pdf->SetFont('Helvetica', 'B', 12);
    $pdf->Cell(0, 10, 'Members & Benefits', 0, 1, 'L');
    $pdf->SetFont('Helvetica', '', 10);

    foreach ($members as $i => $member) {
        $pdf->SetFillColor(245, 245, 245);
        $pdf->Cell(0, 8, 'Member ' . ($i + 1), 1, 1, 'L', true);

        $pdf->Cell(40, 7, 'Relation:', 0, 0, 'L');
        $pdf->Cell(60, 7, ucfirst($member['relation']), 0, 0, 'L');
        $pdf->Cell(30, 7, 'Age:', 0, 0, 'L');
        $pdf->Cell(0, 7, $member['age'], 0, 1, 'L');

        // Benefits table
        $pdf->Ln(2);
        $pdf->SetFillColor(230, 230, 230);
        $pdf->Cell(80, 7, 'Benefit', 1, 0, 'C', true);
        $pdf->Cell(50, 7, 'Limit', 1, 0, 'C', true);
        $pdf->Cell(50, 7, 'Premium', 1, 1, 'C', true);

        foreach ($member['benefits'] as $benefit) {
            $pdf->Cell(80, 7, $benefit['name'], 1, 0, 'L');
            $pdf->Cell(50, 7, number_format($benefit['limit'], 2), 1, 0, 'R');
            $pdf->Cell(50, 7, number_format($benefit['premium'], 2), 1, 1, 'R');
        }

        $pdf->SetFont('Helvetica', 'B', 10);
        $pdf->Cell(130, 7, 'Member Total:', 1, 0, 'R');
        $pdf->Cell(50, 7, number_format($member['premium'], 2), 1, 1, 'R');
        $pdf->SetFont('Helvetica', '', 10);

        $pdf->Ln(5);
    }

    // Total Premium
    $pdf->SetFont('Helvetica', 'B', 12);
    $pdf->Cell(130, 10, 'Total Premium:', 0, 0, 'R');
    $pdf->Cell(50, 10, number_format($total_premium, 2), 0, 1, 'R');

    // Terms and Conditions
    $pdf->Ln(10);
    $pdf->SetFont('Helvetica', 'B', 11);
    $pdf->Cell(0, 7, 'Terms and Conditions:', 0, 1, 'L');
    $pdf->SetFont('Helvetica', '', 9);

    $terms = [
        "1. This quotation is valid until " . date('d/m/Y', strtotime($_POST['valid_until'])),
        "2. All premiums quoted are inclusive of applicable taxes",
        "3. Coverage is subject to full underwriting and policy terms",
        "4. Pre-existing conditions may be excluded",
        "5. Waiting periods may apply for specific benefits",
        "6. Final premium may vary based on medical underwriting"
    ];

    foreach ($terms as $term) {
        $pdf->Cell(0, 5, $term, 0, 1, 'L');
    }

    // Contact Information
    $pdf->Ln(10);
    $pdf->SetFont('Helvetica', 'B', 11);
    $pdf->Cell(0, 7, 'Contact Information:', 0, 1, 'L');
    $pdf->SetFont('Helvetica', '', 9);
    $pdf->Cell(0, 5, 'For any queries regarding this quotation, please contact:', 0, 1, 'L');
    $pdf->Cell(0, 5, 'Tel: ' . ($corporate['tel_no'] ?? 'N/A'), 0, 1, 'L');
    $pdf->Cell(0, 5, 'Email: ' . ($corporate['email'] ?? 'N/A'), 0, 1, 'L');

    // Footer note
    $pdf->Ln(10);
    $pdf->SetFont('Helvetica', 'I', 8);
    $pdf->Cell(0, 5, 'This is a computer-generated document and does not require a signature.', 0, 1, 'C');
    $pdf->Cell(0, 5, 'Preview generated on: ' . date('d/m/Y H:i'), 0, 1, 'C');

    // Output PDF
    $pdf->Output('Quotation_Preview.pdf', 'I');

} catch (Exception $e) {
    // Log error
    error_log("Quotation preview error: " . $e->getMessage());

    // Return error page
    header('Content-Type: text/html');
    echo "<h1>Error Generating Preview</h1>";
    echo "<p>An error occurred while generating the quotation preview: " . htmlspecialchars($e->getMessage()) . "</p>";
    echo "<p><a href='javascript:history.back()'>Go Back</a></p>";
}

$conn->close();
?>