<?php
// auth.php - Authentication Functions
// File location: /bidwheels.net/includes/auth.php

require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/mailer.php';

/**
 * Register new user
 */
function registerUser($name, $email, $password, $phone = '') {
    // Check if email exists
    $existing = fetchOne("SELECT id FROM users WHERE email = '$email'");
    if ($existing) {
        return ['success' => false, 'message' => 'Email already registered'];
    }
    
    // Hash password
    $hashed_password = md5($password);
    
    // Insert user
    $user_id = insert('users', [
        'name' => sanitize($name),
        'email' => sanitize($email),
        'password' => $hashed_password,
        'phone' => sanitize($phone),
        'role' => 'user',
        'is_dummy' => 0
    ]);
    
    if ($user_id) {
        // Send welcome email
        sendWelcomeEmail($email, $name);
        return ['success' => true, 'message' => 'Registration successful! Please login.'];
    }
    
    return ['success' => false, 'message' => 'Registration failed. Please try again.'];
}

/**
 * Login user
 */
function loginUser($email, $password) {
    $hashed_password = md5($password);
    $user = fetchOne("SELECT * FROM users WHERE email = '$email' AND password = '$hashed_password'");
    
    if ($user) {
        // Check if dummy account - prevent login
        if ($user['is_dummy'] == 1) {
            return ['success' => false, 'message' => 'Invalid credentials'];
        }
        
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_name'] = $user['name'];
        $_SESSION['user_email'] = $user['email'];
        $_SESSION['user_role'] = $user['role'];
        
        return ['success' => true, 'message' => 'Login successful!', 'role' => $user['role']];
    }
    
    return ['success' => false, 'message' => 'Invalid email or password'];
}

/**
 * Admin login
 */
function adminLogin($email, $password) {
    $result = loginUser($email, $password);
    
    if ($result['success'] && isset($_SESSION['user_role']) && $_SESSION['user_role'] == 'admin') {
        return $result;
    }
    
    logout();
    return ['success' => false, 'message' => 'Access denied. Admin only.'];
}

/**
 * Logout user
 */
function logout() {
    session_destroy();
    $_SESSION = [];
}

/**
 * Check if user is dummy (block login)
 */
function isDummyUser($user_id) {
    $user = fetchOne("SELECT is_dummy FROM users WHERE id = $user_id");
    return $user && $user['is_dummy'] == 1;
}

/**
 * Require login
 */
function requireLogin() {
    if (!isLoggedIn()) {
        redirect('/user/login.php');
        exit();
    }
}

/**
 * Require admin
 */
function requireAdmin() {
    if (!isAdmin()) {
        redirect('/admin/login.php');
        exit();
    }
}

/**
 * Get user by ID
 */
function getUser($user_id) {
    return fetchOne("SELECT id, name, email, phone, role, created_at FROM users WHERE id = $user_id");
}
?>