<?php

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

$provider_id = ProviderAuth::id();

$data = Request::post();

try{

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

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


/*
-----------------------------------
VERIFY SERVICE BELONGS TO PROVIDER
-----------------------------------
*/

$stmt=$conn->prepare("

SELECT id

FROM provider_service_categories

WHERE provider_id=:provider
AND category_id=:category
AND sub_category_id=:subcategory

LIMIT 1

");

$stmt->execute([
':provider'=>$provider_id,
':category'=>$data['category_id'],
':subcategory'=>$data['sub_category_id']
]);

if(!$stmt->fetch()){
Response::error("Service not assigned to provider.");
}


/*
-----------------------------------
CHECK DUPLICATE
-----------------------------------
*/

$stmt=$conn->prepare("

SELECT id

FROM provider_service_area_map

WHERE provider_id=:provider
AND sub_category_id=:subcategory
AND pincode_id=:pincode

LIMIT 1

");

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

if($stmt->fetch()){
Response::error("This area already exists for the selected service.");
}


/*
-----------------------------------
INSERT SERVICE AREA
-----------------------------------
*/

$stmt=$conn->prepare("

INSERT INTO provider_service_area_map
(provider_id,category_id,sub_category_id,pincode_id)

VALUES
(:provider,:category,:subcategory,:pincode)

");

$stmt->execute([

':provider'=>$provider_id,
':category'=>$data['category_id'],
':subcategory'=>$data['sub_category_id'],
':pincode'=>$data['pincode_id']

]);

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

}
catch(Exception $e){

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

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

}