<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Resort Settings
 * Developer: JOACHIM'S INNOTECH
 */

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

// Require authentication and permission
require_auth();
require_permission('settings.edit');

// Set page title
$page_title = 'Resort Settings';

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

// Get current resort settings
$resort = db_fetch_one("SELECT * FROM resort_settings LIMIT 1");

// If no settings exist, create default
if (!$resort) {
    $resort_id = db_insert('resort_settings', [
        'resort_name' => 'Ruhondo Beach Resort',
        'checkin_time' => DEFAULT_CHECKIN_TIME,
        'checkout_time' => DEFAULT_CHECKOUT_TIME,
        'default_currency' => DEFAULT_CURRENCY,
        'timezone' => DEFAULT_TIMEZONE,
        'date_format' => DATE_FORMAT
    ]);
    $resort = db_fetch_one("SELECT * FROM resort_settings WHERE setting_id = ?", [$resort_id]);
}

// Get all timezones
$timezones = DateTimeZone::listIdentifiers();

// Handle form submission
$errors = [];
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    if (!verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '')) {
        $errors[] = 'Invalid security token. Please try again.';
    } else {
        // Get and validate input
        $resort_name = sanitize_input($_POST['resort_name'] ?? '');
        $resort_address = sanitize_input($_POST['resort_address'] ?? '');
        $resort_city = sanitize_input($_POST['resort_city'] ?? '');
        $resort_state = sanitize_input($_POST['resort_state'] ?? '');
        $resort_postal_code = sanitize_input($_POST['resort_postal_code'] ?? '');
        $resort_country = sanitize_input($_POST['resort_country'] ?? '');
        $resort_phone = sanitize_input($_POST['resort_phone'] ?? '');
        $resort_email = sanitize_input($_POST['resort_email'] ?? '');
        $resort_website = sanitize_input($_POST['resort_website'] ?? '');
        $checkin_time = sanitize_input($_POST['checkin_time'] ?? DEFAULT_CHECKIN_TIME);
        $checkout_time = sanitize_input($_POST['checkout_time'] ?? DEFAULT_CHECKOUT_TIME);
        $default_currency = sanitize_input($_POST['default_currency'] ?? DEFAULT_CURRENCY);
        $timezone = sanitize_input($_POST['timezone'] ?? DEFAULT_TIMEZONE);
        $date_format = sanitize_input($_POST['date_format'] ?? DATE_FORMAT);
        
        // Validate required fields
        if (empty($resort_name)) {
            $errors[] = 'Resort name is required';
        }
        
        if (!empty($resort_email) && !validate_email($resort_email)) {
            $errors[] = 'Invalid email format';
        }
        
        if (!empty($resort_website) && !validate_url($resort_website)) {
            $errors[] = 'Invalid website URL';
        }
        
        if (!empty($resort_phone) && !validate_phone($resort_phone)) {
            $errors[] = 'Invalid phone number format';
        }
        
        // Handle logo upload
        $logo_filename = $resort['resort_logo'] ?? null;
        
        if (isset($_FILES['resort_logo']) && $_FILES['resort_logo']['error'] === UPLOAD_ERR_OK) {
            $upload_result = upload_file(
                $_FILES['resort_logo'],
                UPLOAD_PATH,
                ['jpg', 'jpeg', 'png', 'gif', 'svg']
            );
            
            if ($upload_result['success']) {
                // Delete old logo if exists
                if ($logo_filename) {
                    delete_file(UPLOAD_PATH . $logo_filename);
                }
                $logo_filename = $upload_result['filename'];
            } else {
                $errors = array_merge($errors, $upload_result['errors']);
            }
        }
        
        // Update settings
        if (empty($errors)) {
            try {
                $update_data = [
                    'resort_name' => $resort_name,
                    'resort_address' => $resort_address ?: null,
                    'resort_city' => $resort_city ?: null,
                    'resort_state' => $resort_state ?: null,
                    'resort_postal_code' => $resort_postal_code ?: null,
                    'resort_country' => $resort_country ?: null,
                    'resort_phone' => $resort_phone ?: null,
                    'resort_email' => $resort_email ?: null,
                    'resort_website' => $resort_website ?: null,
                    'checkin_time' => $checkin_time,
                    'checkout_time' => $checkout_time,
                    'default_currency' => $default_currency,
                    'timezone' => $timezone,
                    'date_format' => $date_format
                ];
                
                if ($logo_filename) {
                    $update_data['resort_logo'] = $logo_filename;
                }
                
                db_update('resort_settings', $update_data, 'setting_id = ?', [$resort['setting_id']]);
                
                // Update timezone if changed
                if ($timezone != $resort['timezone']) {
                    date_default_timezone_set($timezone);
                }
                
                audit_log($current_user['user_id'], AUDIT_UPDATE, 'resort_settings', $resort['setting_id'], $resort, $update_data);
                
                $message = 'Resort settings updated successfully';
                
                // Refresh resort data
                $resort = db_fetch_one("SELECT * FROM resort_settings WHERE setting_id = ?", [$resort['setting_id']]);
                
            } catch (Exception $e) {
                $errors[] = 'Failed to update settings: ' . $e->getMessage();
                log_message("Resort settings update failed: " . $e->getMessage(), 'ERROR');
            }
        }
    }
}

