<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
header("Access-Control-Allow-Headers: Content-Type");

session_start();
require "db.php";

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

$email = $data["email"] ?? "";
$password = $data["password"] ?? "";

if (!$email || !$password) {
    echo json_encode(["status" => "error", "message" => "Email & password required"]);
    exit;
}

$stmt = $pdo->prepare("SELECT id, name, email, password FROM users WHERE email = ?");
$stmt->execute([$email]);
$user = $stmt->fetch();

if ($user && $user["password"] === ($password)) {

    $_SESSION["user"] = [
        "id"    => $user["id"],
        "name"  => $user["name"],
        "email" => $user["email"]
    ];

    echo json_encode([
        "status" => "success",
        "message" => "Login successful",
        "user" => $_SESSION["user"]
    ]);
} else {
    echo json_encode(["status" => "error", "message" => "Invalid email or password"]);
}

