<?php
/**
 * Generate PDF Quotation
 * 
 * This script generates a PDF version of a quotation
 * Requires TCPDF library
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Define base path
define('BASE_PATH', dirname(__DIR__));

// Load database functions
require_once dirname(__DIR__) . '/config/db_functions.php';

// Require authentication
if (function_exists('require_auth')) {
    require_auth();
}

// Check permission
if (function_exists('has_permission') && !has_permission('quotations.view')) {
    die('You do not have permission to view quotations');
}

// Get quotation ID from URL
$quotation_id = $_GET['id'] ?? 0;

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

// Fetch quotation details
$quotation = db_fetch_one("
    SELECT q.*, u.username as created_by_name
    FROM quotations q
    LEFT JOIN users u ON q.created_by = u.user_id
    WHERE q.quotation_id = ?
", [$quotation_id]);

if (!$quotation) {
    die('Quotation not found');
}

// Fetch quotation items
$items = db_fetch_all("
    SELECT * FROM quotation_items 
    WHERE quotation_id = ?
    ORDER BY item_id
", [$quotation_id]) ?: [];

// Include TCPDF library
// You need to install TCPDF first. You can download from https://github.com/tecnickcom/tcpdf
// Place it in a libraries folder or use Composer: composer require tecnickcom/tcpdf

// Check if TCPDF is available via Composer
$tcpdf_autoload = dirname(__DIR__) . '/vendor/tecnickcom/tcpdf/tcpdf.php';
$tcpdf_fallback = dirname(__DIR__) . '/libraries/tcpdf/tcpdf.php';

if (file_exists($tcpdf_autoload)) {
    require_once $tcpdf_autoload;
} elseif (file_exists($tcpdf_fallback)) {
    require_once $tcpdf_fallback;
} else {
    // If TCPDF is not available, output HTML instead
    output_html_quotation($quotation, $items);
    exit;
}

// Create new PDF document
class PDF extends TCPDF {
    
    // Page header
    public function Header() {
        // Logo - create a simple text logo if no image
        $this->SetFont('helvetica', 'B', 20);
        $this->SetTextColor(0, 51, 153);
        $this->Cell(0, 15, 'RUHONDO BEACH RESORT', 0, false, 'C', 0, '', 0, false, 'M', 'M');
        $this->Ln(8);
        
        $this->SetFont('helvetica', '', 12);
        $this->SetTextColor(100, 100, 100);
        $this->Cell(0, 6, 'Lake Ruhondo, Musanze - Northern Province, Rwanda', 0, false, 'C', 0, '', 0, false, 'M', 'M');
        $this->Ln(6);
        $this->Cell(0, 6, 'Tel: +250 123 456 789 | Email: reservations@ruhondobeach.com', 0, false, 'C', 0, '', 0, false, 'M', 'M');
        $this->Ln(10);
        
        // Line separator
        $this->SetLineWidth(0.5);
        $this->SetDrawColor(0, 51, 153);
        $this->Line(10, $this->GetY(), 200, $this->GetY());
        $this->Ln(10);
    }
    
    // Page footer
    public function Footer() {
        // Position at 15 mm from bottom
        $this->SetY(-15);
        
        // Line separator
        $this->SetLineWidth(0.2);
        $this->SetDrawColor(200, 200, 200);
        $this->Line(10, $this->GetY(), 200, $this->GetY());
        $this->Ln(2);
        
        // Set font
        $this->SetFont('helvetica', 'I', 8);
        $this->SetTextColor(150, 150, 150);
        
        // Page number
        $this->Cell(0, 5, 'Page ' . $this->getAliasNumPage() . '/' . $this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
        
        // Generated date
        $this->Cell(0, 5, 'Generated on: ' . date('d M Y H:i:s'), 0, false, 'R', 0, '', 0, false, 'T', 'M');
    }
}

// Create new PDF document
$pdf = new PDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// Set document information
$pdf->SetCreator('Ruhondo Beach Resort HMS');
$pdf->SetAuthor('Ruhondo Beach Resort');
$pdf->SetTitle('Quotation ' . $quotation['quotation_number']);
$pdf->SetSubject('Hotel Services Quotation');
$pdf->SetKeywords('quotation, hotel, ruhondo, booking');

// Remove default header/footer
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// Set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// Set margins
$pdf->SetMargins(15, 40, 15);
$pdf->SetHeaderMargin(10);
$pdf->SetFooterMargin(20);

// Set auto page breaks
$pdf->SetAutoPageBreak(TRUE, 25);

// Set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

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

// Set font
$pdf->SetFont('helvetica', '', 10);

// Quotation Title
$pdf->SetFont('helvetica', 'B', 24);
$pdf->SetTextColor(0, 51, 153);
$pdf->Cell(0, 15, 'Hotel Proforma Invoice', 0, 1, 'C');
$pdf->Ln(5);

// Quote Reference and Date
$pdf->SetFont('helvetica', '', 10);
$pdf->SetTextColor(0, 0, 0);

// Two column layout for reference
$pdf->SetFont('helvetica', 'B', 11);
$pdf->Cell(95, 7, 'QUOTATION DETAILS', 0, 0, 'L');
$pdf->Cell(95, 7, 'DATE INFORMATION', 0, 1, 'R');
$pdf->Ln(2);

$pdf->SetFont('helvetica', '', 10);

// Left column
$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(40, 7, 'Quote Number:', 0, 0, 'L');
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(55, 7, $quotation['quotation_number'], 0, 0, 'L');

// Right column
$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(30, 7, 'Issue Date:', 0, 0, 'R');
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(40, 7, date('d M Y', strtotime($quotation['issue_date'])), 0, 1, 'L');

$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(40, 7, 'Valid Until:', 0, 0, 'L');
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(55, 7, date('d M Y', strtotime($quotation['valid_until'])), 0, 0, 'L');

$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(30, 7, 'Status:', 0, 0, 'R');
$status_color = match($quotation['status']) {
    'draft' => '255, 165, 0',
    'sent' => '0, 123, 255',
    'accepted' => '40, 167, 69',
    'expired' => '255, 193, 7',
    'cancelled' => '220, 53, 69',
    default => '108, 117, 125'
};
$pdf->SetTextColor(...explode(', ', $status_color));
$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(40, 7, strtoupper($quotation['status']), 0, 1, 'L');
$pdf->SetTextColor(0, 0, 0);

$pdf->Ln(10);

// RECEIVER Section
$pdf->SetFont('helvetica', 'B', 14);
$pdf->SetTextColor(0, 51, 153);
$pdf->Cell(0, 10, 'RECEIVER', 0, 1, 'L');
$pdf->Ln(2);

$pdf->SetFont('helvetica', 'B', 12);
$pdf->SetTextColor(0, 0, 0);
$pdf->Cell(0, 8, $quotation['customer_name'], 0, 1, 'L');

$pdf->SetFont('helvetica', '', 10);
$address = '';
if (!empty($quotation['customer_address_line1'])) {
    $address .= $quotation['customer_address_line1'] . "\n";
}
if (!empty($quotation['customer_address_line2'])) {
    $address .= $quotation['customer_address_line2'] . "\n";
}
if (!empty($quotation['customer_email'])) {
    $address .= "Email: " . $quotation['customer_email'] . "\n";
}
if (!empty($quotation['customer_phone'])) {
    $address .= "Tel: " . $quotation['customer_phone'];
}

if (!empty($address)) {
    $pdf->MultiCell(0, 6, $address, 0, 'L', 0, 1, '', '', true);
} else {
    $pdf->Cell(0, 6, 'No address provided', 0, 1, 'L');
}

$pdf->Ln(10);

// Items Table
$pdf->SetFont('helvetica', 'B', 14);
$pdf->SetTextColor(0, 51, 153);
$pdf->Cell(0, 10, 'QUOTATION ITEMS', 0, 1, 'L');
$pdf->Ln(2);

// Table header
$pdf->SetFillColor(240, 240, 240);
$pdf->SetTextColor(0, 0, 0);
$pdf->SetFont('helvetica', 'B', 10);

$pdf->Cell(20, 8, 'QTY', 1, 0, 'C', 1);
$pdf->Cell(75, 8, 'DESCRIPTION', 1, 0, 'C', 1);
$pdf->Cell(30, 8, 'UNIT PRICE', 1, 0, 'C', 1);
$pdf->Cell(30, 8, 'SUBTOTAL', 1, 0, 'C', 1);
$pdf->Cell(30, 8, 'VAT (18%)', 1, 1, 'C', 1);

// Table rows
$pdf->SetFont('helvetica', '', 9);
$pdf->SetFillColor(255, 255, 255);

foreach ($items as $item) {
    $pdf->Cell(20, 7, $item['quantity'] . ' Nights', 1, 0, 'C');
    $pdf->Cell(75, 7, $item['description'], 1, 0, 'L');
    $pdf->Cell(30, 7, number_format($item['unit_price'], 2) . ' RWF', 1, 0, 'R');
    $pdf->Cell(30, 7, number_format($item['subtotal'], 2) . ' RWF', 1, 0, 'R');
    $pdf->Cell(30, 7, number_format($item['vat_amount'], 2) . ' RWF', 1, 1, 'R');
}

// Summary
$pdf->Ln(5);

// Summary table - right aligned
$pdf->SetFont('helvetica', 'B', 10);
$pdf->SetFillColor(245, 245, 245);

$pdf->Cell(125, 8, '', 0, 0, 'L');
$pdf->Cell(30, 8, 'Subtotal:', 1, 0, 'R', 1);
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(30, 8, number_format($quotation['subtotal'], 2) . ' RWF', 1, 1, 'R');

$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(125, 8, '', 0, 0, 'L');
$pdf->Cell(30, 8, 'VAT (18%):', 1, 0, 'R', 1);
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(30, 8, number_format($quotation['vat_amount'], 2) . ' RWF', 1, 1, 'R');

$pdf->SetFont('helvetica', 'B', 11);
$pdf->Cell(125, 8, '', 0, 0, 'L');
$pdf->Cell(30, 8, 'TOTAL:', 1, 0, 'R', 1);
$pdf->SetFont('helvetica', 'B', 11);
$pdf->SetTextColor(0, 102, 204);
$pdf->Cell(30, 8, number_format($quotation['total_amount'], 2) . ' RWF', 1, 1, 'R');
$pdf->SetTextColor(0, 0, 0);

// Notes
if (!empty($quotation['notes'])) {
    $pdf->Ln(10);
    $pdf->SetFont('helvetica', 'B', 12);
    $pdf->SetTextColor(0, 51, 153);
    $pdf->Cell(0, 8, 'NOTES', 0, 1, 'L');
    $pdf->Ln(2);
    
    $pdf->SetFont('helvetica', '', 10);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->MultiCell(0, 6, $quotation['notes'], 0, 'L', 0, 1, '', '', true);
}

// Terms and conditions
$pdf->Ln(10);
$pdf->SetFont('helvetica', 'B', 12);
$pdf->SetTextColor(0, 51, 153);
$pdf->Cell(0, 8, 'TERMS AND CONDITIONS', 0, 1, 'L');
$pdf->Ln(2);

$pdf->SetFont('helvetica', '', 9);
$pdf->SetTextColor(0, 0, 0);
$terms = "1. This quotation is valid until " . date('d M Y', strtotime($quotation['valid_until'])) . ".\n";
$terms .= "2. All prices are inclusive of 18% VAT.\n";
$terms .= "3. Payment is required upon check-in or as agreed in advance.\n";
$terms .= "4. Cancellation policy: 48 hours prior to arrival for full refund.\n";
$terms .= "5. Check-in time: 14:00, Check-out time: 11:00.\n";
$terms .= "6. For any queries, please contact our reservations team.";

$pdf->MultiCell(0, 5, $terms, 0, 'L', 0, 1, '', '', true);

// Signature line
$pdf->Ln(15);
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(70, 5, '_________________________', 0, 0, 'L');
$pdf->Cell(50, 5, '', 0, 0, 'L');
$pdf->Cell(70, 5, '_________________________', 0, 1, 'R');

$pdf->SetFont('helvetica', 'B', 9);
$pdf->Cell(70, 5, 'For Ruhondo Beach Resort', 0, 0, 'L');
$pdf->Cell(50, 5, '', 0, 0, 'L');
$pdf->Cell(70, 5, 'Customer Signature', 0, 1, 'R');

// Close and output PDF document
$pdf->Output('Quotation_' . $quotation['quotation_number'] . '.pdf', 'I');

/**
 * Fallback function to output HTML if TCPDF is not available
 */
