<?php
session_start();

// Load database configuration
$config = require __DIR__ . '/../config/database.php';

// Database connection
function getDBConnection() {
    global $config;
    
    $dsn = "mysql:host={$config['host']};dbname={$config['dbname']};charset={$config['charset']}";
    
    try {
        return new PDO($dsn, $config['username'], $config['password'], $config['options']);
    } catch (PDOException $e) {
        error_log('Database connection failed: ' . $e->getMessage());
        die('Connection failed. Please try again later.');
    }
}

// Check if user is logged in
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

// Redirect if not logged in
function requireLogin() {
    if (!isLoggedIn()) {
        header('Location: login.php');
        exit();
    }
}

// User login
function loginUser($phone, $password) {
    $pdo = getDBConnection();
    $stmt = $pdo->prepare("SELECT * FROM users WHERE phone = ?");
    $stmt->execute([$phone]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password_hash'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['phone'] = $user['phone'];
        
        // Update last participation date in user_stats
        $stmt = $pdo->prepare("INSERT INTO user_stats (user_id, last_participation) 
                              VALUES (?, CURDATE()) 
                              ON DUPLICATE KEY UPDATE last_participation = CURDATE()");
        $stmt->execute([$user['id']]);
        
        return true;
    }
    return false;
}

// User registration
function registerUser($phone, $password, $fullName, $ageRange = null, $gender = null, $email = null, $ethnicity = null) {
    $pdo = getDBConnection();
    
    try {
        $pdo->beginTransaction();
        
        // Check if user already exists
        $stmt = $pdo->prepare("SELECT id FROM users WHERE phone = ? OR email = ?");
        $stmt->execute([$phone, $email]);
        if ($stmt->fetch()) {
            $pdo->rollBack();
            return ['success' => false, 'message' => 'Phone number or email already registered'];
        }
        
        // Create new user
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("
            INSERT INTO users 
            (phone, password_hash, full_name, age_range, gender, email, ethnicity, created_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, NOW())"
        );
        
        $stmt->execute([
            $phone, 
            $hashedPassword, 
            $fullName,
            $ageRange, 
            $gender,
            $email,
            $ethnicity
        ]);
        
        $userId = $pdo->lastInsertId();
        
        // Initialize user stats
        $stmt = $pdo->prepare("INSERT INTO user_stats (user_id, points, last_participation) VALUES (?, 0, CURDATE())");
        $stmt->execute([$userId]);
        
        // Set session variables
        $_SESSION['user_id'] = $userId;
        $_SESSION['phone'] = $phone;
        
        $pdo->commit();
        return ['success' => true, 'user_id' => $userId];
        
    } catch (PDOException $e) {
        if (isset($pdo) && $pdo->inTransaction()) {
            $pdo->rollBack();
        }
        error_log('Registration error: ' . $e->getMessage());
        return ['success' => false, 'message' => 'Registration failed. Please try again. Error: ' . $e->getMessage()];
    }
}

// Logout
function logout() {
    session_destroy();
    header('Location: login.php');
    exit();
}
?>