// Include header
require_once dirname(__DIR__, 2) . '/views/partials/header.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">Resort Settings</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?php echo base_url('dashboard.php'); ?>">Home</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('admin/dashboard.php'); ?>">Admin</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('admin/settings/index.php'); ?>">Settings</a></li>
                    <li class="breadcrumb-item active">Resort</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <!-- Messages -->
                <?php if ($message): ?>
                    <div class="alert alert-success alert-dismissible fade show">
                        <i class="fas fa-check-circle mr-2"></i>
                        <?php echo $message; ?>
                        <button type="button" class="close" data-dismiss="alert">&times;</button>
                    </div>
                <?php endif; ?>
                
                <?php if (!empty($errors)): ?>
                    <div class="alert alert-danger alert-dismissible fade show">
                        <i class="fas fa-exclamation-circle mr-2"></i>
                        <strong>Please fix the following errors:</strong>
                        <ul class="mt-2 mb-0">
                            <?php foreach ($errors as $error): ?>
                                <li><?php echo $error; ?></li>
                            <?php endforeach; ?>
                        </ul>
                        <button type="button" class="close" data-dismiss="alert">&times;</button>
                    </div>
                <?php endif; ?>

                <!-- Settings Form -->
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-hotel mr-1"></i>
                            Resort Information
                        </h3>
                    </div>
                    
                    <form method="POST" enctype="multipart/form-data">
                        <?php echo csrf_field(); ?>
                        
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <!-- Basic Information -->
                                    <h5 class="mb-3">Basic Information</h5>
                                    
                                    <div class="form-group">
                                        <label for="resort_name">Resort Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="resort_name" name="resort_name" 
                                               value="<?php echo escape_html($resort['resort_name']); ?>" required>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="resort_address">Address</label>
                                        <textarea class="form-control" id="resort_address" name="resort_address" rows="2"><?php echo escape_html($resort['resort_address']); ?></textarea>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="resort_city">City</label>
                                                <input type="text" class="form-control" id="resort_city" name="resort_city" 
                                                       value="<?php echo escape_html($resort['resort_city']); ?>">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="resort_state">State/Province</label>
                                                <input type="text" class="form-control" id="resort_state" name="resort_state" 
                                                       value="<?php echo escape_html($resort['resort_state']); ?>">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="resort_postal_code">Postal Code</label>
                                                <input type="text" class="form-control" id="resort_postal_code" name="resort_postal_code" 
                                                       value="<?php echo escape_html($resort['resort_postal_code']); ?>">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="resort_country">Country</label>
                                                <input type="text" class="form-control" id="resort_country" name="resort_country" 
                                                       value="<?php echo escape_html($resort['resort_country']); ?>">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="resort_phone">Phone Number</label>
                                        <input type="tel" class="form-control" id="resort_phone" name="resort_phone" 
                                               value="<?php echo escape_html($resort['resort_phone']); ?>" 
                                               placeholder="+250788123456">
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="resort_email">Email Address</label>
                                        <input type="email" class="form-control" id="resort_email" name="resort_email" 
                                               value="<?php echo escape_html($resort['resort_email']); ?>">
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="resort_website">Website</label>
                                        <input type="url" class="form-control" id="resort_website" name="resort_website" 
                                               value="<?php echo escape_html($resort['resort_website']); ?>" 
                                               placeholder="https://www.ruhondo.com">
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <!-- Operations Settings -->
                                    <h5 class="mb-3">Operations Settings</h5>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="checkin_time">Check-in Time</label>
                                                <input type="time" class="form-control" id="checkin_time" name="checkin_time" 
                                                       value="<?php echo substr($resort['checkin_time'] ?? DEFAULT_CHECKIN_TIME, 0, 5); ?>">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="checkout_time">Check-out Time</label>
                                                <input type="time" class="form-control" id="checkout_time" name="checkout_time" 
                                                       value="<?php echo substr($resort['checkout_time'] ?? DEFAULT_CHECKOUT_TIME, 0, 5); ?>">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="default_currency">Default Currency</label>
                                        <select class="form-control select2" id="default_currency" name="default_currency">
                                            <?php
                                            $currencies = db_fetch_all("SELECT currency_code, currency_name FROM currency_rates WHERE is_active = 1 ORDER BY is_base_currency DESC, currency_code");
                                            foreach ($currencies as $currency):
                                            ?>
                                                <option value="<?php echo $currency['currency_code']; ?>" 
                                                        <?php echo ($resort['default_currency'] ?? DEFAULT_CURRENCY) == $currency['currency_code'] ? 'selected' : ''; ?>>
                                                    <?php echo $currency['currency_code'] . ' - ' . $currency['currency_name']; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="timezone">Timezone</label>
                                        <select class="form-control select2" id="timezone" name="timezone">
                                            <?php foreach ($timezones as $tz): ?>
                                                <option value="<?php echo $tz; ?>" 
                                                        <?php echo ($resort['timezone'] ?? DEFAULT_TIMEZONE) == $tz ? 'selected' : ''; ?>>
                                                    <?php echo str_replace('_', ' ', $tz); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="date_format">Date Format</label>
                                        <select class="form-control" id="date_format" name="date_format">
                                            <option value="Y-m-d" <?php echo ($resort['date_format'] ?? 'Y-m-d') == 'Y-m-d' ? 'selected' : ''; ?>>YYYY-MM-DD (2024-12-31)</option>
                                            <option value="d-m-Y" <?php echo ($resort['date_format'] ?? 'Y-m-d') == 'd-m-Y' ? 'selected' : ''; ?>>DD-MM-YYYY (31-12-2024)</option>
                                            <option value="m/d/Y" <?php echo ($resort['date_format'] ?? 'Y-m-d') == 'm/d/Y' ? 'selected' : ''; ?>>MM/DD/YYYY (12/31/2024)</option>
                                            <option value="d/m/Y" <?php echo ($resort['date_format'] ?? 'Y-m-d') == 'd/m/Y' ? 'selected' : ''; ?>>DD/MM/YYYY (31/12/2024)</option>
                                        </select>
                                    </div>
                                    
                                    <!-- Logo Upload -->
                                    <h5 class="mb-3 mt-4">Resort Logo</h5>
                                    
                                    <div class="form-group">
                                        <div class="text-center mb-3">
                                            <?php if (!empty($resort['resort_logo'])): ?>
                                                <img src="<?php echo uploads_url($resort['resort_logo']); ?>" 
                                                     alt="Resort Logo" class="img-fluid" style="max-height: 100px;">
                                            <?php else: ?>
                                                <div class="bg-light p-3 text-center">
                                                    <i class="fas fa-image fa-3x text-muted"></i>
                                                    <p class="mb-0">No logo uploaded</p>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <div class="custom-file">
                                            <input type="file" class="custom-file-input" id="resort_logo" name="resort_logo" 
                                                   accept="image/*">
                                            <label class="custom-file-label" for="resort_logo">Choose new logo</label>
                                        </div>
                                        <small class="text-muted">Allowed: JPG, PNG, GIF, SVG. Max size: <?php echo format_bytes(UPLOAD_MAX_SIZE); ?></small>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save mr-1"></i> Save Changes
                            </button>
                            <a href="<?php echo base_url('admin/settings/index.php'); ?>" class="btn btn-secondary">
                                <i class="fas fa-times mr-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
$(document).ready(function() {
    // Custom file input
    $('.custom-file-input').on('change', function() {
        let fileName = $(this).val().split('\\').pop();
        $(this).next('.custom-file-label').addClass("selected").html(fileName);
    });
    
    // Initialize select2
    $('.select2').select2({
        theme: 'bootstrap-5',
        width: '100%'
    });
});
</script>

<?php
// Include footer
require_once dirname(__DIR__, 2) . '/views/partials/footer.php';
?>