<?php
// Database Configuration
define('DB_HOST', 'localhost');
define('DB_NAME', 'royalpa1_chatapp');
define('DB_USER', 'root');
define('DB_PASS', '');

// App Configuration
define('APP_NAME', 'QuickRe');
define('APP_URL', 'http://royalpandit.shop/chatapp2');
define('UPLOAD_PATH', __DIR__ . '/../uploads/');
define('MAX_UPLOAD_SIZE', 50 * 1024 * 1024); // 50MB

// Security Configuration
define('CSRF_TOKEN_NAME', 'dekokart_csrf_token');
define('MAX_LOGIN_ATTEMPTS', 5);
define('LOGIN_TIMEOUT', 15 * 60); // 15 minutes

define('OTP_EXPIRY', 10 * 60); // 10 minutes

// Session Configuration
define('SESSION_LIFETIME', 24 * 60 * 60); // 24 hours

// Email Configuration (PHPMailer)
define('SMTP_HOST', 'mail.royalpandit.shop');
define('SMTP_PORT', 465);
define('SMTP_USER', 'no-reply@royalpandit.shop');
define('SMTP_PASS', 'KOSHAL12@');
define('SMTP_FROM', 'no-reply@royalpandit.shop');
define('SMTP_FROM_NAME', 'QuickRe Chat');

// Error Reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Timezone
date_default_timezone_set('UTC');

// Database Connection
function getDB() {
    static $pdo = null;
    if ($pdo === null) {
        try {
            $pdo = new PDO(
                "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
                DB_USER,
                DB_PASS,
                [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false
                ]
            );
        } catch (PDOException $e) {
            die("Database connection failed: " . $e->getMessage());
        }
    }
    return $pdo;
}

// CSRF Token Generation
function generateCSRFToken() {
    if (empty($_SESSION[CSRF_TOKEN_NAME])) {
        $_SESSION[CSRF_TOKEN_NAME] = bin2hex(random_bytes(32));
    }
    return $_SESSION[CSRF_TOKEN_NAME];
}

// CSRF Token Validation
function validateCSRFToken($token) {
    return isset($_SESSION[CSRF_TOKEN_NAME]) && hash_equals($_SESSION[CSRF_TOKEN_NAME], $token);
}

// Input Sanitization
function sanitizeInput($data) {
    return htmlspecialchars(strip_tags(trim($data)), ENT_QUOTES, 'UTF-8');
}

// Rate Limiting
function checkRateLimit($identifier, $type = 'login') {
    $db = getDB();
    $ip = $_SERVER['REMOTE_ADDR'];
    $key = $type . '_' . ($identifier ?: $ip);
    
    $stmt = $db->prepare("SELECT attempts, last_attempt FROM rate_limits WHERE identifier = ?");
    $stmt->execute([$key]);
    $record = $stmt->fetch();
    
    $now = time();
    
    if (!$record) {
        $stmt = $db->prepare("INSERT INTO rate_limits (identifier, attempts, last_attempt) VALUES (?, 1, ?)");
        $stmt->execute([$key, $now]);
        return true;
    }
    
    if ($now - $record['last_attempt'] > LOGIN_TIMEOUT) {
        $stmt = $db->prepare("UPDATE rate_limits SET attempts = 1, last_attempt = ? WHERE identifier = ?");
        $stmt->execute([$now, $key]);
        return true;
    }
    
    if ($record['attempts'] >= MAX_LOGIN_ATTEMPTS) {
        return false;
    }
    
    $stmt = $db->prepare("UPDATE rate_limits SET attempts = attempts + 1, last_attempt = ? WHERE identifier = ?");
    $stmt->execute([$now, $key]);
    return true;
}

// JSON Response
function jsonResponse($success, $message = '', $data = []) {
    header('Content-Type: application/json');
    echo json_encode(['success' => $success, 'message' => $message, 'data' => $data]);
    exit;
}

// Check if user is authenticated
function isAuthenticated() {
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

// Check if admin is authenticated
function isAdmin() {
    return isset($_SESSION['admin_id']) && !empty($_SESSION['admin_id']);
}

// Redirect function
function redirect($url) {
    header("Location: " . $url);
    exit;
}

// Generate Unique ID
function generateUniqueId($length = 8) {
    return substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, $length);
}

// Check session validity
function isSessionValid($userId) {
    $db = getDB();
    $sessionToken = $_SESSION['session_token'] ?? '';
    
    $stmt = $db->prepare("SELECT id, is_valid FROM sessions WHERE user_id = ? AND session_token = ? AND is_valid = 1");
    $stmt->execute([$userId, $sessionToken]);
    
    return $stmt->fetch() !== false;
}

// Format timestamp for display
function formatTime($timestamp) {
    if (!$timestamp) return '';
    $date = new DateTime($timestamp);
    $now = new DateTime();
    $diff = $now->diff($date);
    
    if ($diff->days === 0) {
        return $date->format('g:i A');
    } elseif ($diff->days === 1) {
        return 'Yesterday';
    } elseif ($diff->days < 7) {
        return $date->format('D');
    } else {
        return $date->format('M j');
    }
}

// Format full date time
function formatDateTime($timestamp) {
    if (!$timestamp) return '';
    $date = new DateTime($timestamp);
    return $date->format('M j, Y g:i A');
}
?>
