<?php
session_start();
include_once("../includes/configuration.php"); // Ensure configuration includes database connection setup

// Handle login on POST request
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $email = $_POST['email'];
    $password = md5($_POST['password']); // MD5 hashing for password (consider stronger hashing like password_hash in production)

    // Query to select the user based on email and hashed password
    $sql = "SELECT * FROM users WHERE email = ? AND password = ? ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $email, $password); // Bind both email and hashed password
    $stmt->execute();
    $result = $stmt->get_result();

    // Check if user exists
    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        if ($user['status'] === 0) {
            echo json_encode(['status' => 'error', 'message' => 'Your account is not active']);
        } else {
            // Set session for authenticated user
            $_SESSION['user_token'] = $user['token'];
            $_SESSION["user_id"] = base64_encode($user['email']);
            setcookie("user_token_cookie_faysal", $user['token'], time() + (10 * 365 * 24 * 60 * 60), "/", "", true, true); // 10 years
            echo json_encode(['status' => 'success', 'message' => 'Login successful']);
        }
    } else {
        // If no match is found for email and password
        echo json_encode(['status' => 'error', 'message' => 'Invalid email or password']);
    }

    // Close the statement and connection
    $stmt->close();
    $conn->close();
}
?>