<?php

require_once '../../../core/api_bootstrap.php';
require_once '../../../core/jwt.php';

$data = Request::post();

try {

    Validator::required($data, [
        'phone',
        'password'
    ]);

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

    $db = new Database();
    $conn = $db->connect();

    $stmt = $conn->prepare("
SELECT id,name,phone,email,password,account_status
FROM providers
WHERE phone = :phone
LIMIT 1
");

    $stmt->execute([
        ':phone' => $phone
    ]);

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

    if (!$provider) {
        Response::error("Invalid phone or password", 401);
    }

    if (!password_verify($data['password'], $provider['password'])) {
        Response::error("Invalid phone or password", 401);
    }

    if ($provider['account_status'] != 'active') {
        Response::error("Account not active", 403);
    }

    $token = JWTAuth::generate($provider['id']);

    Response::success([
        "token" => $token,
        "provider" => [
            "id" => $provider['id'],
            "name" => $provider['name'],
            "phone" => $provider['phone'],
            "email" => $provider['email']
        ]
    ]);

} catch (Exception $e) {

    Logger::log("system.log", $e->getMessage());
    Response::error("Server error", 500);

}