<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Process Room Charge
 * Developer: JOACHIM'S INNOTECH
 */

// Initialize system
require_once dirname(__DIR__, 3) . '/config/config.php';
require_once dirname(__DIR__, 3) . '/config/constants.php';
require_once dirname(__DIR__, 3) . '/config/database.php';
require_once dirname(__DIR__, 3) . '/config/helpers.php';
require_once dirname(__DIR__, 3) . '/config/auth.php';
require_once dirname(__DIR__, 3) . '/config/csrf.php';

// Require authentication
require_auth();

// Get current user
$current_user = current_user();

// Check if it's an AJAX request
if (!is_ajax_request()) {
    http_response_code(403);
    exit('Direct access not permitted');
}

// Verify CSRF token
if (!verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '')) {
    json_error('Invalid security token');
}

// Get checkout data
$data = json_decode($_POST['data'] ?? '{}', true);

if (empty($data)) {
    json_error('Invalid room charge data');
}

// Validate required fields
if (empty($data['outlet_id'])) {
    json_error('Outlet is required');
}

if (empty($data['reservation_id'])) {
    json_error('Reservation is required for room charge');
}

if (empty($data['items'])) {
    json_error('Cart is empty');
}

// Check for open shift
$active_shift = db_fetch_one("
    SELECT * FROM pos_shifts 
    WHERE user_id = ? AND status = 'open'
    ORDER BY opened_at DESC LIMIT 1
", [$current_user['user_id']]);

if (!$active_shift) {
    json_error('No open shift found');
}

// Verify reservation exists and is checked in
$reservation = db_fetch_one("
    SELECT r.*, g.first_name, g.last_name, g.guest_id
    FROM reservations r
    JOIN guests g ON r.guest_id = g.guest_id
    WHERE r.reservation_id = ? AND r.booking_status = 'checked_in'
", [$data['reservation_id']]);

if (!$reservation) {
    json_error('Invalid or inactive reservation');
}

// Begin transaction
try {
    begin_transaction();
    
    // Calculate totals
    $subtotal = $data['subtotal'];
    $discount = (float)($data['discount'] ?? 0);
    $discount_type = $data['discount_type'] ?? 'fixed';
    
    // Calculate discount amount
    $discount_amount = $discount;
    if ($discount_type === 'percentage') {
        $discount_amount = ($subtotal * $discount) / 100;
    }
    
    // Calculate tax (simplified - in production, use actual tax rates per product)
    $tax_amount = $subtotal * 0.18; // 18% VAT
    $total_amount = $subtotal + $tax_amount - $discount_amount;
    
    // Generate receipt number
    $receipt_number = generate_receipt_number();
    
    // Create sale record
    $sale_id = db_insert('pos_sales', [
        'receipt_number' => $receipt_number,
        'shift_id' => $active_shift['shift_id'],
        'user_id' => $current_user['user_id'],
        'outlet_id' => $data['outlet_id'],
        'guest_id' => $reservation['guest_id'],
        'reservation_id' => $data['reservation_id'],
        'customer_name' => $reservation['first_name'] . ' ' . $reservation['last_name'],
        'subtotal' => $subtotal,
        'tax_amount' => $tax_amount,
        'discount_amount' => $discount_amount,
        'discount_type' => $discount_type,
        'discount_value' => $discount,
        'total_amount' => $total_amount,
        'payment_method_id' => 8, // Room charge method ID
        'payment_status' => 'completed',
        'transaction_type' => 'sale',
        'sale_time' => date(DATETIME_FORMAT)
    ]);
    
    // Insert sale items
    foreach ($data['items'] as $item) {
        db_insert('pos_sale_items', [
            'sale_id' => $sale_id,
            'product_id' => $item['id'],
            'quantity' => $item['quantity'],
            'unit_price' => $item['price'],
            'total_amount' => $item['price'] * $item['quantity']
        ]);
        
        // Update stock if item is tracked
        $product = db_fetch_one("SELECT stock_item, current_stock FROM pos_products WHERE product_id = ?", [$item['id']]);
        
        if ($product && $product['stock_item']) {
            $new_stock = $product['current_stock'] - $item['quantity'];
            
            db_update('pos_products', [
                'current_stock' => $new_stock
            ], 'product_id = ?', [$item['id']]);
            
            // Record stock movement
            db_insert('stock_movements', [
                'product_id' => $item['id'],
                'movement_type' => 'sale',
                'quantity' => -$item['quantity'],
                'reference_type' => 'sale',
                'reference_id' => $sale_id,
                'created_by' => $current_user['user_id']
            ]);
        }
    }
    
    // Update shift totals
    db_update('pos_shifts', [
        'room_charge_sales' => $active_shift['room_charge_sales'] + $total_amount,
        'total_sales' => $active_shift['total_sales'] + $total_amount
    ], 'shift_id = ?', [$active_shift['shift_id']]);
    
    // Create folio charge
    $transaction_code = generate_transaction_code();
    
    db_insert('folio_charges', [
        'reservation_id' => $data['reservation_id'],
        'transaction_code' => $transaction_code,
        'charge_type' => 'fnb',
        'description' => 'POS Sale - ' . $receipt_number,
        'quantity' => count($data['items']),
        'amount' => $total_amount,
        'tax_amount' => $tax_amount,
        'pos_outlet_id' => $data['outlet_id'],
        'posted_by' => $current_user['user_id']
    ]);
    
    // Update reservation payment status
    $new_paid = $reservation['paid_amount'] + $total_amount;
    $payment_status = $new_paid >= $reservation['total_amount'] ? 'paid' : 'partial';
    
    db_update('reservations', [
        'paid_amount' => $new_paid,
        'payment_status' => $payment_status
    ], 'reservation_id = ?', [$data['reservation_id']]);
    
    // Create guest activity record
    db_insert('guest_activity', [
        'guest_id' => $reservation['guest_id'],
        'activity_type' => 'room_charge',
        'description' => "Room charge added: $receipt_number - " . format_currency($total_amount),
        'reference_id' => $sale_id,
        'reference_type' => 'pos_sale',
        'created_by' => $current_user['user_id']
    ]);
    
    // Audit log
    audit_log($current_user['user_id'], 'room_charge', 'pos_sales', $sale_id, null, [
        'receipt' => $receipt_number,
        'reservation' => $data['reservation_id'],
        'amount' => $total_amount
    ]);
    
    commit_transaction();
    
    json_success([
        'sale_id' => $sale_id,
        'receipt_number' => $receipt_number,
        'amount' => $total_amount
    ], 'Room charge completed successfully');
    
} catch (Exception $e) {
    rollback_transaction();
    log_message("Room charge failed: " . $e->getMessage(), 'ERROR');
    json_error('Room charge failed: ' . $e->getMessage());
}