<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Create Room Type - 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
// Current file: /HMSPOS/rooms/room-types/create.php
// Need to go up to: /HMSPOS/
$base_path = null;

// Method 1: Try dirname(__DIR__, 2) - should go up two levels to root
$base_path = dirname(__DIR__, 2);

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

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

// Load the universal initializer
$init_file = $base_path . '/config/init.php';
if (file_exists($init_file)) {
    require_once $init_file;
} else {
    // Emergency fallback - load files directly
    require_once $base_path . '/config/config.php';
    require_once $base_path . '/config/database.php';
    require_once $base_path . '/config/auth.php';
    
    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 permission check function if it doesn't exist
if (!function_exists('require_permission')) {
    function require_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// Define audit constants if not defined
if (!defined('AUDIT_CREATE')) {
    define('AUDIT_CREATE', 'create');
}

// Define escape_html function if it doesn't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

// Define sanitize_input function if it doesn't exist
if (!function_exists('sanitize_input')) {
    function sanitize_input($data) {
        if (is_array($data)) {
            return array_map('sanitize_input', $data);
        }
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
        return $data;
    }
}

// Check permission (commented out for now)
// if (function_exists('require_permission')) {
//     require_permission('roomtypes.create');
// }

// Set page title
$page_title = 'Create Room Type';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;
$user_id = $current_user['user_id'] ?? 0;

if (!$user_id) {
    if (function_exists('redirect')) {
        redirect('login.php');
    } else {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// Handle form submission
$errors = [];
$form_data = [
    'type_code' => '',
    'type_name' => '',
    'description' => '',
    'max_adults' => 2,
    'max_children' => 0,
    'max_occupancy' => 2,
    'size_sqft' => '',
    'bed_type' => '',
    'base_price' => '',
    'amenities' => ''
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    $csrf_valid = true;
    if (function_exists('verify_csrf_token')) {
        $csrf_name = defined('CSRF_TOKEN_NAME') ? CSRF_TOKEN_NAME : 'csrf_token';
        $token = $_POST[$csrf_name] ?? '';
        if (!verify_csrf_token($token)) {
            $csrf_valid = false;
            $errors[] = 'Invalid security token. Please try again.';
        }
    }
    
    if ($csrf_valid) {
        // Get and validate input
        $form_data['type_code'] = isset($_POST['type_code']) ? strtoupper(trim($_POST['type_code'])) : '';
        $form_data['type_name'] = $_POST['type_name'] ?? '';
        $form_data['description'] = $_POST['description'] ?? '';
        $form_data['max_adults'] = (int)($_POST['max_adults'] ?? 2);
        $form_data['max_children'] = (int)($_POST['max_children'] ?? 0);
        $form_data['max_occupancy'] = (int)($_POST['max_occupancy'] ?? 2);
        $form_data['size_sqft'] = !empty($_POST['size_sqft']) ? (int)$_POST['size_sqft'] : null;
        $form_data['bed_type'] = $_POST['bed_type'] ?? '';
        $form_data['base_price'] = (float)($_POST['base_price'] ?? 0);
        $form_data['amenities'] = $_POST['amenities'] ?? '';
        
        // Validate required fields
        if (empty($form_data['type_code'])) {
            $errors[] = 'Room type code is required';
        } elseif (strlen($form_data['type_code']) > 20) {
            $errors[] = 'Room type code must not exceed 20 characters';
        }
        
        if (empty($form_data['type_name'])) {
            $errors[] = 'Room type name is required';
        } elseif (strlen($form_data['type_name']) > 100) {
            $errors[] = 'Room type name must not exceed 100 characters';
        }
        
        if ($form_data['max_adults'] < 1) {
            $errors[] = 'Maximum adults must be at least 1';
        }
        
        if ($form_data['max_children'] < 0) {
            $errors[] = 'Maximum children cannot be negative';
        }
        
        if ($form_data['max_occupancy'] < ($form_data['max_adults'] + $form_data['max_children'])) {
            $errors[] = 'Maximum occupancy must be at least the sum of adults and children';
        }
        
        if ($form_data['base_price'] <= 0) {
            $errors[] = 'Base price must be greater than 0';
        }
        
        // Check uniqueness
        if (empty($errors)) {
            try {
                // Check if type code exists
                $exists = (int)db_fetch_value("SELECT COUNT(*) FROM room_types WHERE type_code = ?", [$form_data['type_code']]) ?: 0;
                if ($exists > 0) {
                    $errors[] = 'Room type code already exists';
                }
                
                // Check if type name exists
                $exists = (int)db_fetch_value("SELECT COUNT(*) FROM room_types WHERE type_name = ?", [$form_data['type_name']]) ?: 0;
                if ($exists > 0) {
                    $errors[] = 'Room type name already exists';
                }
            } catch (Exception $e) {
                error_log("Error checking uniqueness: " . $e->getMessage());
            }
        }
        
        // Create room type
        if (empty($errors)) {
            try {
                if (function_exists('begin_transaction')) {
                    begin_transaction();
                }
                
                $insert_data = [
                    'type_code' => $form_data['type_code'],
                    'type_name' => $form_data['type_name'],
                    'description' => $form_data['description'] ?: null,
                    'max_adults' => $form_data['max_adults'],
                    'max_children' => $form_data['max_children'],
                    'max_occupancy' => $form_data['max_occupancy'],
                    'size_sqft' => $form_data['size_sqft'],
                    'bed_type' => $form_data['bed_type'] ?: null,
                    'base_price' => $form_data['base_price'],
                    'amenities' => $form_data['amenities'] ?: null
                ];
                
                $room_type_id = null;
                
                if (function_exists('db_insert')) {
                    $room_type_id = db_insert('room_types', $insert_data);
                } else {
                    // Fallback direct insert
                    $pdo = get_db_connection();
                    $sql = "INSERT INTO room_types (type_code, type_name, description, max_adults, max_children, max_occupancy, size_sqft, bed_type, base_price, amenities) 
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([
                        $form_data['type_code'],
                        $form_data['type_name'],
                        $form_data['description'] ?: null,
                        $form_data['max_adults'],
                        $form_data['max_children'],
                        $form_data['max_occupancy'],
                        $form_data['size_sqft'],
                        $form_data['bed_type'] ?: null,
                        $form_data['base_price'],
                        $form_data['amenities'] ?: null
                    ]);
                    $room_type_id = $pdo->lastInsertId();
                }
                
                // Audit log
                if (function_exists('audit_log')) {
                    audit_log($user_id, 'create', 'room_types', $room_type_id, null, $form_data);
                }
                
                if (function_exists('commit_transaction')) {
                    commit_transaction();
                }
                
                if (function_exists('set_flash_message')) {
                    set_flash_message('success', 'Room type created successfully');
                }
                
                // Redirect
                if (function_exists('redirect')) {
                    redirect('view.php?id=' . $room_type_id);
                } else {
                    header('Location: view.php?id=' . $room_type_id);
                    exit;
                }
                
            } catch (Exception $e) {
                if (function_exists('rollback_transaction')) {
                    rollback_transaction();
                }
                $errors[] = 'Failed to create room type: ' . $e->getMessage();
                if (function_exists('log_message')) {
                    log_message("Room type creation failed: " . $e->getMessage(), 'ERROR');
                } else {
                    error_log("Room type creation failed: " . $e->getMessage());
                }
            }
        }
    }
}

// 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>Create Room Type</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="#">Create Room Type</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 Room Type</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/rooms/dashboard.php">Rooms</a></li>
                    <li class="breadcrumb-item"><a href="index.php">Room Types</a></li>
                    <li class="breadcrumb-item active">Create</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-8 offset-md-2">
                <!-- Error Messages -->
                <?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; ?>

                <!-- Create Form -->
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-plus-circle me-1"></i>
                            New Room Type
                        </h3>
                    </div>
                    
                    <form method="POST" id="createForm">
                        <?php if (function_exists('csrf_field')): ?>
                            <?php echo csrf_field(); ?>
                        <?php else: ?>
                            <input type="hidden" name="csrf_token" value="<?php echo bin2hex(random_bytes(32)); ?>">
                        <?php endif; ?>
                        
                        <div class="card-body">
                            <!-- Basic Information -->
                            <h5 class="mb-3">Basic Information</h5>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="type_code">Room Type Code <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="type_code" name="type_code" 
                                               value="<?php echo escape_html($form_data['type_code']); ?>" 
                                               maxlength="20" required placeholder="e.g., STD, DLX, EXE">
                                        <small class="text-muted">Unique identifier, uppercase recommended</small>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="type_name">Room Type Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="type_name" name="type_name" 
                                               value="<?php echo escape_html($form_data['type_name']); ?>" 
                                               maxlength="100" required placeholder="e.g., Standard Room, Deluxe Room">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="description">Description</label>
                                <textarea class="form-control" id="description" name="description" rows="3"><?php echo escape_html($form_data['description']); ?></textarea>
                            </div>
                            
                            <!-- Capacity -->
                            <h5 class="mb-3 mt-4">Capacity</h5>
                            
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="max_adults">Max Adults <span class="text-danger">*</span></label>
                                        <input type="number" class="form-control" id="max_adults" name="max_adults" 
                                               value="<?php echo $form_data['max_adults']; ?>" min="1" max="10" required>
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="max_children">Max Children</label>
                                        <input type="number" class="form-control" id="max_children" name="max_children" 
                                               value="<?php echo $form_data['max_children']; ?>" min="0" max="10">
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="max_occupancy">Max Total Occupancy <span class="text-danger">*</span></label>
                                        <input type="number" class="form-control" id="max_occupancy" name="max_occupancy" 
                                               value="<?php echo $form_data['max_occupancy']; ?>" min="1" max="20" required>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Room Details -->
                            <h5 class="mb-3 mt-4">Room Details</h5>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="size_sqft">Room Size (sq ft)</label>
                                        <input type="number" class="form-control" id="size_sqft" name="size_sqft" 
                                               value="<?php echo $form_data['size_sqft']; ?>" min="0" step="1">
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="bed_type">Bed Type</label>
                                        <select class="form-select" id="bed_type" name="bed_type">
                                            <option value="">Select Bed Type</option>
                                            <option value="Twin" <?php echo $form_data['bed_type'] == 'Twin' ? 'selected' : ''; ?>>Twin</option>
                                            <option value="Double" <?php echo $form_data['bed_type'] == 'Double' ? 'selected' : ''; ?>>Double</option>
                                            <option value="Queen" <?php echo $form_data['bed_type'] == 'Queen' ? 'selected' : ''; ?>>Queen</option>
                                            <option value="King" <?php echo $form_data['bed_type'] == 'King' ? 'selected' : ''; ?>>King</option>
                                            <option value="2 Twins" <?php echo $form_data['bed_type'] == '2 Twins' ? 'selected' : ''; ?>>2 Twins</option>
                                            <option value="2 Queens" <?php echo $form_data['bed_type'] == '2 Queens' ? 'selected' : ''; ?>>2 Queens</option>
                                            <option value="Bunk Beds" <?php echo $form_data['bed_type'] == 'Bunk Beds' ? 'selected' : ''; ?>>Bunk Beds</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Pricing -->
                            <h5 class="mb-3 mt-4">Pricing</h5>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="base_price">Base Price (per night) <span class="text-danger">*</span></label>
                                        <div class="input-group">
                                            <span class="input-group-text"><?php echo defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF'; ?></span>
                                            <input type="number" class="form-control" id="base_price" name="base_price" 
                                                   value="<?php echo $form_data['base_price']; ?>" min="0" step="0.01" required>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Amenities -->
                            <h5 class="mb-3 mt-4">Amenities</h5>
                            
                            <div class="mb-3">
                                <label for="amenities">Amenities</label>
                                <textarea class="form-control" id="amenities" name="amenities" rows="3" 
                                          placeholder="TV, WiFi, AC, Mini Bar, Safe, etc."><?php echo escape_html($form_data['amenities']); ?></textarea>
                                <small class="text-muted">Comma separated list of amenities</small>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save me-1"></i> Create Room Type
                            </button>
                            <a href="index.php" class="btn btn-secondary">
                                <i class="fas fa-times me-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
$(document).ready(function() {
    // Auto-capitalize type code
    $('#type_code').on('input', function() {
        this.value = this.value.toUpperCase();
    });
    
    // Validate occupancy
    $('#max_adults, #max_children').on('input', function() {
        const adults = parseInt($('#max_adults').val()) || 0;
        const children = parseInt($('#max_children').val()) || 0;
        const total = adults + children;
        const maxOccupancy = $('#max_occupancy');
        
        if (parseInt(maxOccupancy.val()) < total) {
            maxOccupancy.val(total);
        }
    });
    
    // Form validation
    $('#createForm').on('submit', function(e) {
        const typeCode = $('#type_code').val();
        const typeName = $('#type_name').val();
        const basePrice = parseFloat($('#base_price').val());
        
        if (!typeCode || !typeName || !basePrice) {
            e.preventDefault();
            alert('Please fill in all required fields');
        }
    });
    
    // Check code availability
    let codeTimeout;
    $('#type_code').on('input', function() {
        clearTimeout(codeTimeout);
        const code = $(this).val();
        
        if (code.length < 2) return;
        
        codeTimeout = setTimeout(function() {
            $.get('/HMSPOS/api/check-room-type-code.php', { code: code }, function(response) {
                const $code = $('#type_code');
                if (response.exists) {
                    $code.addClass('is-invalid');
                    if ($code.next('.invalid-feedback').length === 0) {
                        $code.after('<div class="invalid-feedback">Room type code already exists</div>');
                    }
                } else {
                    $code.removeClass('is-invalid');
                    $code.next('.invalid-feedback').remove();
                }
            }).fail(function() {
                console.error('Failed to check code availability');
            });
        }, 500);
    });
});
</script>

<style>
.me-1 { margin-right: 0.25rem; }
.me-2 { margin-right: 0.5rem; }
.mb-3 { margin-bottom: 1rem; }
.mt-4 { margin-top: 1.5rem; }
.input-group-text { background-color: #e9ecef; }
</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>';
}
?>