<script>

	function fetchActs(user_id , beneficiary_id){
		// Fetch acts
		$.ajax({
			url: '<?= base_url('NanoHealthController/getActs')?>',
			type: 'POST',
			dataType: 'json',
			data: {
				"network_id": network_id, "user_id": user_id, "beneficiary_id": beneficiary_id,
			},
			success: function (data) {
				if(data.status === 200){
					acts = data.response
					$('#patient-details').show();
				}else{
					toastr.error(data.error , "<?= $this->lang->line('request_error')?>");
				}
			},
			error: function (resultat, statut, error) {
				console.log(resultat + " " + error);
				toastr.error("<?= $this->lang->line('error_message')?>", "<?= $this->lang->line('request_error')?>");
			}
		});
	}

	function getActsOptions(selectedValue , type) {
		var actsOptions = '';
		acts.forEach(function (a) {
			if(type === a.type) {
				var selected = a.id === parseInt(selectedValue) ? 'selected' : '';
				actsOptions += (`<option value=${a.id} ${selected} data-amount=${a.amount} > ${a.name} </option>`);
			}
		})
		return actsOptions;
	}

	function calculatePrestationsAmount(){
		$('#amount').on('input',fetchPrestationsAmount)
		$('#fees').on('input',fetchPrestationsAmount)
	}

	function fetchPrestationsAmount(){
		var amount = parseFloat($("#amount").val());
		var fees = parseFloat($("#fees").val());
		fees = isNaN(fees) ? 0 : fees;
		var care_condition = $('#sheet-form').find('select[name="care_condition"]').val();
		if(isNaN(amount + fees)){
			$('#moderator-ticket').val('');
			$('#insurance-amount').val('');
		}else{
			$.ajax({
				url: '<?= base_url('NanoHealthController/calculateHealthCareSheetPerformancesAmount')?>',
				type: 'POST',
				dataType: 'json',
				data: {
					"network_id" : network_id, "amount": (amount + fees), "care_condition": care_condition
				},
				success: function (data) {
					if(data.status === 200){
						$('#moderator-ticket').val(data.response.moderator_ticket);
						$('#insurance-amount').val(data.response.insurance_amount);
					}else{
						toastr.error(data.error , "<?= $this->lang->line('request_error')?>");
					}
				},
				error: function (resultat, statut, error) {
					console.log(resultat + " " + error);
					toastr.error("<?= $this->lang->line('error_message')?>", "<?= $this->lang->line('request_error')?>");
				}
			});
		}
	}

	function autoFetchPrestationAmount(){
		console.log('auto fect')
		// Definir le montant du 1er acte selectionné
		let amount =  parseFloat($('#act').find(":selected").data('amount'))
		if(!isNaN(amount)) {
			$("#amount").attr('disabled', true).val(amount).trigger('input');
		}

		$('#act').on('change',function () {
			let amount =  parseFloat($(this).find(":selected").data('amount'))
			if(!isNaN(amount)){
				$("#amount").attr('disabled',true).val(amount).trigger('input');
			}else{
				$("#amount").attr('disabled',false).val(null);
			}
			console.log(amount)
		})
	}

</script>
