<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Invoice PDF Generator - FIXED PATH
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging (comment out in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct path using multiple fallbacks
$base_path = null;

// Method 1: Try dirname(__DIR__, 3) - should go up three levels to root from admin/billing/invoices/
$base_path = dirname(__DIR__, 3);

// Method 2: If config doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/config.php')) {
    // Manual calculation: /HMSPOS/admin/billing/invoices/ -> /HMSPOS/
    $base_path = dirname(__DIR__, 4);
}

// Method 3: If still not found, use absolute path as last resort
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Method 4: Try to find by traversing up until we find config directory
$current_dir = __DIR__;
while (!file_exists($current_dir . '/config/config.php') && $current_dir != dirname($current_dir)) {
    $current_dir = dirname($current_dir);
}
if (file_exists($current_dir . '/config/config.php')) {
    $base_path = $current_dir;
}

// Load required files
$required_files = [
    '/config/config.php',
    '/config/constants.php',
    '/config/database.php',
    '/config/helpers.php',
    '/config/auth.php'
];

foreach ($required_files as $file) {
    $file_path = $base_path . $file;
    if (file_exists($file_path)) {
        require_once $file_path;
    } else {
        error_log("Required file not found: " . $file_path);
        // Try alternate path without HMSPOS
        $alt_path = str_replace('/HMSPOS', '', $base_path) . $file;
        if (file_exists($alt_path)) {
            require_once $alt_path;
        } else {
            // Try one more fallback
            $fallback_path = dirname(__DIR__, 2) . $file;
            if (file_exists($fallback_path)) {
                require_once $fallback_path;
            }
        }
    }
}

