<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * POS Receipt View - FIXED VERSION
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging
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
$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/pos/sales/ -> /HMSPOS/
    $base_path = dirname(dirname(dirname(__DIR__)));
}

// 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';
}

// Load required files
require_once $base_path . '/config/config.php';
require_once $base_path . '/config/database.php';
require_once $base_path . '/config/auth.php';

// Load helpers if they exist
if (file_exists($base_path . '/config/helpers.php')) {
    require_once $base_path . '/config/helpers.php';
}
if (file_exists($base_path . '/config/csrf.php')) {
    require_once $base_path . '/config/csrf.php';
}

// Require authentication
require_auth();

// Define helper functions if they don't exist
if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount, 0);
    }
}

if (!function_exists('format_datetime')) {
    function format_datetime($datetime) {
        if (empty($datetime)) return '';
        return date('d/m/Y H:i', strtotime($datetime));
    }
}

if (!function_exists('has_permission')) {
    function has_permission($permission) {
        return true; // Bypass permission check for now
    }
}

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

if (!$sale_id) {
    die('Invalid sale ID');
}

// Get sale data
$sale = null;
try {
    // First, get the sale without joining payment_methods
    $sale = db_fetch_one("
        SELECT 
            s.*,
            u.first_name, u.last_name,
            o.outlet_name, o.outlet_code
        FROM pos_sales s
        JOIN users u ON s.user_id = u.user_id
        JOIN pos_outlets o ON s.outlet_id = o.outlet_id
        WHERE s.sale_id = ?
    ", [$sale_id]);
} catch (Exception $e) {
    error_log("Error fetching sale: " . $e->getMessage());
    die('Error loading sale data');
}

if (!$sale) {
    die('Sale not found');
}

// Get sale items
$items = [];
try {
    $items = db_fetch_all("
        SELECT si.*, p.product_name
        FROM pos_sale_items si
        LEFT JOIN pos_products p ON si.product_id = p.product_id
        WHERE si.sale_id = ?
    ", [$sale_id]) ?: [];
} catch (Exception $e) {
    error_log("Error fetching sale items: " . $e->getMessage());
}

// Get resort settings (optional)
$resort = null;
try {
    $resort = db_fetch_one("SELECT * FROM resort_settings LIMIT 1");
} catch (Exception $e) {
    error_log("Error fetching resort settings: " . $e->getMessage());
}

// Set page title
$page_title = 'Receipt - ' . ($sale['receipt_number'] ?? 'Unknown');

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    // Simple fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Receipt - <?php echo htmlspecialchars($sale['receipt_number'] ?? 'Unknown'); ?></title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">POS Receipt</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> 
                            <?php 
                            $current_user = function_exists('current_user') ? current_user() : null;
                            echo htmlspecialchars($current_user['username'] ?? 'User'); 
                            ?>
                        </span>
                        <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </nav>
            <div class="content-wrapper">
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Receipt: <?php echo htmlspecialchars($sale['receipt_number'] ?? ''); ?></h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/pos/dashboard.php">POS</a></li>
                    <li class="breadcrumb-item"><a href="pos.php">Terminal</a></li>
                    <li class="breadcrumb-item active">Receipt</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-6 offset-md-3">
                <!-- Receipt Card -->
                <div class="card card-success" id="receipt">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-receipt me-1"></i>
                            Sale Receipt
                        </h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-tool" onclick="window.print()">
                                <i class="fas fa-print"></i>
                            </button>
                            <?php if (file_exists('receipt-pdf.php')): ?>
                            <a href="receipt-pdf.php?id=<?php echo $sale_id; ?>" class="btn btn-tool" target="_blank">
                                <i class="fas fa-file-pdf"></i>
                            </a>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="card-body">
                        <!-- Header -->
                        <div class="text-center mb-4">
                            <h3><?php echo !empty($resort['resort_name']) ? htmlspecialchars($resort['resort_name']) : 'Ruhondo Beach Resort'; ?></h3>
                            <p class="mb-0"><?php echo !empty($resort['resort_address']) ? htmlspecialchars($resort['resort_address']) : ''; ?></p>
                            <p>Tel: <?php echo !empty($resort['resort_phone']) ? htmlspecialchars($resort['resort_phone']) : '+250 788 888 888'; ?></p>
                        </div>
                        
                        <!-- Receipt Info -->
                        <div class="row mb-3">
                            <div class="col-6">
                                <strong>Receipt No:</strong><br>
                                <?php echo htmlspecialchars($sale['receipt_number'] ?? ''); ?>
                            </div>
                            <div class="col-6 text-end">
                                <strong>Date:</strong><br>
                                <?php echo !empty($sale['sale_time']) ? format_datetime($sale['sale_time']) : ''; ?>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-6">
                                <strong>Cashier:</strong><br>
                                <?php echo htmlspecialchars(($sale['first_name'] ?? '') . ' ' . ($sale['last_name'] ?? '')); ?>
                            </div>
                            <div class="col-6 text-end">
                                <strong>Outlet:</strong><br>
                                <?php echo htmlspecialchars($sale['outlet_name'] ?? ''); ?>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-12">
                                <strong>Customer:</strong><br>
                                <?php echo !empty($sale['customer_name']) ? htmlspecialchars($sale['customer_name']) : 'Walk-in Customer'; ?>
                                <?php if (!empty($sale['guest_id'])): ?>
                                    <br><small>Guest ID: <?php echo $sale['guest_id']; ?></small>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <!-- Items Table -->
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Item</th>
                                    <th class="text-center">Qty</th>
                                    <th class="text-end">Price</th>
                                    <th class="text-end">Total</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($items)): ?>
                                    <tr>
                                        <td colspan="4" class="text-center text-muted">No items found</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($items as $item): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($item['product_name'] ?? 'Product'); ?></td>
                                        <td class="text-center"><?php echo $item['quantity'] ?? 0; ?></td>
                                        <td class="text-end"><?php echo format_currency($item['unit_price'] ?? 0); ?></td>
                                        <td class="text-end"><?php echo format_currency($item['total_amount'] ?? 0); ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                        
                        <!-- Totals -->
                        <div class="row">
                            <div class="col-6 offset-6">
                                <table class="table table-sm">
                                    <tr>
                                        <th>Subtotal:</th>
                                        <td class="text-end"><?php echo format_currency($sale['subtotal'] ?? 0); ?></td>
                                    </tr>
                                    <?php if (isset($sale['tax']) && $sale['tax'] > 0): ?>
                                    <tr>
                                        <th>Tax (18%):</th>
                                        <td class="text-end"><?php echo format_currency($sale['tax'] ?? 0); ?></td>
                                    </tr>
                                    <?php endif; ?>
                                    <?php if (isset($sale['discount']) && $sale['discount'] > 0): ?>
                                    <tr>
                                        <th>Discount:</th>
                                        <td class="text-end text-danger">
                                            -<?php echo format_currency($sale['discount'] ?? 0); ?>
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                    <tr class="table-active">
                                        <th>Total:</th>
                                        <td class="text-end">
                                            <strong><?php echo format_currency($sale['total_amount'] ?? 0); ?></strong>
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                        
                        <!-- Payment Method -->
                        <div class="row mt-3">
                            <div class="col-12">
                                <strong>Payment Method:</strong> <?php echo ucfirst($sale['payment_method'] ?? 'Cash'); ?>
                            </div>
                        </div>
                        
                        <!-- Footer -->
                        <div class="text-center mt-4 pt-3 border-top">
                            <p class="mb-1">Thank you for your business!</p>
                            <p class="small text-muted"><?php echo htmlspecialchars($sale['receipt_number'] ?? ''); ?> | <?php echo date('Y-m-d H:i:s'); ?></p>
                            <?php if (!empty($sale['payment_status']) && $sale['payment_status'] == 'completed'): ?>
                                <p class="text-success"><i class="fas fa-check-circle"></i> Payment Completed</p>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Action Buttons -->
                <div class="row mt-3 no-print">
                    <div class="col-6">
                        <a href="pos.php" class="btn btn-primary w-100">
                            <i class="fas fa-cash-register me-1"></i> New Sale
                        </a>
                    </div>
                    <div class="col-6">
                        <button type="button" class="btn btn-success w-100" onclick="window.print()">
                            <i class="fas fa-print me-1"></i> Print Receipt
                        </button>
                    </div>
                    <?php if (file_exists('receipt-pdf.php')): ?>
                    <div class="col-12 mt-2">
                        <a href="receipt-pdf.php?id=<?php echo $sale_id; ?>" class="btn btn-info w-100" target="_blank">
                            <i class="fas fa-file-pdf me-1"></i> Download PDF
                        </a>
                    </div>
                    <?php endif; ?>
                    <?php if (function_exists('has_permission') && has_permission('pos.sales.void')): ?>
                    <div class="col-12 mt-2">
                        <button type="button" class="btn btn-danger w-100" onclick="voidSale()">
                            <i class="fas fa-ban me-1"></i> Void Transaction
                        </button>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Void Modal -->
<div class="modal fade" id="voidModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger">
                <h5 class="modal-title">Void Transaction</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="voidForm">
                <?php if (function_exists('csrf_field')): ?>
                    <?php echo csrf_field(); ?>
                <?php endif; ?>
                <input type="hidden" name="sale_id" value="<?php echo $sale_id; ?>">
                
                <div class="modal-body">
                    <p>Are you sure you want to void this transaction?</p>
                    
                    <div class="mb-3">
                        <label for="void_reason" class="form-label">Reason for voiding</label>
                        <textarea class="form-control" id="void_reason" name="void_reason" rows="3" required></textarea>
                    </div>
                    
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        This action cannot be undone. Inventory will be adjusted.
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Void Transaction</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function voidSale() {
    const modal = new bootstrap.Modal(document.getElementById('voidModal'));
    modal.show();
}

$('#voidForm').on('submit', function(e) {
    e.preventDefault();
    
    $.ajax({
        url: 'void-refund.php',
        method: 'POST',
        data: $(this).serialize(),
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') {
                $('#voidModal').modal('hide');
                alert('Transaction voided successfully');
                location.reload();
            } else {
                alert('Failed to void transaction: ' + (response.message || 'Unknown error'));
            }
        },
        error: function(xhr, status, error) {
            alert('Failed to void transaction: ' + error);
        }
    });
});
</script>

<style>
@media print {
    .main-header, .main-sidebar, .main-footer, .content-header, .no-print, .btn-tool {
        display: none !important;
    }
    .content-wrapper {
        margin-left: 0 !important;
        padding: 0 !important;
    }
    .card {
        border: none !important;
        box-shadow: none !important;
    }
    #receipt {
        font-size: 10pt;
    }
    .text-end {
        text-align: right !important;
    }
}
.me-1 { margin-right: 0.25rem; }
.me-2 { margin-right: 0.5rem; }
.ms-2 { margin-left: 0.5rem; }
.mb-2 { margin-bottom: 0.5rem; }
.mb-3 { margin-bottom: 1rem; }
.mt-2 { margin-top: 0.5rem; }
.mt-3 { margin-top: 1rem; }
.mt-4 { margin-top: 1.5rem; }
.w-100 { width: 100%; }
.text-end { text-align: right; }
</style>

<?php
// Include footer
$footer_path = $base_path . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    require_once $footer_path;
} else {
    echo '</div></div></body></html>';
}
?>