<?php

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

$data = Request::post();

try {

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

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

    $name  = Helper::sanitize($data['name']);
    $phone = $data['phone'];
    $whatsapp = $data['whatsapp'] ?? null;
    $email = $data['email'] ?? null;

    $password = password_hash($data['password'], PASSWORD_BCRYPT);

    $query = "
        INSERT INTO providers
        (name, phone, whatsapp, email, password)
        VALUES
        (:name, :phone, :whatsapp, :email, :password)
    ";

    $stmt = $conn->prepare($query);

    $stmt->execute([
        ':name' => $name,
        ':phone' => $phone,
        ':whatsapp' => $whatsapp,
        ':email' => $email,
        ':password' => $password
    ]);

    $provider_id = $conn->lastInsertId();


    /*
    create empty profile
    */

    $query = "
        INSERT INTO provider_profiles
        (provider_id)
        VALUES
        (:provider_id)
    ";

    $stmt = $conn->prepare($query);

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


    Response::success([
        "provider_id"=>$provider_id
    ],"Provider registered successfully");

}
catch(Exception $e){

    Logger::log("system.log",$e->getMessage());

    Response::error("Server error",500);

}