<?php
// auth.php - Authentication functions for Doyle Enterprise
include_once 'config.php';

if (!function_exists('sanitize_input')) {
    function sanitize_input($data) {
        global $conn;
        return htmlspecialchars(trim($conn->real_escape_string($data)), ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('is_logged_in')) {
    function is_logged_in() {
        return isset($_SESSION['user_id']);
    }
}

if (!function_exists('is_admin')) {
    function is_admin() {
        return is_logged_in() && isset($_SESSION['is_admin']) && $_SESSION['is_admin'] == 1;
    }
}

if (!function_exists('login')) {
    function login($email, $password) {
        global $conn;
        $email = sanitize_input($email);
        $stmt = $conn->prepare("SELECT id, username, password, is_admin FROM users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($user = $result->fetch_assoc()) {
            if ($password === $user['password']) { // Plain text comparison (insecure)
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['is_admin'] = $user['is_admin'];
                return true;
            }
        }
        return false;
    }
}

if (!function_exists('register')) {
    function register($username, $email, $password) {
        global $conn;
        $username = sanitize_input($username);
        $email = sanitize_input($email);
        $stmt = $conn->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");
        $stmt->bind_param("sss", $username, $email, $password);
        return $stmt->execute();
    }
}

if (!function_exists('update_profile')) {
    function update_profile($user_id, $username, $email, $password) {
        global $conn;
        $username = sanitize_input($username);
        $email = sanitize_input($email);
        if (!empty($password)) {
            $stmt = $conn->prepare("UPDATE users SET username = ?, email = ?, password = ? WHERE id = ?");
            $stmt->bind_param("sssi", $username, $email, $password, $user_id);
        } else {
            $stmt = $conn->prepare("UPDATE users SET username = ?, email = ? WHERE id = ?");
            $stmt->bind_param("ssi", $username, $email, $user_id);
        }
        if ($stmt->execute()) {
            $_SESSION['username'] = $username; // Update session
            return true;
        }
        return false;
    }
}

if (!function_exists('logout')) {
    function logout() {
        session_unset(); // Clear all session variables
        session_destroy(); // Destroy the session
        return true;
    }
}

?>