<?php
// =========================================================================
// FILE: auth.php
// =========================================================================
// UPDATED: Major overhaul to implement the device-specific session logic.
// - `login_user` now checks for device ID and stores the session token
//   and device ID in the nsh_users table.
// - `logout_user` now nullifies the session token and device ID fields.
// - `validate_session` is a new function to check token validity on app start.

require_once 'db.php';

// (register_user function is unchanged from our very first version)
function register_user($data) {
    if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
        http_response_code(400);
        return ['success' => false, 'message' => 'Invalid email format.'];
    }

    $conn = get_db_connection();
    $conn->begin_transaction();

    try {
        $sql_user = "INSERT INTO nsh_users (full_name, email, password_hash, role_id) VALUES (?, ?, ?, ?)";
        $stmt_user = $conn->prepare($sql_user);
        $password_hash = password_hash($data['password'], PASSWORD_BCRYPT);
        $role_id = $data['roleId'];
        $stmt_user->bind_param("sssi", $data['fullName'], $data['email'], $password_hash, $role_id);
        $stmt_user->execute();
        $user_id = $conn->insert_id;
        $stmt_user->close();

        if ($role_id == 1) {
            $sql_details = "INSERT INTO nsh_student_details (user_id, student_phone, parent_name, parent_phone, temp_address, perm_address) VALUES (?, ?, ?, ?, ?, ?)";
            $stmt_details = $conn->prepare($sql_details);
            $stmt_details->bind_param("isssss", $user_id, $data['studentPhone'], $data['parentName'], $data['parentPhone'], $data['tempAddress'], $data['permAddress']);
            $stmt_details->execute();
            $stmt_details->close();
            
        }
        else if ($role_id == 3) {
            $sql_details = "INSERT INTO nsh_teacher_details (user_id, subject, phone_number) VALUES (?, ?, ?)";
            $stmt_details = $conn->prepare($sql_details);
            $stmt_details->bind_param("iss", $user_id, $data['subject'], $data['phoneNumber']);
            $stmt_details->execute();
            $stmt_details->close();
            
        }
        else if ($role_id == 2) {
            $sql_details = "INSERT INTO nsh_parent_details (user_id, phone_number) VALUES (?, ?)";
            $stmt_details = $conn->prepare($sql_details);
            $stmt_details->bind_param("is", $user_id, $data['phoneNumber']);
            $stmt_details->execute();
            $stmt_details->close();
            
        }

        $conn->commit();
        $response = ['success' => true, 'message' => 'User registered successfully.'];
        http_response_code(201);

    } catch (mysqli_sql_exception $e) {
        $conn->rollback();
        if ($e->getCode() == 1062) {
            http_response_code(409);
            $response = ['success' => false, 'message' => 'This email address is already registered.'];
        } else {
            http_response_code(500);
            $response = ['success' => false, 'message' => 'A database error occurred.'];
        }
    }
    
    $conn->close();
    return $response;
}


function login_user($data) {
    if (empty($data['email']) || empty($data['password']) || empty($data['deviceId'])) {
        http_response_code(400);
        return ['success' => false, 'message' => 'Email, password, and deviceId are required.'];
    }

    $conn = get_db_connection();
    $email = $data['email'];
    $deviceId = $data['deviceId'];

    $stmt = $conn->prepare("SELECT user_id, password_hash, full_name, role_id, mobile_device_id FROM nsh_users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$user || !password_verify($data['password'], $user['password_hash'])) {
        http_response_code(401);
        return ['success' => false, 'message' => 'Invalid email or password.'];
    }

    // Security: Check if another device is already logged in
    if (!empty($user['mobile_device_id']) && $user['mobile_device_id'] !== $deviceId) {
        http_response_code(409); // Conflict
        return ['success' => false, 'message' => 'This account is already logged in on another device. Please log out from the other device first.'];
    }

    // Login successful, generate and store new token
    $token = bin2hex(random_bytes(32));
    
    $update_stmt = $conn->prepare("UPDATE nsh_users SET mobile_session_token = ?, mobile_device_id = ?, last_login = NOW() WHERE user_id = ?");
    $update_stmt->bind_param("ssi", $token, $deviceId, $user['user_id']);
    $update_stmt->execute();
    $update_stmt->close();
    $conn->close();

    http_response_code(200);
    return [
        'success' => true,
        'message' => 'Login successful!',
        'token' => $token,
        'user' => [
            'userId' => $user['user_id'],
            'fullName' => $user['full_name'],
            'email' => $email,
            'roleId' => $user['role_id']
        ]
    ];
}

function logout_user($token) {
    if (empty($token)) {
        http_response_code(400);
        return ['success' => false, 'message' => 'Token not provided.'];
    }
    
    $conn = get_db_connection();
    // Find the user by the token and nullify their session fields
    $stmt = $conn->prepare("UPDATE nsh_users SET mobile_session_token = NULL, mobile_device_id = NULL WHERE mobile_session_token = ?");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    
    $success = $stmt->affected_rows > 0;
    $stmt->close();
    $conn->close();
    
    http_response_code($success ? 200 : 401);
    return ['success' => $success, 'message' => $success ? 'Logout successful.' : 'Invalid token.'];
}

function validate_session($data) {
    if (empty($data['userId']) || empty($data['token'])) {
        http_response_code(400);
        return ['success' => false, 'message' => 'userId and token are required.'];
    }

    $conn = get_db_connection();
    $stmt = $conn->prepare("SELECT mobile_session_token FROM nsh_users WHERE user_id = ?");
    $stmt->bind_param("i", $data['userId']);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $conn->close();

    if ($result && $result['mobile_session_token'] === $data['token']) {
        http_response_code(200);
        return ['success' => true, 'valid' => true];
    } else {
        http_response_code(200); // The request was successful, the session is just not valid
        return ['success' => true, 'valid' => false, 'message' => 'Session expired or invalid. Please log in again.'];
    }
}


// Helper to get the token from 'Authorization: Bearer <token>' header
function get_bearer_token() {
    $headers = getallheaders();
    if (isset($headers['Authorization']) && preg_match('/Bearer\s(\S+)/', $headers['Authorization'], $matches)) {
        return $matches[1];
    }
    return null;
}
?>