<?php

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

require_once("../config/db.php");

/* ================= GET INPUT ================= */

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

if (!$data) {
    echo json_encode([
        "status" => false,
        "message" => "Invalid request"
    ]);
    exit;
}

$mobile   = $conn->real_escape_string($data['mobile'] ?? '');
$password = $data['password'] ?? '';

if (!$mobile || !$password) {
    echo json_encode([
        "status" => false,
        "message" => "Mobile & Password required"
    ]);
    exit;
}

/* ================= GET USER ================= */

$query = "SELECT * FROM users WHERE mobile = '$mobile' LIMIT 1";
$result = $conn->query($query);

if (!$result || $result->num_rows == 0) {
    echo json_encode([
        "status" => false,
        "message" => "User not found"
    ]);
    exit;
}

$user = $result->fetch_assoc();

/* ================= STATUS CHECK ================= */

if ($user['status'] !== 'approved') {
    echo json_encode([
        "status" => false,
        "message" => "Account pending"
    ]);
    exit;
}

/* ================= PASSWORD VERIFY ================= */

if (!password_verify($password, $user['password'])) {
    echo json_encode([
        "status" => false,
        "message" => "Invalid password"
    ]);
    exit;
}

/* ================= SUCCESS ================= */

echo json_encode([
    "status" => true,
    "message" => "Login success",
    "data" => [
        "id" => $user['id'],
        "name" => $user['name'],
        "mobile" => $user['mobile'],
        "role" => $user['role'],
        "village_id" => $user['village_id']
    ]
]);