<?php
include 'db.php';

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

$data = json_decode(file_get_contents('php://input'), true);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $phone = $data['phone'];
    $password = $data['password'];

    if (!$phone || !$password) {
        echo json_encode(['success' => false, 'message' => 'Phone and password are required']);
        exit();
    }

    // Check if user exists with the given phone number
    $stmt = $conn->prepare("SELECT id, name, password FROM users WHERE phone = ?");
    
    if (!$stmt) {
        echo json_encode(['success' => false, 'message' => 'Error in prepare statement: ' . $conn->error]);
        exit();
    }

    $stmt->bind_param('s', $phone);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        $stmt->bind_result($userId, $username, $hashedPassword);
        $stmt->fetch();

        // Verify password
        if (password_verify($password, $hashedPassword)) {
            echo json_encode(['success' => true, 'message' => 'Login successful', 'token' => 'dummy-token', 'userId' => $userId]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Incorrect password']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'User not found']);
    }

    $stmt->close();
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}

$conn->close();
?>
