<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Create Invoice - FINAL VERSION with Proper Foreign Keys
 * Developer: JOACHIM'S INNOTECH
 */

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

// Calculate the correct path
$base_path = null;
$base_path = dirname(__DIR__, 3);

if (!file_exists($base_path . '/config/config.php')) {
    $base_path = dirname(__DIR__, 4);
}

if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

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

foreach ($required_files as $file) {
    $file_path = $base_path . $file;
    if (file_exists($file_path)) {
        require_once $file_path;
    }
}

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

// Check permission
if (function_exists('require_permission')) {
    require_permission('billing.invoices.manage');
}

// Define helper functions
if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'FRw ' . number_format($amount ?? 0, 2);
    }
}

if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('sanitize_input')) {
    function sanitize_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
        return $data;
    }
}

if (!function_exists('set_flash_message')) {
    function set_flash_message($type, $message) {
        if (!isset($_SESSION['flash_messages'])) {
            $_SESSION['flash_messages'] = [];
        }
        $_SESSION['flash_messages'][] = ['type' => $type, 'message' => $message];
    }
}

if (!function_exists('redirect')) {
    function redirect($url) {
        header('Location: ' . $url);
        exit;
    }
}

if (!function_exists('begin_transaction')) {
    function begin_transaction() {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db) {
                $db->beginTransaction();
                return $db;
            }
        }
        return null;
    }
}

if (!function_exists('commit_transaction')) {
    function commit_transaction() {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db && $db->inTransaction()) {
                return $db->commit();
            }
        }
        return false;
    }
}

if (!function_exists('rollback_transaction')) {
    function rollback_transaction() {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db && $db->inTransaction()) {
                return $db->rollBack();
            }
        }
        return false;
    }
}

// Set page title
$page_title = 'Create Invoice';

// Get current user
$current_user = null;
if (function_exists('current_user')) {
    $current_user = current_user();
} else {
    if (isset($_SESSION['user_id']) && function_exists('db_fetch_one')) {
        $current_user = db_fetch_one("SELECT * FROM users WHERE user_id = ?", [$_SESSION['user_id']]);
    }
}

$user_id = $current_user['user_id'] ?? $_SESSION['user_id'] ?? 0;

// Get parameters from URL
$reservation_id = isset($_GET['reservation_id']) ? (int)$_GET['reservation_id'] : 0;
$guest_id_param = isset($_GET['guest_id']) ? (int)$_GET['guest_id'] : 0;

// Get all guests for dropdown
$guests = [];
if (function_exists('db_fetch_all')) {
    try {
        $guests = db_fetch_all("
            SELECT guest_id, first_name, last_name, email 
            FROM guests 
            ORDER BY first_name, last_name
        ") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching guests: " . $e->getMessage());
    }
}

// Initialize variables
$selected_guest = null;
$reservation = null;
$subtotal = 0;
$tax_amount = 0;
$total_amount = 0;

