<?php

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

$provider_id = ProviderAuth::id();

$data = Request::post();

try {

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

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


    /*
    CHECK DUPLICATE PINCODE
    */

    $stmt = $conn->prepare("

        SELECT id

        FROM provider_service_areas

        WHERE provider_id = :provider
        AND pincode_id = :pincode

        LIMIT 1

    ");

    $stmt->execute([
        ':provider' => $provider_id,
        ':pincode' => $data['pincode_id']
    ]);

    if ($stmt->fetch()) {
        Response::error("This pincode is already added in your service areas.");
    }


    /*
    INSERT SERVICE AREA
    */

    $stmt = $conn->prepare("

        INSERT INTO provider_service_areas
        (provider_id, pincode_id)

        VALUES
        (:provider, :pincode)

    ");

    $stmt->execute([

        ':provider' => $provider_id,
        ':pincode' => $data['pincode_id']

    ]);


    Response::success([], "Service area added successfully");


} catch (PDOException $e) {

    /*
    HANDLE UNIQUE CONSTRAINT ERROR
    */

    if ($e->getCode() == 23000) {
        Response::error("This pincode is already added.");
    }

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

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

}