<?php
require_once 'db_config.php';
require_once 'session_helper.php';

class User {
    
    public function register($n, $e, $p, $ph, $addr) {
        $db = getDBConnection();
        $check = $db->prepare("SELECT id FROM users WHERE email = ?");
        $check->execute([$e]);
        if ($check->rowCount() > 0) return ['success' => false, 'message' => 'Email exists'];
        
        $hp = password_hash($p, PASSWORD_DEFAULT);
        $ins = $db->prepare("INSERT INTO users (name, email, password, phone, adress) VALUES (?, ?, ?, ?, ?)");
        $res = $ins->execute([$n, $e, $hp, $ph, $addr]);
        return $res ? ['success' => true, 'message' => 'OK'] : ['success' => false, 'message' => 'Failed'];
    }
    
    public function login($e, $p) {
        $db = getDBConnection();
        $stmt = $db->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$e]);
        $u = $stmt->fetch();
        
        if ($u && password_verify($p, $u['password'])) {
            safe_session_start();
            $_SESSION['user_id'] = $u['id'];
            $_SESSION['user_name'] = $u['name'];
            $_SESSION['user_email'] = $u['email'];
            $_SESSION['user_role'] = $u['role'];
            require_once 'cart.php';
            onUserLogin($u['id']);
            return ['success' => true, 'message' => 'OK', 'role' => $u['role']];
        }
        return ['success' => false, 'message' => 'Wrong login'];
    }
    
    public static function isLoggedIn() {
        return is_logged_in();
    }
    
    public static function isAdmin() {
        return is_admin();
    }
    
    public static function getCurrentUser() {
        return get_current_user_data();
    }
    
    public static function logout() {
        safe_session_start();
        require_once 'cart.php';
        onUserLogout();
        session_destroy();
    }
}
?>