<?php
// Set the header to indicate the response is JSON
header('Content-Type: application/json');

// Include your database connection file
require_once '../includes/db.php';

// Prepare a standard response array
$response = array('status' => 'error', 'message' => 'An unknown error occurred.');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';

    if (empty($email) || empty($password)) {
        $response['message'] = "Please enter both email and password.";
    } else {
        // --- Fetch user from the database ---
        $stmt = $conn->prepare("SELECT id, full_name, email, password, role, status FROM users WHERE email = ? LIMIT 1");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        // --- Verify user exists and password is correct ---
        if ($user && password_verify($password, $user['password'])) {
            // Check if the user's account is active
            if ($user['status'] === 'active') {
                // --- Login Success ---
                $response['status'] = 'success';
                $response['message'] = 'Login successful!';
                
                // Send user data back to the app. The app will store this.
                $response['data'] = array(
                    'user_id' => $user['id'],
                    'full_name' => $user['full_name'],
                    'email' => $user['email'],
                    'role' => $user['role']
                );
            } else {
                $response['message'] = "Your account is currently " . $user['status'] . ".";
            }
        } else {
            $response['message'] = "Invalid email or password.";
        }
    }
} else {
    $response['message'] = 'Invalid request method. Only POST is accepted.';
}

// Close the database connection
$conn->close();

// Send the final JSON response back to the Sketchware app
echo json_encode($response);
?>