// If reservation_id is provided, fetch reservation details
if ($reservation_id && function_exists('db_fetch_one')) {
    try {
        $reservation = db_fetch_one("
            SELECT 
                r.*,
                g.guest_id, g.first_name, g.last_name, g.email, g.phone,
                rt.type_name, rt.base_price, rt.room_type_id,
                DATEDIFF(r.check_out_date, r.check_in_date) as nights
            FROM reservations r
            JOIN guests g ON r.guest_id = g.guest_id
            JOIN room_types rt ON r.room_type_id = rt.room_type_id
            WHERE r.reservation_id = ?
        ", [$reservation_id]);
        
        if ($reservation) {
            $selected_guest = [
                'guest_id' => $reservation['guest_id'],
                'first_name' => $reservation['first_name'],
                'last_name' => $reservation['last_name'],
                'email' => $reservation['email'] ?? ''
            ];
            
            $guest_id_param = $reservation['guest_id'];
            
            // Calculate amounts
            $nights = max(1, intval($reservation['nights'] ?? 1));
            $base_price = floatval($reservation['base_price'] ?? 0);
            $room_charge = $base_price * $nights;
            
            // Calculate tax (18% VAT)
            $tax_rate = 0.18;
            $tax_amount = $room_charge * $tax_rate;
            $total_amount = $room_charge + $tax_amount;
            $subtotal = $room_charge;
        }
    } catch (Exception $e) {
        error_log("Error fetching reservation: " . $e->getMessage());
    }
}

// If guest_id is provided but no reservation, fetch guest details
if ($guest_id_param && !$reservation && function_exists('db_fetch_one')) {
    try {
        $guest = db_fetch_one("SELECT * FROM guests WHERE guest_id = ?", [$guest_id_param]);
        if ($guest) {
            $selected_guest = $guest;
        }
    } catch (Exception $e) {
        error_log("Error fetching guest: " . $e->getMessage());
    }
}

// Handle form submission
$errors = [];
$form_data = [
    'guest_id' => $guest_id_param,
    'invoice_date' => date('Y-m-d'),
    'due_date' => date('Y-m-d', strtotime('+30 days')),
    'notes' => ''
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF verification
    $token = $_POST['csrf_token'] ?? '';
    if (function_exists('verify_csrf_token') && !verify_csrf_token($token)) {
        $errors[] = 'Invalid security token';
    } else {
        $form_data['guest_id'] = isset($_POST['guest_id']) ? (int)$_POST['guest_id'] : 0;
        $form_data['invoice_date'] = isset($_POST['invoice_date']) ? $_POST['invoice_date'] : date('Y-m-d');
        $form_data['due_date'] = isset($_POST['due_date']) ? $_POST['due_date'] : date('Y-m-d', strtotime('+30 days'));
        $form_data['notes'] = isset($_POST['notes']) ? sanitize_input($_POST['notes']) : '';
        
        // Validate
        if (!$form_data['guest_id']) {
            $errors[] = 'Please select a guest';
        }
        
        if ($total_amount <= 0) {
            $errors[] = 'Invoice total must be greater than 0';
        }
        
        if (empty($errors)) {
            // Database connection for transaction
            $db = null;
            try {
                if (function_exists('begin_transaction')) {
                    $db = begin_transaction();
                }
                
                // Generate invoice number
                $invoice_number = 'INV-' . date('Ymd') . '-' . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
                
                // Create invoice - Using 'draft' as status (from your enum: draft, sent, partial, paid, overdue)
                $invoice_id = null;
                if (function_exists('db_insert')) {
                    $invoice_data = [
                        'invoice_number' => $invoice_number,
                        'guest_id' => $form_data['guest_id'],
                        'reservation_id' => $reservation_id ?: null,
                        'invoice_date' => $form_data['invoice_date'],
                        'due_date' => $form_data['due_date'],
                        'subtotal' => $subtotal,
                        'tax_amount' => $tax_amount,
                        'discount_amount' => 0.00,
                        'total_amount' => $total_amount,
                        'paid_amount' => 0.00,
                        'status' => 'draft',
                        'notes' => $form_data['notes'] ?: null,
                        'created_by' => $user_id,
                        'created_at' => date('Y-m-d H:i:s')
                    ];
                    
                    error_log("Inserting invoice with data: " . print_r($invoice_data, true));
                    
                    $invoice_id = db_insert('invoices', $invoice_data);
                }
                
                if (!$invoice_id) {
                    throw new Exception('Failed to create invoice - database insert returned false');
                }
                
                // First, create a folio charge entry if this is from a reservation
                $charge_id = null;
                if ($reservation_id && function_exists('db_insert')) {
                    // Check if folio_charges table exists and create a charge
                    try {
                        $folio_charge_data = [
                            'reservation_id' => $reservation_id,
                            'guest_id' => $form_data['guest_id'],
                            'description' => 'Room Charge - ' . ($reservation['type_name'] ?? 'Room') . ' (' . ($reservation['nights'] ?? 1) . ' nights)',
                            'quantity' => $reservation['nights'] ?? 1,
                            'unit_price' => $reservation['base_price'] ?? 0,
                            'tax_amount' => $tax_amount,
                            'total_amount' => $total_amount,
                            'charge_type' => 'room',
                            'created_at' => date('Y-m-d H:i:s')
                        ];
                        
                        error_log("Creating folio charge: " . print_r($folio_charge_data, true));
                        
                        $charge_id = db_insert('folio_charges', $folio_charge_data);
                        
                        if (!$charge_id) {
                            // If folio_charges table doesn't exist or insert fails, just set charge_id to NULL
                            error_log("Could not create folio charge, continuing with NULL charge_id");
                            $charge_id = null;
                        }
                    } catch (Exception $e) {
                        // Folio_charges table might not exist, just set charge_id to NULL
                        error_log("Folio charges table error: " . $e->getMessage());
                        $charge_id = null;
                    }
                }
                
                // Create invoice item in invoice_items table
                if (function_exists('db_insert')) {
                    $nights = $reservation['nights'] ?? 1;
                    $item_data = [
                        'invoice_id' => $invoice_id,
                        'description' => 'Room Charge - ' . ($reservation['type_name'] ?? 'Room') . ' (' . $nights . ' nights)',
                        'quantity' => $nights,
                        'unit_price' => $reservation['base_price'] ?? 0,
                        'tax_amount' => $tax_amount,
                        'total_amount' => $total_amount,
                        'charge_id' => $charge_id, // This will be NULL if folio_charges doesn't exist or insert failed
                        'created_at' => date('Y-m-d H:i:s')
                    ];
                    
                    error_log("Inserting invoice item: " . print_r($item_data, true));
                    
                    $item_id = db_insert('invoice_items', $item_data);
                    
                    if (!$item_id) {
                        throw new Exception('Failed to create invoice item');
                    }
                }
                
                // Create guest activity
                if (function_exists('db_insert')) {
                    db_insert('guest_activity', [
                        'guest_id' => $form_data['guest_id'],
                        'activity_type' => 'invoice',
                        'description' => "Invoice #$invoice_number created for total " . format_currency($total_amount),
                        'reference_id' => $invoice_id,
                        'reference_type' => 'invoice',
                        'created_by' => $user_id,
                        'created_at' => date('Y-m-d H:i:s')
                    ]);
                }
                
                if (function_exists('commit_transaction')) {
                    commit_transaction();
                }
                
                if (function_exists('set_flash_message')) {
                    set_flash_message('success', 'Invoice created successfully');
                }
                
                // Redirect based on source
                if ($reservation_id) {
                    redirect('/HMSPOS/admin/reservations/checkin/start.php?id=' . $reservation_id);
                } else {
                    redirect('view.php?id=' . $invoice_id);
                }
                
            } catch (Exception $e) {
                if (function_exists('rollback_transaction')) {
                    rollback_transaction();
                }
                $errors[] = 'Failed to create invoice: ' . $e->getMessage();
                error_log("Invoice creation error: " . $e->getMessage());
                error_log("Stack trace: " . $e->getTraceAsString());
            }
        }
    }
}

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Create Invoice</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
        <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.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>
        <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.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; }
            .reservation-summary { background: #e3f2fd; padding: 15px; border-radius: 5px; margin-bottom: 20px; border-left: 4px solid #2196f3; }
            .summary-box { background: #e9ecef; padding: 15px; border-radius: 5px; }
            .me-1 { margin-right: 0.25rem; }
            .me-2 { margin-right: 0.5rem; }
            .mb-2 { margin-bottom: 0.5rem; }
            .mb-3 { margin-bottom: 1rem; }
            .mt-2 { margin-top: 0.5rem; }
            .mt-4 { margin-top: 1.5rem; }
            .text-right { text-align: right; }
            .alert { margin-bottom: 20px; }
        </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="#">Create Invoice</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> 
                            <?php echo isset($current_user['username']) ? 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">Create Invoice</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/billing/dashboard.php">Billing</a></li>
                    <li class="breadcrumb-item"><a href="index.php">Invoices</a></li>
                    <li class="breadcrumb-item active">Create</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <?php if (!empty($errors)): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-circle me-2"></i>
                <strong>Please fix the following errors:</strong>
                <ul class="mt-2 mb-0">
                    <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-md-8 offset-md-2">
                <!-- Reservation Summary -->
                <?php if ($reservation): ?>
                <div class="reservation-summary">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">
                            <i class="fas fa-concierge-bell me-2"></i>
                            Reservation #<?php echo htmlspecialchars($reservation['booking_code'] ?? $reservation_id); ?>
                        </h5>
                        <span class="badge bg-info"><?php echo ucfirst($reservation['booking_status'] ?? 'confirmed'); ?></span>
                    </div>
                    <div class="row mt-3">
                        <div class="col-md-3">
                            <small class="text-muted d-block">Check In</small>
                            <strong><?php echo date('M d, Y', strtotime($reservation['check_in_date'])); ?></strong>
                        </div>
                        <div class="col-md-3">
                            <small class="text-muted d-block">Check Out</small>
                            <strong><?php echo date('M d, Y', strtotime($reservation['check_out_date'])); ?></strong>
                        </div>
                        <div class="col-md-3">
                            <small class="text-muted d-block">Nights</small>
                            <strong><?php echo $reservation['nights'] ?? 1; ?></strong>
                        </div>
                        <div class="col-md-3">
                            <small class="text-muted d-block">Room Type</small>
                            <strong><?php echo htmlspecialchars($reservation['type_name'] ?? 'N/A'); ?></strong>
                        </div>
                    </div>
                    <div class="row mt-2">
                        <div class="col-md-4">
                            <small class="text-muted d-block">Base Price/Night</small>
                            <strong><?php echo format_currency($reservation['base_price'] ?? 0); ?></strong>
                        </div>
                        <div class="col-md-4">
                            <small class="text-muted d-block">Room Total</small>
                            <strong><?php echo format_currency(($reservation['base_price'] ?? 0) * ($reservation['nights'] ?? 1)); ?></strong>
                        </div>
                        <div class="col-md-4">
                            <small class="text-muted d-block">Total with Tax</small>
                            <strong class="text-success"><?php echo format_currency($total_amount); ?></strong>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Invoice Form -->
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-file-invoice me-1"></i>
                            Invoice Details
                        </h3>
                    </div>
                    
                    <form method="POST" id="invoiceForm">
                        <?php if (function_exists('csrf_field')): ?>
                            <?php echo csrf_field(); ?>
                        <?php else: ?>
                            <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token'] ?? ''; ?>">
                        <?php endif; ?>
                        
                        <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>">
                        
                        <div class="card-body">
                            <!-- Guest Selection -->
                            <div class="form-group mb-3">
                                <label for="guest_id">Guest <span class="text-danger">*</span></label>
                                <?php if ($selected_guest): ?>
                                    <input type="hidden" name="guest_id" value="<?php echo $selected_guest['guest_id']; ?>">
                                    <div class="form-control bg-light">
                                        <i class="fas fa-user me-2"></i>
                                        <?php echo escape_html($selected_guest['first_name'] . ' ' . $selected_guest['last_name']); ?>
                                        <?php if (!empty($selected_guest['email'])): ?>
                                            <small class="text-muted"> - <?php echo htmlspecialchars($selected_guest['email']); ?></small>
                                        <?php endif; ?>
                                    </div>
                                <?php else: ?>
                                    <select class="form-select select2" id="guest_id" name="guest_id" required>
                                        <option value="">Select Guest</option>
                                        <?php foreach ($guests as $guest): ?>
                                            <option value="<?php echo $guest['guest_id']; ?>" 
                                                    <?php echo $form_data['guest_id'] == $guest['guest_id'] ? 'selected' : ''; ?>>
                                                <?php echo escape_html($guest['first_name'] . ' ' . $guest['last_name']); ?>
                                                <?php if (!empty($guest['email'])): ?> - <?php echo htmlspecialchars($guest['email']); ?><?php endif; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Dates -->
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label for="invoice_date">Invoice Date</label>
                                        <input type="date" class="form-control" id="invoice_date" name="invoice_date" 
                                               value="<?php echo $form_data['invoice_date']; ?>" required>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label for="due_date">Due Date</label>
                                        <input type="date" class="form-control" id="due_date" name="due_date" 
                                               value="<?php echo $form_data['due_date']; ?>" required>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Summary -->
                            <div class="row mt-4">
                                <div class="col-md-6 offset-md-6">
                                    <div class="summary-box">
                                        <table class="table table-sm table-borderless mb-0">
                                            <tr>
                                                <th>Subtotal:</th>
                                                <td class="text-end fw-bold" id="subtotal">
                                                    <?php echo format_currency($subtotal); ?>
                                                </td>
                                            </tr>
                                            <tr>
                                                <th>Tax (18% VAT):</th>
                                                <td class="text-end" id="tax">
                                                    <?php echo format_currency($tax_amount); ?>
                                                </td>
                                            </tr>
                                            <tr>
                                                <th>Discount:</th>
                                                <td class="text-end" id="discount">
                                                    FRw 0.00
                                                </td>
                                            </tr>
                                            <tr class="border-top">
                                                <th class="h5 mb-0">Total:</th>
                                                <td class="text-end h5 mb-0 text-success" id="grand-total">
                                                    <?php echo format_currency($total_amount); ?>
                                                </td>
                                            </tr>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Notes -->
                            <div class="form-group mb-3 mt-4">
                                <label for="notes">Notes</label>
                                <textarea class="form-control" id="notes" name="notes" rows="2" placeholder="Additional notes or comments..."><?php echo escape_html($form_data['notes']); ?></textarea>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-success btn-lg">
                                <i class="fas fa-save me-1"></i> Create Invoice
                            </button>
                            <?php if ($reservation_id): ?>
                                <a href="/HMSPOS/admin/reservations/checkin/start.php?id=<?php echo $reservation_id; ?>" class="btn btn-secondary btn-lg">
                                    <i class="fas fa-arrow-left me-1"></i> Back to Check-in
                                </a>
                            <?php else: ?>
                                <a href="index.php" class="btn btn-secondary btn-lg">
                                    <i class="fas fa-times me-1"></i> Cancel
                                </a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
$(document).ready(function() {
    // Initialize Select2
    if ($.fn.select2) {
        $('.select2').select2({
            theme: 'bootstrap-5',
            width: '100%'
        });
    }
});

// Form validation
$('#invoiceForm').on('submit', function(e) {
    // Check guest
    const guestId = $('#guest_id').val();
    if (!guestId && $('input[name="guest_id"]').length === 0) {
        e.preventDefault();
        alert('Please select a guest');
        return false;
    }
    
    const total = <?php echo $total_amount; ?>;
    if (total <= 0) {
        e.preventDefault();
        alert('Invoice total must be greater than 0');
        return false;
    }
    
    return confirm('Create this invoice for <?php echo format_currency($total_amount); ?>?');
});
</script>

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