<?php
class AuthController extends BaseController {
    public function showLogin() {
        $this->checkGuest();
        return $this->view->render('auth/login', ['title' => 'Login']);
    }
    
    public function login() {
        $this->checkGuest();
        
        $email = $_POST['email'] ?? '';
        $password = $_POST['password'] ?? '';
        
        $stmt = $this->db->prepare("
            SELECT u.*, t.company_name 
            FROM users u 
            LEFT JOIN tenants t ON u.tenant_id = t.id 
            WHERE u.email = ? AND u.email_verified = 1
        ");
        $stmt->execute([$email]);
        $user = $stmt->fetch();
        
        if ($user && password_verify($password, $user['password_hash'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_email'] = $user['email'];
            $_SESSION['user_name'] = $user['first_name'] . ' ' . $user['last_name'];
            $_SESSION['tenant_id'] = $user['tenant_id'];
            $_SESSION['company_name'] = $user['company_name'];
            
            $_SESSION['success'] = 'Login successful!';
            $this->redirect(url('/app'));
        }
        
        $_SESSION['error'] = 'Invalid credentials or email not verified';
        $this->redirect(url('/login'));
    }
    
    public function logout() {
        session_destroy();
        session_start();
        $this->redirect(url('/login'));
    }
    
    public function showRegister() {
        $this->checkGuest();
        return $this->view->render('auth/register', ['title' => 'Register']);
    }
    
    public function register() {
        $this->checkGuest();
        
        // Your existing registration logic
        $first_name = $_POST['first_name'] ?? '';
        $last_name = $_POST['last_name'] ?? '';
        $email = $_POST['email'] ?? '';
        $password = $_POST['password'] ?? '';
        $account_type = $_POST['account_type'] ?? 'individual';
        $company_name = $_POST['company_name'] ?? '';
        
        // Validation
        $errors = [];
        if (empty($first_name)) $errors[] = "First name is required";
        if (empty($email)) $errors[] = "Email is required";
        if (empty($password)) $errors[] = "Password is required";
        if ($account_type === 'company' && empty($company_name)) {
            $errors[] = "Company name is required for business accounts";
        }
        
        if (!empty($errors)) {
            $_SESSION['error'] = implode('<br>', $errors);
            $_SESSION['form_data'] = $_POST;
            $this->redirect(url('/register'));
        }
        
        try {
            $this->db->beginTransaction();
            
            // Create tenant
            $stmt = $this->db->prepare("INSERT INTO tenants (company_name, account_type) VALUES (?, ?)");
            $company_display = $account_type === 'company' ? $company_name : ($first_name . ' ' . $last_name);
            $stmt->execute([$company_display, $account_type]);
            $tenant_id = $this->db->lastInsertId();
            
            // Create user
            $password_hash = password_hash($password, PASSWORD_DEFAULT);
            $email_token = bin2hex(random_bytes(32));
            
            $stmt = $this->db->prepare("
                INSERT INTO users (tenant_id, first_name, last_name, email, password_hash, email_verification_token) 
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([$tenant_id, $first_name, $last_name, $email, $password_hash, $email_token]);
            
            $this->db->commit();
            
            $_SESSION['success'] = 'Registration successful! Please check your email to verify your account.';
            $this->redirect(url('/login'));
            
        } catch (Exception $e) {
            $this->db->rollBack();
            $_SESSION['error'] = 'Registration failed: ' . $e->getMessage();
            $_SESSION['form_data'] = $_POST;
            $this->redirect(url('/register'));
        }
    }
    
    public function verifyEmail() {
        $token = $_GET['token'] ?? '';
        
        if (empty($token)) {
            $_SESSION['error'] = 'Invalid verification link';
            $this->redirect(url('/login'));
        }
        
        $stmt = $this->db->prepare("SELECT id FROM users WHERE email_verification_token = ?");
        $stmt->execute([$token]);
        $user = $stmt->fetch();
        
        if ($user) {
            $stmt = $this->db->prepare("UPDATE users SET email_verified = 1, email_verification_token = NULL WHERE id = ?");
            $stmt->execute([$user['id']]);
            $_SESSION['success'] = 'Email verified successfully! You can now login.';
        } else {
            $_SESSION['error'] = 'Invalid or expired verification link';
        }
        
        $this->redirect(url('/login'));
    }
}