<?php
require_once __DIR__ . '/../connect.php';

// Get email and password from the request
$email = filterRequest('email');
$password = filterRequest('password');

// Check if email and password are provided
if (empty($email) || empty($password)) {
    echo json_encode([
        "status" => "failure",
        "message" => "Email and password are required."
    ]);
    exit();
}

// SQL to check for user with provided email
$sql = "SELECT * FROM `users` WHERE `email` = :email";

$stmt = $con->prepare($sql);
$stmt->bindParam(':email', $email);
$stmt->execute();

$user = $stmt->fetch(PDO::FETCH_ASSOC);

header('Content-Type: application/json'); // Ensure the response is JSON

if ($user) {
    // Verify the password
    if ($password=== $user['password']) {
        // Password is correct
        unset($user['password']); // Remove password from the response
        echo json_encode([
            "status" => "success",
            "message" => "Login successful",
            "data" => $user
        ]);
    } else {
        // Password is incorrect
        echo json_encode([
            "status" => "failure",
            "message" => "Incorrect password",
            "password"=>$password,
            "password1"=>$user['password'],
        ]);
    }
} else {
    // User not found
    echo json_encode([
        "status" => "failure",
        "message" => "User not found"
    ]);
}

$stmt = null; // Close the statement
$con = null;  // Close the connection
exit();       // Ensure no further output