<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Main Configuration File - FIXED ASSET PATHS
 * Developer: JOACHIM'S INNOTECH
 */

// =============================================
// ERROR REPORTING (Disable in production)
// =============================================
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', dirname(__DIR__) . '/logs/app.log');

// =============================================
// TIMEZONE SETTINGS
// =============================================
date_default_timezone_set('Africa/Kigali');

// =============================================
// SESSION CONFIGURATION
// =============================================
ini_set('session.cookie_httponly', 1);
ini_set('session.use_only_cookies', 1);
ini_set('session.cookie_secure', 0); // Set to 1 if using HTTPS
ini_set('session.cookie_samesite', 'Strict');
ini_set('session.gc_maxlifetime', 7200); // 2 hours
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 100);

// Session name
session_name('ruhondo_hms_session');

// =============================================
// BASE PATH DEFINITION - DEFINE THIS FIRST!
// =============================================
if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(__DIR__));
}

// =============================================
// BASE URL CONFIGURATION
// =============================================
// Auto-detect base URL
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
$dirName = dirname($scriptName);

// Remove /public from path if present
$basePath = str_replace('/public', '', $dirName);
if ($basePath === '/' || $basePath === '\\') {
    $basePath = '';
}

define('BASE_URL', rtrim($protocol . $host . $basePath, '/'));

// =============================================
// ASSET URL CONSTANTS
// =============================================
define('ASSETS_URL', BASE_URL . '/assets');
define('CSS_URL', ASSETS_URL . '/css');
define('JS_URL', ASSETS_URL . '/js');
define('IMG_URL', ASSETS_URL . '/img');

// =============================================
// APPLICATION CONSTANTS
// =============================================
define('APP_NAME', 'Ruhondo Beach Resort HMS');
define('APP_VERSION', '1.0.0');
define('APP_COMPANY', 'JOACHIM\'S INNOTECH');

// =============================================
// DATABASE CONFIGURATION
// =============================================
define('DB_HOST', 'localhost');
define('DB_NAME', 'ruhondo_hms'); // Make sure this database exists!
define('DB_USER', 'root'); // XAMPP default
define('DB_PASS', ''); // XAMPP default (empty password)
define('DB_CHARSET', 'utf8mb4');

// =============================================
// FILE UPLOAD CONFIGURATION
// =============================================
define('UPLOAD_MAX_SIZE', 5 * 1024 * 1024); // 5MB
define('UPLOAD_ALLOWED_EXTENSIONS', 'jpg,jpeg,png,gif,pdf,doc,docx');
define('UPLOAD_ALLOWED_MIMES', 'image/jpeg,image/png,image/gif,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document');

// Upload directories
define('UPLOAD_PATH', BASE_PATH . '/uploads/');
define('UPLOAD_PATH_IDS', UPLOAD_PATH . 'ids/');
define('UPLOAD_PATH_ROOM_IMAGES', UPLOAD_PATH . 'room_images/');
define('UPLOAD_PATH_PRODUCT_IMAGES', UPLOAD_PATH . 'product_images/');
define('UPLOAD_PATH_INVOICES', UPLOAD_PATH . 'invoices/');

// Upload URLs
define('UPLOAD_URL', BASE_URL . '/uploads');
define('UPLOAD_URL_IDS', UPLOAD_URL . '/ids');
define('UPLOAD_URL_ROOM_IMAGES', UPLOAD_URL . '/room_images');
define('UPLOAD_URL_PRODUCT_IMAGES', UPLOAD_URL . '/product_images');
define('UPLOAD_URL_INVOICES', UPLOAD_URL . '/invoices');

