<?php
header('Content-Type: application/json');

include_once __DIR__ . '/../../config/dbcon.php';
include_once __DIR__ . '/../../helpers/api_helper.php';
require_once __DIR__ . '/../../helpers/jwt_helper.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(405, "Invalid request method.");
}

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

$email = trim($data['email'] ?? '');
$phone = trim($data['phone'] ?? '');

if ($email === '' && $phone === '') {
    sendResponse(422, "Email or phone number is required.");
}

if ($email !== '') {

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        sendResponse(422, "Invalid email format.");
    }

    $field = 'email';
    $value = $email;

} else {

   if ( !preg_match('/^\+[1-9]\d{7,14}$/', $phone)) {
    sendResponse(422, "Invalid phone number format.");
}


    $field = 'phone';
    $value = $phone;
}

try {
    $stmt = $conn->prepare("
        SELECT id, name, email, phone, role, profile
        FROM users
        WHERE $field = ?
        LIMIT 1
    ");
    $stmt->execute([$value]);

    if ($stmt->rowCount() === 0) {
        sendResponse(404, "User not found.");
    }

    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    $token = generateJWT([
        'user_id' => $user['id'],
        'role' => $user['role']
    ]);

    sendResponse(200, "Login successful.", [
       
        'user' => [
            'id' => $user['id'],
             'token' => $token,
            'name' => $user['name'],
            'email' => $user['email'],
            'phone' => $user['phone'],
            'role' => $user['role'],
            'profile_image' => $user['profile']
                ? '/uploads/profile/' . $user['profile']
                : null
        ]
    ]);

} catch (PDOException $e) {
    sendResponse(500, "Database error.");
}
