<?php
require_once __DIR__ . '/../../config/cors.php';
require_once __DIR__ . '/../../config/jwt.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); echo json_encode(['error' => 'Method not allowed']); exit;
}

// Support both form-urlencoded (Android Retrofit) and JSON (web/admin)
$contentType = strtolower($_SERVER['CONTENT_TYPE'] ?? '');
if (str_contains($contentType, 'application/json')) {
    $body  = json_decode(file_get_contents('php://input'), true) ?? [];
    $email = trim($body['email'] ?? '');
    $pass  = $body['password'] ?? '';
} else {
    $email = trim($_POST['email'] ?? '');
    $pass  = $_POST['password'] ?? '';
}

if (!$email || !$pass) {
    http_response_code(400); echo json_encode(['error' => 'Email and password required']); exit;
}

$stmt = $pdo->prepare('SELECT * FROM surveyors WHERE email = ? AND is_active = 1');
$stmt->execute([$email]);
$user = $stmt->fetch();

if (!$user || !password_verify($pass, $user['password_hash'])) {
    http_response_code(401); echo json_encode(['error' => 'Invalid credentials']); exit;
}

$token = jwt_encode([
    'id'   => $user['id'],
    'role' => $user['role'],
    'exp'  => time() + 86400,
]);

echo json_encode([
    'token' => $token,
    'role'  => $user['role'],
    'name'  => $user['name'],
]);