// =============================================
// EMAIL CONFIGURATION (SMTP)
// =============================================
define('SMTP_HOST', 'smtp.gmail.com'); // Change in production
define('SMTP_PORT', 587);
define('SMTP_USER', 'joachimdjihad2017@gmail.com'); // Change in production
define('SMTP_PASS', 'Njoachim2022@@'); // Change in production
define('SMTP_ENCRYPTION', 'tls');
define('SMTP_FROM_EMAIL', 'noreply@ruhondo.com');
define('SMTP_FROM_NAME', 'Ruhondo Beach Resort');

// =============================================
// PAGINATION SETTINGS
// =============================================
define('ITEMS_PER_PAGE', 25);
define('MAX_PAGINATION_LINKS', 10);

// =============================================
// DATE/TIME FORMATS
// =============================================
define('DATE_FORMAT', 'Y-m-d');
define('DATETIME_FORMAT', 'Y-m-d H:i:s');
define('DISPLAY_DATE_FORMAT', 'M d, Y');
define('DISPLAY_DATETIME_FORMAT', 'M d, Y H:i');
define('DISPLAY_TIME_FORMAT', 'H:i');

// =============================================
// CURRENCY SETTINGS
// =============================================
define('DEFAULT_CURRENCY', 'RWF');
define('CURRENCY_SYMBOL', 'FRw');
define('DECIMAL_PLACES', 0);
define('THOUSAND_SEPARATOR', ',');
define('DECIMAL_SEPARATOR', '.');

// =============================================
// SECURITY SETTINGS
// =============================================
define('BCRYPT_COST', 12);
define('CSRF_TOKEN_NAME', 'csrf_token');
define('CSRF_TOKEN_LENGTH', 32);
define('PASSWORD_RESET_EXPIRY', 3600); // 1 hour
define('MAX_LOGIN_ATTEMPTS', 5);
define('LOGIN_LOCKOUT_TIME', 900); // 15 minutes
define('SESSION_TIMEOUT', 7200); // 2 hours

// =============================================
// SYSTEM PATHS
// =============================================
define('CONFIG_PATH', BASE_PATH . '/config/');
define('PUBLIC_PATH', BASE_PATH . '/public/');
define('VIEWS_PATH', BASE_PATH . '/views/');
define('PARTIALS_PATH', VIEWS_PATH . '/partials/');
define('ASSETS_PATH', BASE_PATH . '/assets/');
define('LOGS_PATH', BASE_PATH . '/logs/');

// =============================================
// LOGGING SETTINGS
// =============================================
define('LOG_APP', LOGS_PATH . 'app.log');
define('LOG_AUDIT', LOGS_PATH . 'audit.log');
define('LOG_LEVEL', 'DEBUG'); // DEBUG, INFO, WARNING, ERROR

// =============================================
// FEATURE TOGGLES
// =============================================
define('ENABLE_EMAIL', true);
define('ENABLE_SMS', false);
define('ENABLE_AUDIT_LOG', true);
define('ENABLE_RATE_LIMITING', true);
define('MAINTENANCE_MODE', false);

// =============================================
// MAINTENANCE MODE CHECK
// =============================================
if (MAINTENANCE_MODE) {
    // Allow access from specific IPs
    $allowed_ips = ['127.0.0.1', '::1'];
    $current_ip = $_SERVER['REMOTE_ADDR'] ?? '';
    
    if (!in_array($current_ip, $allowed_ips)) {
        http_response_code(503);
        die(file_get_contents(PUBLIC_PATH . 'maintenance.html'));
    }
}

// =============================================
// SESSION START
// =============================================
// Only start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// =============================================
// CUSTOM FUNCTIONS
// =============================================

/**
 * Get base URL with optional path
 */
if (!function_exists('base_url')) {
    function base_url($path = '') {
        $base = defined('BASE_URL') ? BASE_URL : '';
        $path = ltrim($path, '/');
        return $path ? $base . '/' . $path : $base;
    }
}

/**
 * Get assets URL - FIXED VERSION
 */
