{% extends 'base.html' %}
{% load static %}

{% block content %}
      <header class="bg-primary text-white text-center py-5">
        <div class="container">
            <h1>Welcome to Sahara</h1>
            <p>Your one-stop platform for elder cure serviecs.</p>
        </div>
    </header>

    <div class="search-bar">
        <input type="text" class="form-control" name=search id=search placeholder="Search Your Caretaker...">
        <button class="btn btn-primary ms-1" onclick=sendSearch()>Search</button>
    </div>

    <section class="container my-5">
        <div class="row">
            <div class="col-md-3">
                <div class="category-bar">
                    <h4>Services</h4>
                    <ul class="list-unstyled">
                    {% for service in services %}
                        <li><a href="{% url 'home' %}?category={{ service.id }}" class="category-link">{{ service.name }}</a></li>
                    {% endfor %}
                    </ul>
                </div>
            </div>
            
            <div class="col-md-9">
                <h2 class="text-center mb-4">Available Caretakers</h2>
                <div class="row row-cols-1 row-cols-md-3 g-4">

                {% for user in service_providers %}
                    <div class="col">
                        <div class="profile-card">
                            {% if user.profile %}
                                <img src="{{ user.profile.url }}" alt="{{ user.first_name }} {{ user.last_name }}'s Image" class="img-fluid">
                            {% else %}
                                <img src="{% static 'img/dummypic.png' %}" alt="Avatar Image" class="img-fluid">
                            {% endif %}

                            <div class="card-body">
                                <h5 class="card-title">{{ user.first_name|capfirst }} {{ user.last_name|capfirst }}</h5>
                                <p class="card-text">Bio: {{ user.bio }}</p>
                                <p class="availability">Member Since: {{ user.member_since|date:"F j, Y" }}</p>
                                <div class="d-flex align-items-center">
                                    <p class="price mb-0">Rs. {{ user.price|floatformat:2 }}</p>
                                    <!-- Hire button -->
                                    <button class="btn btn-primary btn-sm ms-auto" data-bs-toggle="modal" data-bs-target="#hireModal" data-id="{{user.id}}" data-name="{{ user.first_name }} {{ user.last_name }}" data-email="{{ user.email }}" data-contact = "{{ user.phone_number }}" data-bio="{{ user.bio }}" data-price="{{ user.price|floatformat:2 }}" data-id="{{ user.id }}">Hire</button>
                                </div>
                            </div>
                        </div>
                    </div>
                {% empty %}
                    <div class="mx-auto">Oops! No Caretaker Found Currently.</div>
                {% endfor %}

                </div>
            </div>
        </div>
    </section>

    <!-- Modal -->
    <div class="modal fade" id="hireModal" tabindex="-1" aria-labelledby="hireModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="hireModalLabel">Hire Caretaker</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="hireForm" method="POST">
                    {% csrf_token %}
                        <div class="mb-3">
                            <label for="caretakerName" class="form-label">Caretaker Name</label>
                            <input type="text" class="form-control" name="caretakerName" id="caretakerName" disabled>
                        </div>
                        <div class="mb-3">
                            <label for="caretakerBio" class="form-label">Bio</label>
                            <textarea class="form-control" id="caretakerBio" name="caretakerBio" rows="3" disabled></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="caretakeremail" class="form-label">Email Address</label>
                            <textarea class="form-control" id="caretakeremail" name = "caretakeremail" rows="3" disabled></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="caretakercontact" class="form-label">Contact no</label>
                            <textarea class="form-control" id="caretakercontact" name="caretakercontact" rows="3" disabled></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="caretakerPrice" class="form-label">Price</label>
                            <input type="text" class="form-control" id="caretakerPrice" name="caretakercontact" price="caretakercontact">
                        </div>
                        <div class="mb-3">
                            <label for="serviceHour" class="form-label">Hours to Hire</label>
                            <input type="number" class="form-control" id="serviceHour" name="serviceHour">
                        </div>
                        <div class="mb-3">
                            <label for="service" class="form-label">Service </label>
                            <select class="form-control" id="caretakerservice" name="caretakerservice">
                            {% for service in services %}
                            <option value={{service.id}}>{{service.name}}</option>
                            {% endfor %}
                            </select>
                        </div>
                        <div class="mb-3">
                            <input type="hidden" class="form-control" id="caretakerid" name="caretakerid" disabled>
                        </div>
                        <a "btn btn-primary" href="javascript:sendRequest()"  >Send Request</a>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    <script>
        // Handle the modal data population
        const hireModal = document.getElementById('hireModal');
        hireModal.addEventListener('show.bs.modal', function (event) {
            // Button that triggered the modal
            const button = event.relatedTarget;

            // Extract information from data-* attributes
            const name = button.getAttribute('data-name');
            const bio = button.getAttribute('data-bio');
            const price = button.getAttribute('data-price');
            const serviceId = button.getAttribute('data-id');
            const contact = button.getAttribute('data-contact');
            const email = button.getAttribute('data-email');
            const id = button.getAttribute('data-id');

            document.getElementById('caretakerName').value = name;
            document.getElementById('caretakerBio').value = bio;
            document.getElementById('caretakerPrice').value = price;
            document.getElementById('caretakeremail').value = email;
            document.getElementById('caretakercontact').value = contact;
            document.getElementById('caretakerid').value = id;
        });



const sendRequest = async () => {
    try {
        const price = document.getElementById('caretakerPrice').value;
        const serviceHour = document.getElementById('serviceHour').value;
        const serviceProviderId = document.getElementById('caretakerid').value;
        const caretakerservice = document.getElementById('caretakerservice').value;

        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
        const hireUrl = "{% url 'hire' %}";
        const initiatorId = "{{ request.user.id }}";

        const response = await fetch(hireUrl, {
            method: "POST",
            headers: {
                "Content-Type": "application/json; charset=UTF-8",
                "X-CSRFToken": csrfToken,
            },
            body: JSON.stringify({
                price: price,
                initiator: initiatorId,
                serviceProvider: serviceProviderId,
                serviceHour: serviceHour,
                caretakerservice: caretakerservice,
            })
        });

        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(errorText);
        }

        const data = await response.json();
        console.log('Request was successful:', data);
        window.location.href = window.location.href;

    } catch (error) {
        console.error('There was an error with the request:', error.message);
        alert('There was an error with your request: ' + error.message);
    }
};


        const sendSearch = () => {
    let url = window.location.href;
    const searchTerm = document.getElementById("search").value;
    url = url.split('?')[0] + "?search=" + encodeURIComponent(searchTerm);
    window.location.href = url;
}
    </script>

{% endblock %}