// Require authentication
if (function_exists('require_auth')) {
    require_auth();
} else {
    // Fallback authentication check
    session_start();
    if (!isset($_SESSION['user_id'])) {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// Define format_date function if it doesn't exist
if (!function_exists('format_date')) {
    function format_date($date, $format = 'M d, Y') {
        if (empty($date)) return '';
        return date($format, strtotime($date));
    }
}

// Define htmlspecialchars as an alias for escape_html if needed
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

// Define CURRENCY_SYMBOL if not defined
if (!defined('CURRENCY_SYMBOL')) {
    define('CURRENCY_SYMBOL', 'RWF');
}

// Check if user is authenticated
$user_id = $_SESSION['user_id'] ?? 0;
if (!$user_id) {
    header('Location: /HMSPOS/public/login.php');
    exit;
}

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

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

// Get invoice data with details
$invoice = [];
if (function_exists('db_fetch_one')) {
    try {
        $invoice = db_fetch_one("
            SELECT 
                i.*,
                g.guest_id, g.first_name, g.last_name, g.email, g.phone,
                g.address, g.city, g.country,
                r.booking_code, r.check_in_date, r.check_out_date
            FROM invoices i
            JOIN guests g ON i.guest_id = g.guest_id
            LEFT JOIN reservations r ON i.reservation_id = r.reservation_id
            WHERE i.invoice_id = ?
        ", [$invoice_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching invoice: " . $e->getMessage());
        die('Error loading invoice data');
    }
}

if (empty($invoice)) {
    die('Invoice not found');
}

// Get invoice items
$items = [];
if (function_exists('db_fetch_all')) {
    try {
        $items = db_fetch_all("
            SELECT * FROM invoice_items 
            WHERE invoice_id = ?
            ORDER BY item_id
        ", [$invoice_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching invoice items: " . $e->getMessage());
    }
}

// Get payments for this invoice
$payments = [];
if (function_exists('db_fetch_all')) {
    try {
        $payments = db_fetch_all("
            SELECT p.*, pm.method_name
            FROM payments p
            JOIN payment_methods pm ON p.payment_method_id = pm.payment_method_id
            WHERE p.invoice_id = ?
            ORDER BY p.payment_date
        ", [$invoice_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching payments: " . $e->getMessage());
    }
}

// Get resort settings
$resort = [];
if (function_exists('db_fetch_one')) {
    try {
        $resort = db_fetch_one("SELECT * FROM resort_settings LIMIT 1") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching resort settings: " . $e->getMessage());
    }
}

// Calculate totals
$total_paid = 0;
foreach ($payments as $payment) {
    if (($payment['status'] ?? '') == 'completed') {
        $total_paid += $payment['amount'] ?? 0;
    }
}
$balance = ($invoice['total_amount'] ?? 0) - $total_paid;

// Load Dompdf
$autoload_path = $base_path . '/vendor/autoload.php';
if (file_exists($autoload_path)) {
    require_once $autoload_path;
} else {
    // Try alternative paths for Composer autoload
    $alt_autoload_paths = [
        dirname(__DIR__, 4) . '/vendor/autoload.php',
        dirname(__DIR__, 3) . '/vendor/autoload.php',
        dirname(__DIR__, 2) . '/vendor/autoload.php',
        __DIR__ . '/../../vendor/autoload.php',
        '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS/vendor/autoload.php'
    ];
    
    $found = false;
    foreach ($alt_autoload_paths as $path) {
        if (file_exists($path)) {
            require_once $path;
            $found = true;
            break;
        }
    }
    
    if (!$found) {
        die('Dompdf library not found. Please run: composer require dompdf/dompdf');
    }
}

use Dompdf\Dompdf;
use Dompdf\Options;

// Generate HTML for PDF
$html = '
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice ' . htmlspecialchars($invoice['invoice_number'] ?? 'N/A') . '</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            font-size: 12px;
            line-height: 1.4;
            margin: 0;
            padding: 20px;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
            border-bottom: 2px solid #333;
            padding-bottom: 10px;
        }
        .header h1 {
            margin: 0;
            font-size: 24px;
            color: #333;
        }
        .header p {
            margin: 5px 0;
            color: #666;
        }
        .invoice-title {
            font-size: 20px;
            font-weight: bold;
            text-align: center;
            margin: 20px 0;
            text-transform: uppercase;
        }
        .company-info, .client-info {
            width: 45%;
            margin-bottom: 20px;
        }
        .client-info {
            float: right;
        }
        .invoice-info {
            clear: both;
            margin: 20px 0;
            padding: 10px;
            background: #f9f9f9;
            border-radius: 5px;
        }
        .invoice-info table {
            width: 100%;
        }
        .invoice-info td {
            padding: 5px;
        }
        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        .items-table th {
            background: #f0f0f0;
            padding: 8px;
            text-align: left;
            border-bottom: 2px solid #333;
        }
        .items-table td {
            padding: 8px;
            border-bottom: 1px solid #ccc;
        }
        .items-table .text-right {
            text-align: right;
        }
        .items-table .text-center {
            text-align: center;
        }
        .totals {
            width: 300px;
            margin-left: auto;
            border-collapse: collapse;
        }
        .totals td {
            padding: 5px;
        }
        .totals .total-row {
            font-weight: bold;
            border-top: 2px solid #333;
        }
        .payment-history {
            margin-top: 30px;
        }
        .payment-history table {
            width: 100%;
            border-collapse: collapse;
        }
        .payment-history th {
            background: #f0f0f0;
            padding: 5px;
            text-align: left;
        }
        .payment-history td {
            padding: 5px;
            border-bottom: 1px solid #eee;
        }
        .footer {
            margin-top: 50px;
            text-align: center;
            border-top: 1px solid #ccc;
            padding-top: 20px;
            color: #666;
            font-size: 11px;
        }
        .status-paid {
            color: #28a745;
            font-weight: bold;
        }
        .status-overdue {
            color: #dc3545;
            font-weight: bold;
        }
        .status-partial {
            color: #ffc107;
            font-weight: bold;
        }
        .status-draft {
            color: #6c757d;
            font-weight: bold;
        }
        .status-sent {
            color: #17a2b8;
            font-weight: bold;
        }
        .terms {
            margin-top: 30px;
            font-size: 10px;
            color: #666;
            border-top: 1px dotted #ccc;
            padding-top: 10px;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>' . htmlspecialchars($resort['resort_name'] ?? 'Ruhondo Beach Resort') . '</h1>
        <p>' . htmlspecialchars($resort['resort_address'] ?? '') . '</p>
        <p>Tel: ' . htmlspecialchars($resort['resort_phone'] ?? '+250 788 888 888') . ' | Email: ' . htmlspecialchars($resort['resort_email'] ?? 'info@ruhondo.com') . '</p>
    </div>

    <div class="invoice-title">
        INVOICE
    </div>

    <div style="overflow: auto;">
        <div class="company-info">
            <strong>From:</strong><br>
            ' . htmlspecialchars($resort['resort_name'] ?? 'Ruhondo Beach Resort') . '<br>
            ' . htmlspecialchars($resort['resort_address'] ?? '') . '<br>
            ' . htmlspecialchars($resort['resort_city'] ?? '') . ', ' . htmlspecialchars($resort['resort_country'] ?? '') . '
        </div>
        
        <div class="client-info">
            <strong>Bill To:</strong><br>
            ' . htmlspecialchars(($invoice['first_name'] ?? '') . ' ' . ($invoice['last_name'] ?? '')) . '<br>
            ' . htmlspecialchars($invoice['email'] ?? '') . '<br>
            ' . htmlspecialchars($invoice['phone'] ?? '') . '<br>';

if (!empty($invoice['address'])) {
    $html .= htmlspecialchars($invoice['address']) . '<br>';
}
if (!empty($invoice['city']) || !empty($invoice['country'])) {
    $html .= htmlspecialchars(implode(', ', array_filter([$invoice['city'] ?? '', $invoice['country'] ?? ''])));
}

$html .= '
        </div>
    </div>

    <div class="invoice-info">
        <table>
            <tr>
                <td><strong>Invoice Number:</strong></td>
                <td>' . htmlspecialchars($invoice['invoice_number'] ?? 'N/A') . '</td>
                <td><strong>Invoice Date:</strong></td>
                <td>' . (isset($invoice['invoice_date']) ? date('M d, Y', strtotime($invoice['invoice_date'])) : 'N/A') . '</td>
            </tr>
            <tr>
                <td><strong>Due Date:</strong></td>
                <td>' . (isset($invoice['due_date']) ? date('M d, Y', strtotime($invoice['due_date'])) : 'N/A') . '</td>
                <td><strong>Status:</strong></td>
                <td><span class="status-' . ($invoice['status'] ?? 'draft') . '">' . ucfirst($invoice['status'] ?? 'draft') . '</span></td>
            </tr>';

if (!empty($invoice['booking_code'])) {
    $html .= '
            <tr>
                <td><strong>Booking Reference:</strong></td>
                <td colspan="3">' . htmlspecialchars($invoice['booking_code']) . '</td>
            </tr>';
}

$html .= '
        </table>
    </div>

    <table class="items-table">
        <thead>
            <tr>
                <th>Description</th>
                <th class="text-center">Quantity</th>
                <th class="text-right">Unit Price</th>
                <th class="text-right">Amount</th>
            </tr>
        </thead>
        <tbody>';

foreach ($items as $item) {
    $html .= '
            <tr>
                <td>' . htmlspecialchars($item['description'] ?? '') . '</td>
                <td class="text-center">' . ($item['quantity'] ?? 0) . '</td>
                <td class="text-right">' . CURRENCY_SYMBOL . ' ' . number_format($item['unit_price'] ?? 0, 2) . '</td>
                <td class="text-right">' . CURRENCY_SYMBOL . ' ' . number_format($item['total_amount'] ?? 0, 2) . '</td>
            </tr>';
}

$html .= '
        </tbody>
    </table>

    <table class="totals">
        <tr>
            <td>Subtotal:</td>
            <td class="text-right">' . CURRENCY_SYMBOL . ' ' . number_format($invoice['subtotal'] ?? 0, 2) . '</td>
        </tr>
        <tr>
            <td>Tax:</td>
            <td class="text-right">' . CURRENCY_SYMBOL . ' ' . number_format($invoice['tax_amount'] ?? 0, 2) . '</td>
        </tr>
        <tr class="total-row">
            <td><strong>TOTAL:</strong></td>
            <td class="text-right"><strong>' . CURRENCY_SYMBOL . ' ' . number_format($invoice['total_amount'] ?? 0, 2) . '</strong></td>
        </tr>
        <tr>
            <td>Paid:</td>
            <td class="text-right">' . CURRENCY_SYMBOL . ' ' . number_format($total_paid, 2) . '</td>
        </tr>
        <tr>
            <td><strong>Balance Due:</strong></td>
            <td class="text-right"><strong>' . CURRENCY_SYMBOL . ' ' . number_format($balance, 2) . '</strong></td>
        </tr>
    </table>';

if (!empty($payments)) {
    $html .= '
    <div class="payment-history">
        <h4>Payment History</h4>
        <table>
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Method</th>
                    <th>Reference</th>
                    <th class="text-right">Amount</th>
                </tr>
            </thead>
            <tbody>';

    foreach ($payments as $payment) {
        $html .= '
                <tr>
                    <td>' . (isset($payment['payment_date']) ? date('M d, Y', strtotime($payment['payment_date'])) : 'N/A') . '</td>
                    <td>' . htmlspecialchars($payment['method_name'] ?? '') . '</td>
                    <td>' . htmlspecialchars($payment['reference_number'] ?? '-') . '</td>
                    <td class="text-right">' . CURRENCY_SYMBOL . ' ' . number_format($payment['amount'] ?? 0, 2) . '</td>
                </tr>';
    }

    $html .= '
            </tbody>
        </table>
    </div>';
}

if (!empty($invoice['notes'])) {
    $html .= '
    <div style="margin-top: 20px;">
        <strong>Notes:</strong><br>
        <p>' . nl2br(htmlspecialchars($invoice['notes'])) . '</p>
    </div>';
}

$html .= '
    <div class="terms">
        <p><strong>Terms & Conditions:</strong></p>
        <p>1. Payment is due by the due date shown above.</p>
        <p>2. Late payments may be subject to interest charges.</p>
        <p>3. Please include the invoice number with your payment.</p>
        <p>4. This invoice is valid only when bearing our company details.</p>
    </div>

    <div class="footer">
        <p>Thank you for your business!</p>
        <p>' . htmlspecialchars($invoice['invoice_number'] ?? 'N/A') . ' | Generated on ' . date('Y-m-d H:i:s') . '</p>
        <p>This is a computer generated invoice. No signature required.</p>
        <p>&copy; ' . date('Y') . ' ' . htmlspecialchars($resort['resort_name'] ?? 'Ruhondo Beach Resort') . '</p>
    </div>
</body>
</html>';

// Configure Dompdf
$options = new Options();
$options->set('isHtml5ParserEnabled', true);
$options->set('isPhpEnabled', false);
$options->set('defaultFont', 'Arial');
$options->set('isRemoteEnabled', true);

$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();

// Output PDF
$filename = "invoice_{$invoice['invoice_number']}.pdf";
$dompdf->stream($filename, array("Attachment" => false));