<?php
// login.php

header('Content-Type: application/json');

// Enable CORS
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

// Simulated database of users
$users = [
    'user1@example.com' => 'password123',
    'user2@example.com' => 'securepassword',
];

// Read input data
$input = json_decode(file_get_contents('php://input'), true);
$email = $input['email'] ?? '';
$password = $input['password'] ?? '';

// Validate input
if (empty($email) || empty($password)) {
    http_response_code(400);
    echo json_encode(['error' => 'Email and password are required.']);
    exit;
}

// Authenticate user
if (isset($users[$email]) && $users[$email] === $password) {
    // Generate a token (for simplicity, using base64 encoding)
    $token = base64_encode($email . ':' . time());

    echo json_encode(['token' => $token]);
} else {
    http_response_code(401);
    echo json_encode(['error' => 'Invalid email or password.']);
}
?>