<?php
ob_start();
require_once __DIR__ . '/../config/config.php';
if (session_status() == PHP_SESSION_NONE && !headers_sent()) {
    session_start();
}
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/functions.php';

class Auth {
    private $db;
    private $functions;
    
    public function __construct() {
        $this->functions = new InvestmentFunctions();
        $this->db = Database::getInstance()->getConnection();
    }
    
    // User Registration
    public function register($data) {
        $username = $this->functions->sanitize($data['username']);
        $email = $this->functions->sanitize($data['email']);
        $password = $data['password'];
        $confirm_password = $data['confirm_password'];
        $referral_code = isset($data['referral_code']) ? $this->functions->sanitize($data['referral_code']) : null;
        
        // Validation
        if (empty($username) || empty($email) || empty($password)) {
            return ['success' => false, 'message' => 'All fields are required'];
        }
        
        if (!$this->functions->validateEmail($email)) {
            return ['success' => false, 'message' => 'Invalid email address'];
        }
        
        if (strlen($password) < 6) {
            return ['success' => false, 'message' => 'Password must be at least 6 characters'];
        }
        
        if ($password !== $confirm_password) {
            return ['success' => false, 'message' => 'Passwords do not match'];
        }
        
        if (strlen($password) < 6) {
            return ['success' => false, 'message' => 'Password must be at least 6 characters'];
        }
        $check = $this->db->prepare("SELECT id FROM users WHERE email = ? OR username = ?");
        $check->execute([$email, $username]);
        
        if ($check->rowCount() > 0) {
            return ['success' => false, 'message' => 'Username or email already exists'];
        }
        
        // Generate referral code
        $user_referral = strtoupper(substr(md5(time().$username), 0, 8));
        
        // Hash password
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        
        try {
            $this->db->beginTransaction();
            
            // Insert user
            $stmt = $this->db->prepare("INSERT INTO users (username, email, password, referral_code, referred_by, account_status) 
                                       VALUES (?, ?, ?, ?, ?, 'active')");
            $stmt->execute([$username, $email, $hashed_password, $user_referral, $referral_code]);
            
            $user_id = $this->db->lastInsertId();
            
            // If referred, add bonus to referrer
            if ($referral_code) {
                $stmt = $this->db->prepare("SELECT id FROM users WHERE referral_code = ?");
                $stmt->execute([$referral_code]);
                if ($stmt->rowCount() == 1) {
                    $referrer = $stmt->fetch();
                    $functions->addReferralBonus($referrer['id'], $user_id);
                }
            }
            
            $this->db->commit();
            
            // Auto login after registration
            $this->login(['email' => $email, 'password' => $password]);
            
            return ['success' => true, 'message' => 'Registration successful!', 'user_id' => $user_id];
            
        } catch(PDOException $e) {
            $this->db->rollBack();
            error_log("Registration error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Registration failed. Please try again.'];
        }
    }
    
    // User Login
    public function login($data) {
        $email = $this->functions->sanitize($data['email']);
        $password = $data['password'];
        
        if (empty($email) || empty($password)) {
            return ['success' => false, 'message' => 'Email and password are required'];
        }
        
        if (empty($email) || empty($password)) {
            return ['success' => false, 'message' => 'Email and password are required'];
        }
        
        $stmt = $this->db->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$email]);
        
        if ($stmt->rowCount() == 1) {
            $user = $stmt->fetch();
            
            if (password_verify($password, $user['password'])) {
                if ($user['account_status'] != 'active') {
                    return ['success' => false, 'message' => 'Your account is ' . $user['account_status']];
                }
                
                // Update last login
                $update = $this->db->prepare("UPDATE users SET last_login = NOW() WHERE id = ?");
                $update->execute([$user['id']]);
                
                // Set session
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['email'] = $user['email'];
                $_SESSION['user_role'] = 'user';
                $_SESSION['logged_in'] = true;
                
                return ['success' => true, 'message' => 'Login successful'];
            }
        }
        
        // Record failed login
        return ['success' => false, 'message' => 'Invalid email or password'];
    }
    
    // Admin Login
    public function adminLogin($data) {
        $username = $this->functions->sanitize($data['username']);
        $password = $data['password'];
        
        $stmt = $this->db->prepare("SELECT * FROM admin_users WHERE username = ?");
        $stmt->execute([$username]);
        
        if ($stmt->rowCount() == 1) {
            $admin = $stmt->fetch();
            
            if (password_verify($password, $admin['password'])) {
                // Update last login
                $update = $this->db->prepare("UPDATE admin_users SET last_login = NOW() WHERE id = ?");
                $update->execute([$admin['id']]);
                
                // Set session
                $_SESSION['admin_id'] = $admin['id'];
                $_SESSION['admin_username'] = $admin['username'];
                $_SESSION['admin_role'] = $admin['role'];
                $_SESSION['user_role'] = 'admin';
                $_SESSION['logged_in'] = true;
                
                return ['success' => true, 'message' => 'Admin login successful'];
            }
        }
        return ['success' => false, 'message' => 'Invalid credentials'];
    }
    
    // Check if user is logged in
    public function isLoggedIn() {
        return isset($_SESSION['user_id']) && $_SESSION['logged_in'] === true;
    }
    
    // Check if admin is logged in
    public function isAdminLoggedIn() {
        return isset($_SESSION['admin_id']) && $_SESSION['logged_in'] === true;
    }
    
    // Get current user ID
    public function getCurrentUserId() {
        return $_SESSION['user_id'] ?? null;
    }
    
    // Get current user data
    public function getCurrentUser() {
        if (!$this->isLoggedIn()) return null;
        
        $stmt = $this->db->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$this->getCurrentUserId()]);
        return $stmt->fetch();
    }
    
    // Logout
    public function logout() {
        session_destroy();
        header("Location: ../index.php");
        exit();
    }
}

$auth = new Auth();