<?php
ob_start();
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/constants.php';
if (session_status() == PHP_SESSION_NONE && !headers_sent()) {
    session_start();
}
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/../vendor/phpmailer/phpmailer/src/PHPMailer.php';
require_once __DIR__ . '/../vendor/phpmailer/phpmailer/src/SMTP.php';
require_once __DIR__ . '/../vendor/phpmailer/phpmailer/src/Exception.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

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['password2'];
        $referral_code = isset($data['ref']) ? $this->functions->sanitize($data['ref']) : 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'];
        }
        
        $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));

        // Lookup referrer id (store an integer id for the foreign key)
        $referred_by_id = null;
        if (!empty($referral_code)) {
            $refStmt = $this->db->prepare("SELECT id FROM users WHERE referral_code = ?");
            $refStmt->execute([$referral_code]);
            if ($refStmt->rowCount() === 1) {
                $refRow = $refStmt->fetch();
                $referred_by_id = (int) $refRow['id'];
            } else {
                // invalid referral code, ignore it
                $referred_by_id = null;
            }
        }

        // Generate verification token
        $verification_token = bin2hex(random_bytes(32));
        $token_expiry = date('Y-m-d H:i:s', strtotime('+24 hours'));
        
        // Hash password
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        
        try {
            $this->db->beginTransaction();
            
            // Insert user (use numeric referred_by id or NULL)
            $stmt = $this->db->prepare("INSERT INTO users (username, email, password, referral_code, referred_by, account_status, email_verification_token, email_verification_expiry) 
                                       VALUES (?, ?, ?, ?, ?, 'active', ?, ?)");
            $stmt->execute([$username, $email, $hashed_password, $user_referral, $referred_by_id, $verification_token, $token_expiry]);

            $user_id = $this->db->lastInsertId();

            // If referred and referrer id exists, add bonus to referrer
            if (!is_null($referred_by_id)) {
                $this->functions->addReferralBonus($referred_by_id, $user_id);
            }
            
            $this->db->commit();
            
            // Send Verification Email
            $this->sendVerificationEmail($email, $username, $verification_token);
            
            // 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());
            $message = 'Registration failed. Please try again.';
            if (ENVIRONMENT === 'development' || (defined('SHOW_DEBUG_ERRORS') && SHOW_DEBUG_ERRORS)) {
                $message .= ' Details: ' . $e->getMessage();
            }
            return ['success' => false, 'message' => $message];
        }
    }
    
    // Helper to send verification email
    private function sendVerificationEmail($email, $username, $token) {
        $verification_link = SITE_URL . "/user/verify-email.php?token=" . $token;
        $subject = "Verify Your Email - " . SITE_NAME;
        $message = "
        <html>
        <head><title>Verify Your Email</title></head>
        <body>
            <h2>Welcome to " . SITE_NAME . "</h2>
            <p>Hi " . htmlspecialchars($username) . ",</p>
            <p>Thank you for registering! Please verify your email address to complete your account setup.</p>
            <p><a href='" . $verification_link . "' style='background-color: #667eea; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>Verify Email</a></p>
            <p>Or copy this link: " . $verification_link . "</p>
            <p>Best regards,<br>" . SITE_NAME . " Team</p>
        </body>
        </html>";

        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host = SMTP_HOST;
            $mail->SMTPAuth = true;
            $mail->Username = SMTP_USERNAME;
            $mail->Password = SMTP_PASSWORD;
            $mail->SMTPSecure = SMTP_ENCRYPTION;
            $mail->Port = SMTP_PORT;
            $mail->setFrom(SITE_EMAIL, SITE_NAME);
            $mail->addAddress($email);
            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body = $message;
            $mail->send();
            return true;
        } catch (Exception $e) {
            error_log("Mail Error: " . $mail->ErrorInfo);
            return false;
        }
    }
    
    // Verify reCAPTCHA
    private function verifyRecaptcha($response) {
        $url = 'https://www.google.com/recaptcha/api/siteverify';
        $data = [
            'secret' => RECAPTCHA_SECRET_KEY,
            'response' => $response,
            'remoteip' => $_SERVER['REMOTE_ADDR']
        ];
        
        $options = [
            'http' => [
                'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                'method' => 'POST',
                'content' => http_build_query($data)
            ]
        ];
        
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        
        if ($result === false) {
            return false;
        }
        
        $result = json_decode($result, true);
        return isset($result['success']) && $result['success'] === true;
    }
    
    // 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();