if (!function_exists('assets_url')) {
    function assets_url($path = '') {
        $base = defined('ASSETS_URL') ? ASSETS_URL : (defined('BASE_URL') ? BASE_URL . '/assets' : '/HMSPOS/assets');
        $path = ltrim($path, '/');
        return $path ? $base . '/' . $path : $base;
    }
}

/**
 * Get CSS file URL
 */
if (!function_exists('css_url')) {
    function css_url($file = '') {
        return assets_url('css/' . ltrim($file, '/'));
    }
}

/**
 * Get JavaScript file URL
 */
if (!function_exists('js_url')) {
    function js_url($file = '') {
        return assets_url('js/' . ltrim($file, '/'));
    }
}

/**
 * Get image URL
 */
if (!function_exists('img_url')) {
    function img_url($file = '') {
        return assets_url('img/' . ltrim($file, '/'));
    }
}

/**
 * Get uploads URL
 */
if (!function_exists('uploads_url')) {
    function uploads_url($path = '') {
        $base = defined('UPLOAD_URL') ? UPLOAD_URL : (defined('BASE_URL') ? BASE_URL . '/uploads' : '/HMSPOS/uploads');
        $path = ltrim($path, '/');
        return $path ? $base . '/' . $path : $base;
    }
}

/**
 * Redirect to URL
 */
if (!function_exists('redirect')) {
    function redirect($url) {
        if (function_exists('base_url')) {
            header('Location: ' . base_url($url));
        } else {
            header('Location: ' . $url);
        }
        exit;
    }
}

/**
 * Check if request is AJAX
 */
if (!function_exists('is_ajax_request')) {
    function is_ajax_request() {
        return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
               strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
    }
}

/**
 * Get current URL
 */
if (!function_exists('current_url')) {
    function current_url() {
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
        return $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    }
}

/**
 * Generate random string
 */
if (!function_exists('generate_random_string')) {
    function generate_random_string($length = 32) {
        return bin2hex(random_bytes($length / 2));
    }
}

/**
 * Format currency
 */
if (!function_exists('format_currency')) {
    function format_currency($amount, $currency = DEFAULT_CURRENCY) {
        $symbol = $currency === 'USD' ? '$' : 
                  ($currency === 'EUR' ? '€' : 
                  ($currency === 'GBP' ? '£' : CURRENCY_SYMBOL));
        
        $formatted = number_format(
            $amount, 
            DECIMAL_PLACES, 
            DECIMAL_SEPARATOR, 
            THOUSAND_SEPARATOR
        );
        
        return $symbol . ' ' . $formatted;
    }
}

/**
 * Format number
 */
if (!function_exists('format_number')) {
    function format_number($number, $decimals = 0) {
        return number_format($number, $decimals, '.', ',');
    }
}

/**
 * Format date
 */
if (!function_exists('format_date')) {
    function format_date($date, $format = DISPLAY_DATE_FORMAT) {
        if (empty($date)) return '';
        $timestamp = is_numeric($date) ? $date : strtotime($date);
        return date($format, $timestamp);
    }
}

/**
 * Format datetime
 */
if (!function_exists('format_datetime')) {
    function format_datetime($datetime, $format = DISPLAY_DATETIME_FORMAT) {
        if (empty($datetime)) return '';
        $timestamp = is_numeric($datetime) ? $datetime : strtotime($datetime);
        return date($format, $timestamp);
    }
}

/**
 * Time ago function
 */
if (!function_exists('time_ago')) {
    function time_ago($datetime) {
        $time = strtotime($datetime);
        $now = time();
        $diff = $now - $time;
        
        if ($diff < 60) {
            return $diff . ' seconds ago';
        } elseif ($diff < 3600) {
            $mins = floor($diff / 60);
            return $mins . ' minute' . ($mins > 1 ? 's' : '') . ' ago';
        } elseif ($diff < 86400) {
            $hours = floor($diff / 3600);
            return $hours . ' hour' . ($hours > 1 ? 's' : '') . ' ago';
        } elseif ($diff < 2592000) {
            $days = floor($diff / 86400);
            return $days . ' day' . ($days > 1 ? 's' : '') . ' ago';
        } else {
            return date('M d, Y', $time);
        }
    }
}

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

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