function output_html_quotation($quotation, $items) {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Quotation <?php echo $quotation['quotation_number']; ?></title>
        <style>
            body {
                font-family: Arial, sans-serif;
                margin: 30px;
                background: #fff;
            }
            .header {
                text-align: center;
                margin-bottom: 30px;
                border-bottom: 2px solid #003399;
                padding-bottom: 20px;
            }
            .header h1 {
                color: #003399;
                margin: 0;
                font-size: 28px;
            }
            .header h2 {
                color: #666;
                margin: 5px 0;
                font-size: 18px;
                font-weight: normal;
            }
            .company-details {
                margin-top: 10px;
                color: #666;
                font-size: 12px;
            }
            .quote-title {
                text-align: center;
                font-size: 24px;
                color: #003399;
                margin: 20px 0;
                font-weight: bold;
            }
            .info-section {
                margin-bottom: 30px;
            }
            .info-box {
                border: 1px solid #ddd;
                padding: 15px;
                margin-bottom: 20px;
                border-radius: 5px;
            }
            .info-box h3 {
                margin-top: 0;
                color: #003399;
                border-bottom: 1px solid #eee;
                padding-bottom: 10px;
            }
            table {
                width: 100%;
                border-collapse: collapse;
                margin: 20px 0;
            }
            th {
                background: #f0f0f0;
                padding: 10px;
                text-align: left;
                font-weight: bold;
            }
            td {
                padding: 10px;
                border-bottom: 1px solid #ddd;
            }
            .totals {
                float: right;
                width: 300px;
                margin-top: 20px;
            }
            .totals table {
                width: 100%;
            }
            .totals td {
                padding: 8px;
                border: none;
            }
            .totals .total-row {
                font-weight: bold;
                font-size: 16px;
                color: #003399;
            }
            .footer {
                margin-top: 50px;
                padding-top: 20px;
                border-top: 1px solid #ddd;
                font-size: 11px;
                color: #666;
                text-align: center;
            }
            .signatures {
                margin-top: 50px;
                display: flex;
                justify-content: space-between;
            }
            .signature-line {
                width: 200px;
                border-top: 1px solid #000;
                margin-top: 30px;
                text-align: center;
            }
            .status-badge {
                display: inline-block;
                padding: 5px 10px;
                border-radius: 3px;
                font-weight: bold;
                text-transform: uppercase;
                font-size: 12px;
            }
            .status-draft { background: #ffeeba; color: #856404; }
            .status-sent { background: #cce5ff; color: #004085; }
            .status-accepted { background: #d4edda; color: #155724; }
            .status-expired { background: #fff3cd; color: #856404; }
            .status-cancelled { background: #f8d7da; color: #721c24; }
            @media print {
                .no-print { display: none; }
                body { margin: 0; }
            }
        </style>
    </head>
    <body>
        <div class="header">
            <h1>RUHONDO BEACH RESORT</h1>
            <div class="company-details">
                Lake Ruhondo, Musanze - Northern Province, Rwanda<br>
                Tel: +250 123 456 789 | Email: reservations@ruhondobeach.com<br>
                TIN: 112345657
            </div>
        </div>

        <div class="quote-title">Hotel Proforma Invoice</div>

        <div class="info-section">
            <table width="100%">
                <tr>
                    <td width="50%">
                        <strong>Quote Number:</strong> <?php echo $quotation['quotation_number']; ?><br>
                        <strong>Issue Date:</strong> <?php echo date('d M Y', strtotime($quotation['issue_date'])); ?><br>
                        <strong>Valid Until:</strong> <?php echo date('d M Y', strtotime($quotation['valid_until'])); ?>
                    </td>
                    <td width="50%" style="text-align: right;">
                        <span class="status-badge status-<?php echo $quotation['status']; ?>">
                            <?php echo strtoupper($quotation['status']); ?>
                        </span>
                    </td>
                </tr>
            </table>
        </div>

        <div class="info-box">
            <h3>RECEIVER</h3>
            <h2><?php echo htmlspecialchars($quotation['customer_name']); ?></h2>
            <p>
                <?php echo htmlspecialchars($quotation['customer_address_line1'] ?? ''); ?><br>
                <?php echo htmlspecialchars($quotation['customer_address_line2'] ?? ''); ?><br>
                <?php if (!empty($quotation['customer_email'])): ?>
                    Email: <?php echo htmlspecialchars($quotation['customer_email']); ?><br>
                <?php endif; ?>
                <?php if (!empty($quotation['customer_phone'])): ?>
                    Tel: <?php echo htmlspecialchars($quotation['customer_phone']); ?>
                <?php endif; ?>
            </p>
        </div>

        <h3>QUOTATION ITEMS</h3>
        <table>
            <thead>
                <tr>
                    <th>QTY</th>
                    <th>DESCRIPTION</th>
                    <th>UNIT PRICE</th>
                    <th>SUBTOTAL</th>
                    <th>VAT (18%)</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($items as $item): ?>
                <tr>
                    <td><?php echo $item['quantity']; ?> Nights</td>
                    <td><?php echo htmlspecialchars($item['description']); ?></td>
                    <td><?php echo format_currency($item['unit_price']); ?></td>
                    <td><?php echo format_currency($item['subtotal']); ?></td>
                    <td><?php echo format_currency($item['vat_amount']); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <div class="totals">
            <table>
                <tr>
                    <td><strong>Subtotal:</strong></td>
                    <td align="right"><?php echo format_currency($quotation['subtotal']); ?></td>
                </tr>
                <tr>
                    <td><strong>VAT (18%):</strong></td>
                    <td align="right"><?php echo format_currency($quotation['vat_amount']); ?></td>
                </tr>
                <tr class="total-row">
                    <td><strong>TOTAL:</strong></td>
                    <td align="right"><strong><?php echo format_currency($quotation['total_amount']); ?></strong></td>
                </tr>
            </table>
        </div>

        <div style="clear: both;"></div>

        <?php if (!empty($quotation['notes'])): ?>
        <div class="info-box">
            <h3>NOTES</h3>
            <p><?php echo nl2br(htmlspecialchars($quotation['notes'])); ?></p>
        </div>
        <?php endif; ?>

        <div class="info-box">
            <h3>TERMS AND CONDITIONS</h3>
            <ol style="font-size: 12px;">
                <li>This quotation is valid until <?php echo date('d M Y', strtotime($quotation['valid_until'])); ?>.</li>
                <li>All prices are inclusive of 18% VAT.</li>
                <li>Payment is required upon check-in or as agreed in advance.</li>
                <li>Cancellation policy: 48 hours prior to arrival for full refund.</li>
                <li>Check-in time: 14:00, Check-out time: 11:00.</li>
                <li>For any queries, please contact our reservations team.</li>
            </ol>
        </div>

        <div class="signatures">
            <div>
                <div class="signature-line"></div>
                <p><strong>For Ruhondo Beach Resort</strong></p>
            </div>
            <div>
                <div class="signature-line"></div>
                <p><strong>Customer Signature</strong></p>
            </div>
        </div>

        <div class="footer">
            <p>This is a computer generated quotation. No signature is required.</p>
            <p>Generated on: <?php echo date('d M Y H:i:s'); ?></p>
            <p class="no-print">
                <button onclick="window.print()">Print</button>
                <button onclick="window.close()">Close</button>
            </p>
        </div>
    </body>
    </html>
    <?php
}
?>