<?php

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


require_once '../../core/employee_auth.php';
EmployeeAuth::check('manage_providers');

$data = Request::post();

try {

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

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

    $provider_id = (int)$data['provider_id'];

    /*
    UPDATE PROVIDERS TABLE
    */

    $query = "

        UPDATE providers SET
        name = :name,
        phone = :phone,
        whatsapp = :whatsapp,
        email = :email
        WHERE id = :id

    ";

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

    $stmt->execute([

        ':name' => $data['name'] ?? null,
        ':phone' => $data['phone'] ?? null,
        ':whatsapp' => $data['whatsapp'] ?? null,
        ':email' => $data['email'] ?? null,
        ':id' => $provider_id

    ]);


    /*
    HANDLE PROFILE PHOTO UPLOAD
    */

    $profile_photo = null;

    if(isset($_FILES['profile_photo']) && $_FILES['profile_photo']['error'] === 0){
        $profile_photo = Upload::image('profile_photo','providers');
    }


    /*
    UPDATE PROFILE TABLE
    */

    $query = "

        UPDATE provider_profiles SET

        business_name = :business_name,
        description = :description,
        address = :address,
        city_id = :city_id,
        pincode = :pincode

    ";

    $params = [

        ':business_name' => $data['business_name'] ?? null,
        ':description' => $data['description'] ?? null,
        ':address' => $data['address'] ?? null,
        ':city_id' => $data['city_id'] ?? null,
        ':pincode' => $data['pincode'] ?? null,
        ':provider_id' => $provider_id

    ];


    /*
    ADD PHOTO UPDATE IF EXISTS
    */

    if($profile_photo){

        $query .= ", profile_photo = :profile_photo";
        $params[':profile_photo'] = $profile_photo;

    }


    $query .= " WHERE provider_id = :provider_id";

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

    $stmt->execute($params);


    Response::success([],"Provider updated successfully");

}
catch(Exception $e){

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

}