/**
 * Truncate text
 */
if (!function_exists('truncate_text')) {
    function truncate_text($text, $length = 100, $suffix = '...') {
        if (strlen($text) <= $length) {
            return $text;
        }
        return substr($text, 0, $length) . $suffix;
    }
}

/**
 * Get user IP address
 */
if (!function_exists('get_client_ip')) {
    function get_client_ip() {
        $ipaddress = '';
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
        } elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
        } elseif (isset($_SERVER['HTTP_FORWARDED'])) {
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ipaddress = $_SERVER['REMOTE_ADDR'];
        } else {
            $ipaddress = 'UNKNOWN';
        }
        return $ipaddress;
    }
}

/**
 * Log message to file
 */
if (!function_exists('log_message')) {
    function log_message($message, $level = 'INFO', $file = LOG_APP) {
        $timestamp = date(DATETIME_FORMAT);
        $log_entry = "[$timestamp] [$level] $message" . PHP_EOL;
        file_put_contents($file, $log_entry, FILE_APPEND | LOCK_EX);
    }
}

// =============================================
// DATABASE CONNECTION TEST (Optional - can be commented out in production)
// =============================================
// This will test if the database connection works when config loads
if (!defined('SKIP_DB_TEST')) {
    try {
        $test_dsn = "mysql:host=" . DB_HOST . ";charset=" . DB_CHARSET;
        $test_pdo = new PDO($test_dsn, DB_USER, DB_PASS);
        $test_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        // Check if database exists
        $stmt = $test_pdo->query("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '" . DB_NAME . "'");
        $db_exists = $stmt->fetch();
        
        if (!$db_exists) {
            // Database doesn't exist - create it
            $test_pdo->exec("CREATE DATABASE IF NOT EXISTS `" . DB_NAME . "` CHARACTER SET " . DB_CHARSET);
            error_log("Database '" . DB_NAME . "' created successfully");
        }
        
    } catch (PDOException $e) {
        error_log("Database connection test failed: " . $e->getMessage());
        // Don't halt execution, just log the error
    }
}

// =============================================
// INITIAL SETTINGS CHECK
// =============================================
// Create upload directories if they don't exist (only once)
if (!defined('DIRECTORIES_CREATED')) {
    $upload_dirs = [
        UPLOAD_PATH,
        UPLOAD_PATH_IDS,
        UPLOAD_PATH_ROOM_IMAGES,
        UPLOAD_PATH_PRODUCT_IMAGES,
        UPLOAD_PATH_INVOICES
    ];

    foreach ($upload_dirs as $dir) {
        if (!file_exists($dir)) {
            @mkdir($dir, 0755, true);
        }
    }

    // Create logs directory if it doesn't exist
    if (!file_exists(LOGS_PATH)) {
        @mkdir(LOGS_PATH, 0755, true);
    }

    // Create assets directories if they don't exist
    $asset_dirs = [
        ASSETS_PATH,
        ASSETS_PATH . 'css/',
        ASSETS_PATH . 'js/',
        ASSETS_PATH . 'img/'
    ];

    foreach ($asset_dirs as $dir) {
        if (!file_exists($dir)) {
            @mkdir($dir, 0755, true);
        }
    }

    // Create .htaccess files in upload directories to prevent PHP execution
    $htaccess_content = "Options -Indexes\n<FilesMatch \"\\.php$\">\nOrder Deny,Allow\nDeny from all\n</FilesMatch>";
    foreach ($upload_dirs as $dir) {
        if (!file_exists($dir . '.htaccess')) {
            @file_put_contents($dir . '.htaccess', $htaccess_content);
        }
    }
    
    define('DIRECTORIES_CREATED', true);
}