<?php

require_once 'includes/provider_auth.php';
require_once '../config/constants.php';

$token = $_SESSION['provider_token'];
$provider_id = $_SESSION['provider']['id'];

/*
GET SERVICE AREAS
*/

$ch = curl_init();

curl_setopt_array($ch,[
CURLOPT_URL => API_URL."providers/service-areas.php",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'X-API-KEY: '.API_KEY,
'Authorization: Bearer '.$token
]
]);

$res = curl_exec($ch);
curl_close($ch);

$data = json_decode($res,true);

$services = $data['data']['services'] ?? [];
$areas    = $data['data']['service_areas'] ?? [];


/*
GET SUBSCRIPTION
*/

$ch = curl_init();

curl_setopt_array($ch,[
CURLOPT_URL => API_URL."providers/full-profile.php?provider_id=".$provider_id,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'X-API-KEY: '.API_KEY,
'Authorization: Bearer '.$token
]
]);

$res = curl_exec($ch);
curl_close($ch);

$profile = json_decode($res,true);

$subscription = $profile['data']['subscription'] ?? [];

$areaLimit = $subscription['service_areas_allowed'] ?? 0;
$currentAreas = count($areas);
$remainingAreas = max(0, $areaLimit - $currentAreas);

?>

<?php include '../admin/partials/layouts/layoutTop.php' ?>


<div class="dashboard-main-body">

<h6 class="fw-semibold mb-24">My Service Areas</h6>


<div class="card p-24 mb-24">

<div class="row mb-20">

<div class="col-md-4">
<strong>Plan:</strong>
<?php echo htmlspecialchars($subscription['plan_name'] ?? 'Trial Plan'); ?>
</div>

<div class="col-md-4">
<strong>Areas Used:</strong>
<?php echo $currentAreas ?> / <?php echo $areaLimit ?>
</div>

<div class="col-md-4">
<strong>Areas Remaining:</strong>
<?php echo $remainingAreas ?>
</div>

</div>


<?php if($remainingAreas<=0): ?>

<div class="alert alert-warning">
You have reached your plan limit.
<a href="subscription.php">Upgrade plan</a>
to add more areas.
</div>

<?php endif; ?>


<div class="row gy-3">

<div class="col-md-3">

<label class="form-label">Category</label>

<select id="category" class="form-select">
<option value="">Select Category</option>
</select>

</div>


<div class="col-md-3">

<label class="form-label">Service</label>

<select id="subcategory" class="form-select">
<option value="">Select Service</option>
</select>

</div>


<div class="col-md-2">

<label class="form-label">State</label>

<select id="state" class="form-select">
<option value="">Select State</option>
</select>

</div>


<div class="col-md-2">

<label class="form-label">City</label>

<select id="city" class="form-select">
<option value="">Select City</option>
</select>

</div>


<div class="col-md-2">

<label class="form-label">Areas</label>

<select id="pincode" class="form-select" multiple>
</select>

</div>

</div>


<div class="mt-20 text-end">

<button id="addAreaBtn"
class="btn btn-primary"
<?php if($remainingAreas<=0) echo "disabled"; ?>>

Add Service Areas

</button>

</div>

</div>



<div class="card p-24">

<table class="table bordered-table">

<thead>

<tr>
<th>Category</th>
<th>Service</th>
<th>Pincode</th>
<th>Area</th>
<th>City</th>
<th>Action</th>
</tr>

</thead>

<tbody>

<?php if($areas): ?>

<?php foreach($areas as $a): ?>

<tr>

<td><?php echo htmlspecialchars($a['category']) ?></td>

<td><?php echo htmlspecialchars($a['subcategory']) ?></td>

<td><?php echo htmlspecialchars($a['pincode']) ?></td>

<td><?php echo htmlspecialchars($a['area_name']) ?></td>

<td><?php echo htmlspecialchars($a['city']) ?></td>

<td>

<button
class="btn btn-danger removeArea"
data-id="<?php echo $a['id'] ?>">

Remove

</button>

</td>

</tr>

<?php endforeach ?>

<?php else: ?>

<tr>
<td colspan="6" class="text-center">No service areas added</td>
</tr>

<?php endif ?>

</tbody>

</table>

</div>

</div>


<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>

<script>

const headers={
'X-API-KEY':'<?php echo API_KEY ?>',
'Authorization':'Bearer <?php echo $_SESSION["provider_token"] ?>'
};

const services=<?php echo json_encode($services); ?>;


/*
SELECT2
*/

$('#pincode').select2({
placeholder:"Select Areas"
});


/*
LOAD CATEGORY
*/

let categories={};

services.forEach(function(s){
categories[s.category_id]=s.category;
});

for(let id in categories){

$("#category").append(
`<option value="${id}">${categories[id]}</option>`
);

}


/*
LOAD SERVICES
*/

$("#category").change(function(){

let cat=$(this).val();

$("#subcategory").html('<option value="">Select Service</option>');

services.forEach(function(s){

if(s.category_id==cat){

$("#subcategory").append(
`<option value="${s.sub_category_id}">
${s.subcategory}
</option>`
);

}

});

});


/*
LOAD STATES
*/

$(document).ready(function(){

$.ajax({

url:"<?php echo BASE_URL ?>api/providers/states.php",
headers:headers,
dataType:"json",

success:function(res){

if(res.status !== "success") return;

$("#state").html('<option value="">Select State</option>');

res.data.forEach(function(state){

$("#state").append(
`<option value="${state.id}">${state.name}</option>`
);

});

}

});

});


/*
LOAD CITIES
*/

$("#state").on("change", function(){

let state_id = $(this).val();

$("#city").html('<option value="">Select City</option>');
$("#pincode").html('');

if(!state_id) return;

$.ajax({

url:"<?php echo BASE_URL ?>api/providers/cities.php",
headers:headers,
dataType:"json",
data:{state_id:state_id},

success:function(res){

if(res.status !== "success") return;

res.data.forEach(function(city){

$("#city").append(
`<option value="${city.id}">${city.name}</option>`
);

});

}

});

});


/*
LOAD AREAS
*/

$("#city").on("change", function(){

let city_id = $(this).val();

$("#pincode").html('');

if(!city_id) return;

$.ajax({

url:"<?php echo BASE_URL ?>api/providers/pincodes.php",
headers:headers,
dataType:"json",
data:{city_id:city_id},

success:function(res){

if(res.status !== "success") return;

res.data.forEach(function(area){

$("#pincode").append(
`<option value="${area.id}">
${area.pincode} - ${area.area_name}
</option>`
);

});

}

});

});


/*
ADD AREAS
*/

$("#addAreaBtn").click(function(){

let category=$("#category").val();
let sub=$("#subcategory").val();
let areas=$("#pincode").val();

if(!category || !sub || !areas){

alert("Select service and areas");
return;

}

areas.forEach(function(area){

$.ajax({

url:"<?php echo BASE_URL ?>api/providers/add-service-area.php",
method:"POST",
headers:headers,

data:{
category_id:category,
sub_category_id:sub,
pincode_id:area
}

});

});

location.reload();

});


/*
REMOVE AREA
*/

$(".removeArea").click(function(){

if(!confirm("Remove service area?")) return;

let id=$(this).data("id");

$.ajax({

url:"<?php echo BASE_URL ?>api/providers/remove-service-area.php",
method:"POST",
headers:headers,

data:{id:id},

success:function(){
location.reload();
}

});

});

</script>


<?php include '../admin/partials/layouts/layoutBottom.php' ?>