<?php
/**
 * Authentication Controller (FIXED - backward compatible roles)
 */

class AuthController {
    private $db;
    private $config;

    public function __construct($db, $config) {
        $this->db = $db;
        $this->config = $config;
    }

    public function login($data) {
        if (empty($data['email']) || empty($data['password'])) {
            return ['success' => false, 'message' => 'Email and password required'];
        }

        try {
            $stmt = $this->db->prepare("
                SELECT u.id, u.name, u.email, u.password, u.role_id, u.status,
                       r.name AS role_name, r.label AS role_label
                FROM users u
                LEFT JOIN roles r ON r.id = u.role_id
                WHERE u.email = ? AND u.status = 'active' AND u.deleted_at IS NULL
            ");
            $stmt->execute([$data['email']]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$user) {
                return ['success' => false, 'message' => 'Invalid credentials'];
            }

            if (!password_verify($data['password'], $user['password'])) {
                return ['success' => false, 'message' => 'Invalid credentials'];
            }

            // Generate session token
            $token = bin2hex(random_bytes(32));
            $expires_at = date('Y-m-d H:i:s', strtotime('+7 days'));

            $stmt = $this->db->prepare("
                INSERT INTO user_sessions (user_id, token, ip_address, user_agent, expires_at, created_at)
                VALUES (?, ?, ?, ?, ?, NOW())
            ");
            $stmt->execute([
                $user['id'], $token,
                $_SERVER['REMOTE_ADDR'] ?? '',
                $_SERVER['HTTP_USER_AGENT'] ?? '',
                $expires_at
            ]);

            // Update last login
            $stmt = $this->db->prepare("UPDATE users SET last_login_at = NOW() WHERE id = ?");
            $stmt->execute([$user['id']]);

            // Remove password from response
            unset($user['password']);

            // Add backward-compatible role fields
            $roleMap = [1 => 'admin', 2 => 'admin', 3 => 'manager', 4 => 'staff'];
            $user['role'] = $user['role_name'] ?? ($roleMap[$user['role_id']] ?? 'admin');
            $user['active'] = 1;
            $user['property_id'] = null;

            // Get user's property if any
            try {
                $pStmt = $this->db->prepare("SELECT id FROM properties WHERE owner_id = ? LIMIT 1");
                $pStmt->execute([$user['id']]);
                $prop = $pStmt->fetch(PDO::FETCH_ASSOC);
                if ($prop) $user['property_id'] = $prop['id'];
            } catch (Exception $e) {}

            // Get permissions
            try {
                if ($user['role_name'] === 'super_admin' || $user['role_id'] == 1) {
                    $user['permissions'] = ['all'];
                } else {
                    $permStmt = $this->db->prepare("
                        SELECT p.code FROM role_permissions rp
                        JOIN permissions p ON p.id = rp.permission_id
                        WHERE rp.role_id = ?
                    ");
                    $permStmt->execute([$user['role_id']]);
                    $user['permissions'] = $permStmt->fetchAll(PDO::FETCH_COLUMN) ?: [];
                }
            } catch (Exception $e) {
                $user['permissions'] = ['all'];
            }

            return [
                'success' => true,
                'message' => 'Login successful',
                'user' => $user,
                'token' => $token
            ];

        } catch (Exception $e) {
            error_log('Auth login error: ' . $e->getMessage());
            return ['success' => false, 'message' => 'Server error: ' . $e->getMessage()];
        }
    }

    public function register($data) {
        $required = ['name', 'email', 'password', 'password_confirm'];
        foreach ($required as $field) {
            if (empty($data[$field])) {
                return ['success' => false, 'message' => ucfirst($field) . ' required'];
            }
        }

        if ($data['password'] !== $data['password_confirm']) {
            return ['success' => false, 'message' => 'Passwords do not match'];
        }

        try {
            $stmt = $this->db->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$data['email']]);
            if ($stmt->fetch()) {
                return ['success' => false, 'message' => 'Email already registered'];
            }

            $stmt = $this->db->prepare("
                INSERT INTO users (name, email, password, role_id, status, created_at)
                VALUES (?, ?, ?, 4, 'active', NOW())
            ");
            $stmt->execute([
                $data['name'],
                $data['email'],
                password_hash($data['password'], PASSWORD_BCRYPT)
            ]);

            return ['success' => true, 'message' => 'Registration successful'];

        } catch (Exception $e) {
            error_log('Auth register error: ' . $e->getMessage());
            return ['success' => false, 'message' => 'Server error'];
        }
    }

    public function logout($token) {
        if (!$token) {
            return ['success' => false, 'message' => 'No token provided'];
        }

        try {
            $stmt = $this->db->prepare("DELETE FROM user_sessions WHERE token = ?");
            $stmt->execute([$token]);
            return ['success' => true, 'message' => 'Logged out'];
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Server error'];
        }
    }

    public function verify($token) {
        if (!$token) {
            return ['success' => false, 'message' => 'No token'];
        }

        try {
            $stmt = $this->db->prepare("
                SELECT u.id, u.name, u.email, u.role_id, u.status,
                       r.name AS role_name, r.label AS role_label
                FROM user_sessions s
                JOIN users u ON u.id = s.user_id
                LEFT JOIN roles r ON r.id = u.role_id
                WHERE s.token = ? AND s.expires_at > NOW()
            ");
            $stmt->execute([$token]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$user) {
                return ['success' => false, 'message' => 'Invalid or expired token'];
            }

            // Add backward-compatible fields
            $roleMap = [1 => 'admin', 2 => 'admin', 3 => 'manager', 4 => 'staff'];
            $user['role'] = $user['role_name'] ?? ($roleMap[$user['role_id']] ?? 'admin');
            $user['active'] = 1;

            return ['success' => true, 'user' => $user];

        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Server error'];
        }
    }
}
