<?php
session_start();
header('Content-Type: application/json');
require_once "../includes/functions.php"; 

$phone = trim($_POST['phone'] ?? '');
$pin   = trim($_POST['pin'] ?? '');

if (empty($phone) || empty($pin)) {
    echo json_encode(["status" => "error", "message" => "Phone and Pin are required"]);
    exit;
}

$user = loginUser($phone, $pin);

if ($user) {
    // save user to session
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['fullname'] = $user['fullname'];
    $_SESSION['email'] = $user['email'];
    $_SESSION['phone'] = $user['phone'];

    echo json_encode([
        "status" => "success",
        "message" => "Login successful",
        "user" => [
            "id" => $user['id'],
            "fullname" => $user['fullname'],
            "email" => $user['email'],
            "phone" => $user['phone']
        ]
    ]);
} else {
    echo json_encode(["status" => "error", "message" => "Invalid phone or pin"]);
}
