<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Edit Guest - 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/guests/guests/edit.php
// Need to go up to: /HMSPOS/
$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/guests/guests/ -> /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';
}
if (file_exists($base_path . '/config/constants.php')) {
    require_once $base_path . '/config/constants.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 helper functions if they don't exist
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) {
        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;
    }
}

if (!function_exists('csrf_field')) {
    function csrf_field() {
        $token = $_SESSION['csrf_token'] ?? bin2hex(random_bytes(32));
        if (!isset($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = $token;
        }
        return '<input type="hidden" name="csrf_token" value="' . $token . '">';
    }
}

if (!function_exists('validate_email')) {
    function validate_email($email) {
        return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
    }
}

if (!function_exists('validate_phone')) {
    function validate_phone($phone) {
        return preg_match('/^[0-9+\-\s()]{7,15}$/', $phone);
    }
}

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,
            'time' => time()
        ];
    }
}

if (!function_exists('redirect')) {
    function redirect($url) {
        if (strpos($url, 'http') === 0) {
            header('Location: ' . $url);
        } else {
            header('Location: /HMSPOS/guests/guests/' . ltrim($url, '/'));
        }
        exit;
    }
}

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

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

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

// Set page title
$page_title = 'Edit Guest';

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

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

if (!$guest_id) {
    set_flash_message('danger', 'Invalid guest ID');
    if (function_exists('redirect')) {
        redirect('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

// Get guest data
$guest = null;
try {
    $guest = db_fetch_one("SELECT * FROM guests WHERE guest_id = ?", [$guest_id]);
} catch (Exception $e) {
    error_log("Error fetching guest: " . $e->getMessage());
}

if (!$guest) {
    set_flash_message('danger', 'Guest not found');
    if (function_exists('redirect')) {
        redirect('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

// Handle form submission
$errors = [];
$form_data = [
    'first_name' => $guest['first_name'] ?? '',
    'last_name' => $guest['last_name'] ?? '',
    'email' => $guest['email'] ?? '',
    'phone' => $guest['phone'] ?? '',
    'phone_country_code' => $guest['phone_country_code'] ?? '',
    'address' => $guest['address'] ?? '',
    'city' => $guest['city'] ?? '',
    'country' => $guest['country'] ?? '',
    'postal_code' => $guest['postal_code'] ?? '',
    'id_type' => $guest['id_type'] ?? '',
    'id_number' => $guest['id_number'] ?? '',
    'id_expiry' => $guest['id_expiry'] ?? '',
    'nationality' => $guest['nationality'] ?? '',
    'date_of_birth' => $guest['date_of_birth'] ?? ''
];

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['first_name'] = $_POST['first_name'] ?? '';
        $form_data['last_name'] = $_POST['last_name'] ?? '';
        $form_data['email'] = $_POST['email'] ?? '';
        $form_data['phone'] = $_POST['phone'] ?? '';
        $form_data['phone_country_code'] = $_POST['phone_country_code'] ?? '';
        $form_data['address'] = $_POST['address'] ?? '';
        $form_data['city'] = $_POST['city'] ?? '';
        $form_data['country'] = $_POST['country'] ?? '';
        $form_data['postal_code'] = $_POST['postal_code'] ?? '';
        $form_data['id_type'] = $_POST['id_type'] ?? '';
        $form_data['id_number'] = $_POST['id_number'] ?? '';
        $form_data['id_expiry'] = $_POST['id_expiry'] ?? '';
        $form_data['nationality'] = $_POST['nationality'] ?? '';
        $form_data['date_of_birth'] = $_POST['date_of_birth'] ?? '';
        
        // Validate required fields
        if (empty($form_data['first_name'])) {
            $errors[] = 'First name is required';
        }
        
        if (empty($form_data['last_name'])) {
            $errors[] = 'Last name is required';
        }
        
        if (!empty($form_data['email']) && !validate_email($form_data['email'])) {
            $errors[] = 'Invalid email format';
        }
        
        if (!empty($form_data['phone']) && !validate_phone($form_data['phone'])) {
            $errors[] = 'Invalid phone number format';
        }
        
        if (!empty($form_data['id_expiry']) && strtotime($form_data['id_expiry']) < time()) {
            $errors[] = 'ID has expired';
        }
        
        // Check email uniqueness
        if (!empty($form_data['email']) && $form_data['email'] != ($guest['email'] ?? '')) {
            try {
                $exists = (int)db_fetch_value("SELECT COUNT(*) FROM guests WHERE email = ? AND guest_id != ?", 
                                             [$form_data['email'], $guest_id]) ?: 0;
                if ($exists > 0) {
                    $errors[] = 'Email address already exists';
                }
            } catch (Exception $e) {
                error_log("Error checking email uniqueness: " . $e->getMessage());
            }
        }
        
        // Update guest
        if (empty($errors)) {
            try {
                if (function_exists('begin_transaction')) {
                    begin_transaction();
                }
                
                $pdo = get_db_connection();
                
                $update_data = [
                    'first_name' => $form_data['first_name'],
                    'last_name' => $form_data['last_name'],
                    'email' => $form_data['email'] ?: null,
                    'phone' => $form_data['phone'] ?: null,
                    'phone_country_code' => $form_data['phone_country_code'] ?: null,
                    'address' => $form_data['address'] ?: null,
                    'city' => $form_data['city'] ?: null,
                    'country' => $form_data['country'] ?: null,
                    'postal_code' => $form_data['postal_code'] ?: null,
                    'id_type' => $form_data['id_type'] ?: null,
                    'id_number' => $form_data['id_number'] ?: null,
                    'id_expiry' => $form_data['id_expiry'] ?: null,
                    'nationality' => $form_data['nationality'] ?: null,
                    'date_of_birth' => $form_data['date_of_birth'] ?: null
                ];
                
                if (function_exists('db_update')) {
                    db_update('guests', $update_data, 'guest_id = ?', [$guest_id]);
                } else {
                    // Build update query dynamically
                    $set_parts = [];
                    $values = [];
                    
                    foreach ($update_data as $field => $value) {
                        $set_parts[] = "$field = ?";
                        $values[] = $value;
                    }
                    
                    $values[] = $guest_id;
                    $sql = "UPDATE guests SET " . implode(', ', $set_parts) . " WHERE guest_id = ?";
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute($values);
                }
                
                // Create activity record (if table exists)
                try {
                    $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
                    if (in_array('guest_activity', $tables)) {
                        $act_sql = "INSERT INTO guest_activity (guest_id, activity_type, description, created_by, created_at) 
                                    VALUES (?, ?, ?, ?, ?)";
                        $act_stmt = $pdo->prepare($act_sql);
                        $act_stmt->execute([
                            $guest_id,
                            'updated',
                            'Guest profile updated',
                            $user_id,
                            date('Y-m-d H:i:s')
                        ]);
                    }
                } catch (Exception $e) {
                    error_log("Error creating activity record: " . $e->getMessage());
                }
                
                // Audit log
                if (function_exists('audit_log')) {
                    audit_log($user_id, 'update', 'guests', $guest_id, $guest, $update_data);
                }
                
                if (function_exists('commit_transaction')) {
                    commit_transaction();
                }
                
                set_flash_message('success', 'Guest updated successfully');
                
                // Redirect
                if (function_exists('redirect')) {
                    redirect('view.php?id=' . $guest_id);
                } else {
                    header('Location: view.php?id=' . $guest_id);
                    exit;
                }
                
            } catch (Exception $e) {
                if (function_exists('rollback_transaction')) {
                    rollback_transaction();
                }
                $errors[] = 'Failed to update guest: ' . $e->getMessage();
                if (function_exists('log_message')) {
                    log_message("Guest update failed: " . $e->getMessage(), 'ERROR');
                } else {
                    error_log("Guest update 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>Edit Guest</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="#">Edit Guest</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">Edit Guest: <?php echo escape_html(($guest['first_name'] ?? '') . ' ' . ($guest['last_name'] ?? '')); ?></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/guests/dashboard.php">Guests</a></li>
                    <li class="breadcrumb-item"><a href="index.php">Guests</a></li>
                    <li class="breadcrumb-item"><a href="view.php?id=<?php echo $guest_id; ?>">View</a></li>
                    <li class="breadcrumb-item active">Edit</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- 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; ?>

        <!-- Edit Form -->
        <div class="card card-warning">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-edit me-1"></i>
                    Edit Guest Information
                </h3>
            </div>
            
            <form method="POST" id="editGuestForm">
                <?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">
                    <!-- Personal Information -->
                    <h5 class="mb-3">Personal Information</h5>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="first_name" class="form-label">First Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="first_name" name="first_name" 
                                       value="<?php echo escape_html($form_data['first_name']); ?>" 
                                       maxlength="50" required>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="last_name" class="form-label">Last Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="last_name" name="last_name" 
                                       value="<?php echo escape_html($form_data['last_name']); ?>" 
                                       maxlength="50" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="date_of_birth" class="form-label">Date of Birth</label>
                                <input type="date" class="form-control" id="date_of_birth" name="date_of_birth" 
                                       value="<?php echo $form_data['date_of_birth']; ?>">
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="nationality" class="form-label">Nationality</label>
                                <input type="text" class="form-control" id="nationality" name="nationality" 
                                       value="<?php echo escape_html($form_data['nationality']); ?>">
                            </div>
                        </div>
                    </div>

                    <!-- Contact Information -->
                    <h5 class="mb-3 mt-4">Contact Information</h5>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="email" class="form-label">Email Address</label>
                                <input type="email" class="form-control" id="email" name="email" 
                                       value="<?php echo escape_html($form_data['email']); ?>" 
                                       maxlength="100">
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="phone" class="form-label">Phone Number</label>
                                <div class="input-group">
                                    <span class="input-group-text">+</span>
                                    <input type="text" class="form-control" id="phone_country_code" name="phone_country_code" 
                                           value="<?php echo escape_html($form_data['phone_country_code']); ?>" 
                                           placeholder="250" style="max-width: 70px;">
                                    <input type="text" class="form-control" id="phone" name="phone" 
                                           value="<?php echo escape_html($form_data['phone']); ?>" 
                                           placeholder="788123456">
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Address Information -->
                    <h5 class="mb-3 mt-4">Address Information</h5>
                    
                    <div class="mb-3">
                        <label for="address" class="form-label">Street Address</label>
                        <input type="text" class="form-control" id="address" name="address" 
                               value="<?php echo escape_html($form_data['address']); ?>">
                    </div>
                    
                    <div class="row">
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="city" class="form-label">City</label>
                                <input type="text" class="form-control" id="city" name="city" 
                                       value="<?php echo escape_html($form_data['city']); ?>">
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="postal_code" class="form-label">Postal Code</label>
                                <input type="text" class="form-control" id="postal_code" name="postal_code" 
                                       value="<?php echo escape_html($form_data['postal_code']); ?>">
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="country" class="form-label">Country</label>
                                <input type="text" class="form-control" id="country" name="country" 
                                       value="<?php echo escape_html($form_data['country']); ?>">
                            </div>
                        </div>
                    </div>

                    <!-- Identification -->
                    <h5 class="mb-3 mt-4">Identification</h5>
                    
                    <div class="row">
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="id_type" class="form-label">ID Type</label>
                                <select class="form-select" id="id_type" name="id_type">
                                    <option value="">Select ID Type</option>
                                    <option value="passport" <?php echo $form_data['id_type'] == 'passport' ? 'selected' : ''; ?>>Passport</option>
                                    <option value="national_id" <?php echo $form_data['id_type'] == 'national_id' ? 'selected' : ''; ?>>National ID</option>
                                    <option value="drivers_license" <?php echo $form_data['id_type'] == 'drivers_license' ? 'selected' : ''; ?>>Driver's License</option>
                                    <option value="other" <?php echo $form_data['id_type'] == 'other' ? 'selected' : ''; ?>>Other</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="id_number" class="form-label">ID Number</label>
                                <input type="text" class="form-control" id="id_number" name="id_number" 
                                       value="<?php echo escape_html($form_data['id_number']); ?>">
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="id_expiry" class="form-label">ID Expiry Date</label>
                                <input type="date" class="form-control" id="id_expiry" name="id_expiry" 
                                       value="<?php echo $form_data['id_expiry']; ?>">
                            </div>
                        </div>
                    </div>

                    <!-- Status Information -->
                    <?php if (!empty($guest['is_blacklisted'])): ?>
                        <div class="alert alert-danger mt-3">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            <strong>Blacklisted Guest</strong> - This guest is on the blacklist.
                            <?php if (function_exists('has_permission') && has_permission('guests.blacklist')): ?>
                                <a href="blacklist.php?action=remove&id=<?php echo $guest_id; ?>" class="btn btn-sm btn-success ms-2">
                                    Remove from Blacklist
                                </a>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>
                
                <div class="card-footer">
                    <button type="submit" class="btn btn-warning">
                        <i class="fas fa-save me-1"></i> Update Guest
                    </button>
                    <a href="view.php?id=<?php echo $guest_id; ?>" class="btn btn-secondary">
                        <i class="fas fa-times me-1"></i> Cancel
                    </a>
                </div>
            </form>
        </div>
    </div>
</section>

<script>
$(document).ready(function() {
    // Email availability check
    let emailTimeout;
    $('#email').on('input', function() {
        clearTimeout(emailTimeout);
        const email = $(this).val();
        const originalEmail = '<?php echo addslashes($guest['email'] ?? ''); ?>';
        
        if (!email || !isValidEmail(email) || email === originalEmail) return;
        
        emailTimeout = setTimeout(function() {
            $.ajax({
                url: '/HMSPOS/api/check-guest-email.php',
                method: 'GET',
                data: { 
                    email: email,
                    exclude: <?php echo $guest_id; ?>
                },
                dataType: 'json',
                success: function(response) {
                    const $email = $('#email');
                    if (response.exists) {
                        $email.addClass('is-invalid');
                        if ($email.next('.invalid-feedback').length === 0) {
                            $email.after('<div class="invalid-feedback">Email already exists</div>');
                        }
                    } else {
                        $email.removeClass('is-invalid');
                        $email.next('.invalid-feedback').remove();
                    }
                },
                error: function() {
                    console.error('Failed to check email availability');
                }
            });
        }, 500);
    });
    
    // Phone validation
    $('#phone').on('input', function() {
        const phone = $(this).val();
        const phoneRegex = /^[0-9]{7,15}$/;
        
        if (phone && !phoneRegex.test(phone)) {
            $(this).addClass('is-invalid');
            if ($(this).next('.invalid-feedback').length === 0) {
                $(this).after('<div class="invalid-feedback">Phone number should contain only digits (7-15 digits)</div>');
            }
        } else {
            $(this).removeClass('is-invalid');
            $(this).next('.invalid-feedback').remove();
        }
    });
    
    // ID expiry validation
    $('#id_expiry').on('change', function() {
        const expiry = new Date($(this).val());
        const today = new Date();
        
        if (expiry < today) {
            $(this).addClass('is-invalid');
            if ($(this).next('.invalid-feedback').length === 0) {
                $(this).after('<div class="invalid-feedback">ID has expired</div>');
            }
        } else {
            $(this).removeClass('is-invalid');
            $(this).next('.invalid-feedback').remove();
        }
    });
    
    function isValidEmail(email) {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    }
});
</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>';
}
?>