{{>header}}
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>

<title>Community Profile</title>
<section class="content">
    <div class="container-fluid">
        <div class="row pb-2 pr-2 pl-2">
            <div class="col-md-12">
                <div class="card card-primary card-outline mt-3">
                    <div class="card-header" style="background-color: white; color:#4D6C1F;">
                        <h4><b style="font-weight:bolder; color:  #4B0F77 !important ">Community Profile</b></h4>
                    </div>
                </div>
            </div>
            <div class="col-md-3 ">
                <div class="card card-primary card-outline">
                    <div class="card-body box-profile">
                        <div class="text-center">
                            <img class="img-fluid" src="/{{vendorExists.profilePicture}}" alt="Profile picture"
                                onerror="this.onerror=null;this.src='/admin/images/dummy.png'">
                        </div><br>
                        <ul class="list-group list-group-unbordered mb-3">
                            <li class="list-group-item">
                                <b>Community Name</b>
                                <p class="float-right">
                                    <b>{{vendorExists.communityName}}</b>
                                </p>
                            </li>
                            <li class="list-group-item">
                                <b>Email</b>
                                {{!-- <p class="float-right"> --}}
                                <p class="float-right text-truncate"
                                    style="max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                                    <b>{{vendorExists.email}}</b>
                                </p>
                            </li>
                            <li class="list-group-item">
                                <b>Mobile</b>
                                <p class="float-right">
                                    <b>{{vendorExists.phone}}</b>
                                </p>
                            </li>
                            <li class="list-group-item">
                                <b>Status</b>
                                <p class="float-right">
                                    <b>{{vendorExists.status}}</b>
                                </p>
                        </ul>
                    </div>
                </div>
            </div>
            <div class="col-md-9">
                <div class="card">
                    <div class="card-header p-2">
                        <ul class="nav nav-pills">
                            <li class="nav-item"><a class="nav-link active" href="#details"
                                    data-toggle="tab">Details</a>
                            </li>
                            <li class="nav-item"><a class="nav-link" href="#allProducts" data-toggle="tab">Products</a>
                            </li>
                        </ul>
                    </div>
                    <div class="card-body">
                        <div class="tab-content">
                            <div class="tab-pane active" id="details">
                                <div class="row">
                                    <div class="col-md-12">
                                        <form id="vendorForm" action="/admin/v1/updatevendor/{{vendorExists._id}}"
                                            onsubmit="return validateCategoriesAndAddresses()" method="post"
                                            enctype="multipart/form-data">
                                            <div class="form-group">
                                                <div class="row">
                                                    <div class="col-md-4">
                                                        <label>Community Name</label>
                                                        <input type="text" class="form-control" name="storeName"
                                                            placeholder="Enter Store Name" pattern="^[A-Za-z ]{3,50}$"
                                                            title="Name must be 3–50 letters long, only alphabets and spaces (no numbers or special characters), and cannot start or end with a space."
                                                            value="{{vendorExists.communityName}}">
                                                    </div>
                                                    <div class="col-md-4">
                                                        <label>Vendor Name</label>
                                                        <input type="text" class="form-control" name="vendorName"
                                                            placeholder="Enter Vendor Name" pattern="^[A-Za-z ]{3,50}$"
                                                            title="Name must be 3–50 letters long, only alphabets and spaces (no numbers or special characters), and cannot start or end with a space."
                                                            value="{{vendorExists.vendorName}}">
                                                    </div>
                                                    <div class="col-md-4">
                                                        <label>Email</label>
                                                        <input type="text" class="form-control" name="email"
                                                            placeholder="Enter Email Adress"
                                                            value="{{vendorExists.email}}" oninput="validateEmail(this)"
                                                            onblur="this.value = this.value.trim(); ">
                                                        <small id="update-emailError"
                                                            style="color: red; display: none;">
                                                            Please enter a valid email address (e.g.,
                                                            example@domain.com).
                                                        </small>

                                                    </div>

                                                </div><br>
                                                <div class="row">
                                                    <div class="col-md-4">
                                                        <label>Mobile Number</label>
                                                        <input type="text" class="form-control" name="phone"
                                                            placeholder="Enter Mobile Number"
                                                            value="{{vendorExists.phone}}" pattern="^[6-9]\d{9}$"
                                                            title="Phone number must be exactly 10 digits and start with 6, 7, 8, or 9.">
                                                    </div>
                                                    <div class="col-md-4">
                                                        <label>Change Password</label>
                                                        <div class="input-group">
                                                            <input type="password" class="form-control" id="password"
                                                                pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&#.])[A-Za-z\d@$!%*?&#.]{8,}$"
                                                                title="Password must be at least 8 characters, include uppercase, lowercase, number, and special character."
                                                                name="password" placeholder="Enter Password">
                                                            <button type="button" class="btn btn-primary"
                                                                onclick="togglePasswordVisibility('password', this)"
                                                                style="background-color: aliceblue; color:black">
                                                                <i class="fa fa-eye" id="toggleEye"></i>
                                                            </button>
                                                        </div>
                                                        <p id="passwordP" style="color:red !important;"></p>
                                                    </div>
                                                    <div class="col-md-4">
                                                        <label>Profile Picture</label>
                                                        <input type="file" class="form-control" accept="image/*"
                                                            id="picture" name="picture">
                                                    </div>
                                                </div>
                                                {{!-- <div class="row">
                                                    <div class="col-md-4">
                                                        <label class="col-form-label">Food & Ecommerce Range</label>
                                                        <input type="number" class="form-control" min="1" max="100" step="0.01"
                                                            name="foodAndEcommerceRange"
                                                            placeholder="Enter Food and Ecommerce delivery range"
                                                            value="{{vendorExists.foodAndEcommerceRange}}">
                                                    </div>
                                                    <div class="col-md-4">
                                                        <label class="col-form-label">Grocery Range</label>
                                                        <input type="number" class="form-control" name="groceryRange" min="1" max="100" step="0.01"
                                                            placeholder="Enter Grocery range"
                                                            value="{{vendorExists.groceryRange}}">
                                                    </div>
                                                    <div class="col-md-4">
                                                        <div class="form-group">
                                                            <label class="col-form-label">Select City <span
                                                                    class="text-danger">*</span></label>
                                                            <select name="cityId" class="selectpicker form-control"
                                                                data-live-search="true" required>
                                                                <option value="{{vendorExists.city._id}}" selected
                                                                    hidden>
                                                                    {{vendorExists.city.cityName}}
                                                                </option> <!-- Important for placeholder -->
                                                                {{#each allCities}}
                                                                <option value="{{this._id}}">{{this.cityName}}</option>
                                                                {{/each}}
                                                            </select>
                                                        </div>
                                                    </div>
                                                </div> --}}
                                                <div class="row">
                                                {{!-- <div class="col-md-3">
                                                    <div class="form-group">
                                                        <label class="col-form-label">Store Type</label>
                                                        <select name="categories" class="selectpicker form-control" data-live-search="true" disabled>
                                                            <option value="" disabled selected hidden> Select Store Type</option> <!-- Important for placeholder -->
                                                            <option value="grocery"  {{#if (includes vendorExists.categories "grocery" )}}selected{{/if}}>Grocery</option>
                                                            <option value="ecommerce" {{#if (includes vendorExists.categories "ecommerce" )}}selected{{/if}}>Ecommerce</option>
                                                            <option value="food" {{#if (includes vendorExists.categories "food" )}}selected{{/if}}>Food</option>
                                                        </select>
                                                    </div>
                                                </div> --}}
                                                 {{!-- <div class="col-md-3" style="display: flex; align-items: center;" id="homeStoreSection">
                                                        <label style="margin-right: 10px;">Home Store</label><br>
                                                        <input type="checkbox" class="status" name="homeStore"
                                                            {{#ifEquals vendorExists.homeStore "Active" }} checked
                                                            {{/ifEquals}} data-on-text="on" data-off-text="off"
                                                            data-on-color="green" data-off-color="red">
                                                    </div> --}}
                                                    {{!-- <div class="col-md-3">
                                                    <div class="form-group">
                                                    <label class="col-form-label">Store Open Time:<span class="text-danger">*</span></label><br>
                                                    <input
                                                        type="time"
                                                        id="event-time"
                                                        name="storeOpenTime"
                                                        style="border: 1px solid #ccc; border-radius: 6px; padding: 6px 10px; width: 50%; font-size: 18px;"
                                                        value="{{vendorExists.storeOpenTime}}"
                                                        required
                                                    >
                                                    </div>
                                                </div> --}}
                                                {{!-- <div class="col-md-3">
                                                    <div class="form-group">
                                                    <label class="col-form-label">Store Close Time:<span class="text-danger">*</span></label><br>
                                                    <input
                                                        type="time"
                                                        id="event-time"
                                                        name="storeCloseTime"
                                                        style="border: 1px solid #ccc; border-radius: 6px; padding: 6px 10px; width: 50%; font-size: 18px;"
                                                        value="{{vendorExists.storeCloseTime}}"
                                                        required
                                                    >
                                                    </div>
                                                </div> --}}
                                                </div>

                                                <div class="row">
                                                            <div class="col-md-3">
                                                                <div class="form-group">
                                                                        <label for="storeAddress" class="form-label">Store
                                                                Address</label>
                                                            <input type="text" class="form-control" name="storeAddress"
                                                                id="storeAddress" minlength="3" maxlength="500"
                                                                placeholder="Enter Store Address"
                                                                value="{{vendorExists.address}}">
                                                                </div>
                                                            </div>
                                                            <!-- Latitude & Longitude -->
                                                            {{!-- <div class="mt-2">
                                                                <label for="latitude"
                                                                    class="form-label">Latitude</label>
                                                                <input type="text" class="form-control" name="latitude"
                                                                    id="latitude" readonly>

                                                                <label for="longitude"
                                                                    class="form-label mt-2">Longitude</label>
                                                                <input type="text" class="form-control" name="longitude"
                                                                    id="longitude" readonly>
                                                            </div> --}}
                                                            <div class="col-md-3">
                                                                <div class="form-group">
                                                                    <label class="form-label">Status</label>
                                                                <select name="status" class="form-control">
                                                                    <option value="Active" {{#if (eql
                                                                        vendorExists.status "Active" )}}selected{{/if}}>
                                                                        Active</option>
                                                                    <option value="Inactive" {{#if (eql
                                                                        vendorExists.status "Inactive"
                                                                        )}}selected{{/if}}>
                                                                        Inactive</option>
                                                                </select>
                                                                </div>
                                                            </div>
                                                                <div class="col-md-3">
                                                                    <div class="form-group">
                                                                        <label class="form-label">Store Status</label>
                                                                <select name="storeStatus" class="form-control">
                                                                    <option value="Open" {{#if (eql
                                                                        vendorExists.storeStatus "Open" )}}selected{{/if}}>
                                                                        Open</option>
                                                                    <option value="Closed" {{#if (eql
                                                                        vendorExists.storeStatus "Closed"
                                                                        )}}selected{{/if}}>
                                                                        Closed</option>
                                                                </select>
                                                                    </div>
                                                                </div>
                                                    {{!-- <div class="col-md-6">
                                                        <label class="form-label">Select Location</label>
                                                        <div id="map"
                                                            style="height: 300px; width: 100%; border:1px solid #ccc; border-radius:10px;">
                                                        </div>
                                                    </div> --}}
                                                </div>
                                            </div><br>
                                            <div class="form-group">
                                                <button type="submit"
                                                    class="saveButton btn btn-info col-md-4 offset-md-4 btn-block d-flex justify-content-center">Update</button>
                                            </div>
                                            <div class="form-group d-flex justify-content-center">
                                                <a href="javascript:void(0);" data-bs-toggle="modal"
                                                    data-id="{{vendorExists._id}}" data-bs-target="#deleteModal"
                                                    class="btn btn-danger col-md-4 btn-block">
                                                    Delete
                                                </a>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            <div class="tab-pane" id="allProducts">
                                <div class="col-sm-12 table-responsive">
                                    <table id="example145" class="table table-bordered table-striped" aria-describedby="example1_info">
                                        <thead>
                                            <tr>
                                                <th class="sorting" tabindex="0" aria-controls="example1">S.No</th>
                                                <th class="sorting" tabindex="0" aria-controls="example1">Product Id
                                                </th>
                                                <th class="sorting" tabindex="0" aria-controls="example1">Product Name
                                                </th>
                                                <th class="sorting" tabindex="0" aria-controls="example1">Price</th>
                                                <th class="sorting" tabindex="0" aria-controls="example1">Discount%</th>
                                                <th class="sorting" tabindex="0" aria-controls="example1">Stock</th>
                                                <th class="sorting" tabindex="0" aria-controls="example1">Category</th>
                                                <th class="sorting" tabindex="0" aria-controls="example1">Availability
                                                </th>
                                                <th class="sorting" tabindex="0" aria-controls="example1">Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div><!-- /.card-body -->
            </div>
            <!-- /.card -->
        </div>
    </div>
    </div>
</section>

<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 style="color: black; font-weight: 480;">Are you sure you want to delete this?</h4>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">No</button>
                <a href="" id="deleteBannerLink" type="button" class="btn btn-danger">Yes</a>
            </div>
        </div>
    </div>
</div>
<script>
  $(document).ready(function () {
   $('#example145').DataTable({
      serverSide: true,
      ajax: {
        url: `/admin/v1/single-vendor-products/{{vendorExists._id}}`,  // 👈 your new route
        type: 'GET',
         data: function(d) {
      return {
        start: d.start,
        length: d.length,
        draw: d.draw,
        searchText: d.search.value // rename for CloudFront safety
      };
    }
      },
      pageLength: 10,
      lengthMenu: [10, 25, 50, 100],
      columns: [
        {
          data: null,
          render: function (data, type, row, meta) {
            return meta.row + meta.settings._iDisplayStart + 1; // S.No across pages
          }
        },
        { data: 'productId', title: 'Product Id', defaultContent: '' },
        { data: 'productName', title: 'Product Name', defaultContent: '' },
        {
          data: 'price',
          title: 'Price',
          render: function (data, type, row) {
            return `₹${parseFloat(data || 0)}`;
          }
        },
        {
          data: 'discount',
          title: 'Discount',
          render: function (data) {
            return data ? `${data}` : '0';
          }
        },
        { data: 'stock', title: 'stock', defaultContent: '' },
        { data: 'categoryName', title: 'Category', defaultContent: '' },
        { data: 'availability', title: 'Availability', defaultContent: '' },
        {
          data: '_id',
          title: 'Action',
          orderable: false,
          render: function (id, type, row) {
            return `
              <div class="actions d-flex justify-content-start align-items-center">
                <a href="/admin/v1/singleproduct/${id}" class="btn btn-sm btn-info me-1" title="View">
                  <i class="fas fa-eye"></i>
                </a>
              </div>
            `;
          }
        }
      ]
    });

    // Optional: enhance fuzzy search
    $.fn.dataTable.ext.search.push(function (settings, data) {
      const searchValue = table.search().trim().toLowerCase().replace(/\s+/g, '');
      if (!searchValue) return true;
      return data.some(cell =>
        cell.toString().toLowerCase().replace(/\s+/g, '').includes(searchValue)
      );
    });

    // Redraw table on input
    $('#example22_filter input').on('input', function () {
      table.draw();
    });
  });
</script>
<script>
    let map, marker;

    document.addEventListener("DOMContentLoaded", () => {
        // Use vendor's saved coordinates, or fallback to India
        const vendorLat = parseFloat("{{vendorExists.latitude}}") || 20.5937;
        const vendorLng = parseFloat("{{vendorExists.longitude}}") || 78.9629;
        const zoomLevel = ("{{vendorExists.latitude}}" && "{{vendorExists.longitude}}") ? 15 : 5;

        map = L.map('map').setView([vendorLat, vendorLng], zoomLevel);

        // Add OpenStreetMap tiles
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 19,
            attribution: '© OpenStreetMap contributors'
        }).addTo(map);

        // Place existing marker if vendor has saved location
        if ("{{vendorExists.latitude}}" && "{{vendorExists.longitude}}") {
            marker = L.marker([vendorLat, vendorLng]).addTo(map);
            document.getElementById("latitude").value = vendorLat;
            document.getElementById("longitude").value = vendorLng;
        }

        // On click → move marker + update inputs
        map.on("click", function (e) {
            const lat = e.latlng.lat.toFixed(6);
            const lng = e.latlng.lng.toFixed(6);

            if (marker) {
                marker.setLatLng(e.latlng);
            } else {
                marker = L.marker(e.latlng).addTo(map);
            }

            document.getElementById("latitude").value = lat;
            document.getElementById("longitude").value = lng;
        });
    });
</script>

<script>
    function validateEmail(input) {
        input.value = input.value.toLowerCase();
        /*
                const allowedDomains = [
                    '.com', '.net', '.org', '.edu', '.gov', '.mil', '.int', '.co', '.io',
                    '.us', '.uk', '.ca', '.in', '.au', '.de', '.jp', '.cn', '.ru', '.br',
                    '.tech', '.biz', '.info', '.xyz', '.online', '.store', '.ai', '.app', '.dev',
                    '.health', '.law', '.news', '.music', '.bank', '.design', '.photography',
                    '.media', '.finance', '.marketing', '.consulting', '.solutions', '.digital',
                    '.agency', '.ventures', '.guru', '.expert', '.club'
                ];
        */
        const email = input.value.trim();
        const errorElement = input.parentElement.querySelector("small");


        const emailRegex = /^[a-zA-Z0-9](?!.*[._%+-]{2})[a-zA-Z0-9._%+-]*[a-zA-Z0-9]@[a-zA-Z0-9]+\.[a-zA-Z0-9]+$/;
        const isFormatValid = emailRegex.test(email);

        // Extract domain extension
        const domain = email.substring(email.lastIndexOf('.')).toLowerCase();
        //const isDomainValid = allowedDomains.includes(domain);

        if (!isFormatValid) {
            errorElement.style.display = 'block';
            isValidEmail = false;
        } else {
            errorElement.style.display = 'none';
            isValidEmail = true;
        }

        checkFormValidity();
    }
</script>
<script>
    function toggleStoreAddressField() {
        const groceryCheck = document.getElementById('groceryCheck');
        const ecommerceCheck = document.getElementById('ecommerceCheck');
        const foodCheck = document.getElementById('foodCheck');
        const storeAddressInput = document.getElementById('storeAddress');

        // Pre-check based on vendor categories (without disabling)
        if (vendorCategories.includes('grocery')) groceryCheck.checked = true;
        if (vendorCategories.includes('ecommerce')) ecommerceCheck.checked = true;
        if (vendorCategories.includes('food')) foodCheck.checked = true;

        // Show address field if any category is selected
        const anyChecked = groceryCheck.checked || ecommerceCheck.checked || foodCheck.checked;
        document.getElementById('address-field').style.display = anyChecked ? 'block' : 'none';

        // Pre-fill storeAddress by priority: food > grocery > ecommerce
        if (foodCheck.checked) {
            storeAddressInput.value = vendorFoodAddress || '';
        } else if (groceryCheck.checked) {
            storeAddressInput.value = vendorGroceryAddress || '';
        } else if (ecommerceCheck.checked) {
            storeAddressInput.value = vendorEcomAddress || '';
        } else {
            storeAddressInput.value = '';
        }
    }

    // Run on page load
    window.onload = toggleStoreAddressField;

    // Update dynamically when checkboxes change
    ['groceryCheck', 'ecommerceCheck', 'foodCheck'].forEach(id => {
        document.getElementById(id).addEventListener('change', toggleStoreAddressField);
    });
</script>
<script>
    document.addEventListener("DOMContentLoaded", function () {
        const categoryCheckboxes = document.querySelectorAll('input[name="categories"]');
        const categoryError = document.getElementById("categoryError");
        const form = document.querySelector("form"); // adjust if your form has a specific id
        function validateCategories() {
            const checkedCount = document.querySelectorAll('input[name="categories"]:checked').length;
            if (checkedCount === 0) {
                categoryError.style.display = "block";
                return false;
            } else {
                categoryError.style.display = "none";
                return true;
            }
        }
        // Prevent unchecking all checkboxes
        categoryCheckboxes.forEach(cb => {
            cb.addEventListener("change", function (e) {
                const checkedCount = document.querySelectorAll('input[name="categories"]:checked').length;
                if (checkedCount === 0) {
                    e.target.checked = true; // re-check the one just unchecked
                    categoryError.style.display = "block";
                } else {
                    categoryError.style.display = "none";
                }
            });
        });

        // Validate on submit
        form.addEventListener("submit", function (e) {
            if (!validateCategories()) {
                e.preventDefault();
            }
        });
    });
</script>
<script>
    function togglePasswordVisibility(inputId, toggleButton) {
        const input = document.getElementById(inputId);
        const icon = toggleButton.querySelector("i");

        if (input.type === "password") {
            input.type = "text";
            icon.classList.remove("fa-eye");
            icon.classList.add("fa-eye-slash");
        } else {
            input.type = "password";
            icon.classList.remove("fa-eye-slash");
            icon.classList.add("fa-eye");
        }
    }
</script>
<script>
    document.addEventListener("DOMContentLoaded", () => {
        // Select all disabled input fields
        document.querySelectorAll("input[disabled], input[readonly]").forEach((input) => {
            if (!input.value.trim()) {
                input.value = "N/A";
            }
        });
        document.querySelectorAll("p b").forEach((bTag) => {
            if (!bTag.textContent.trim()) {
                bTag.textContent = "N/A"; // Set "N/A" if empty
            }
        });
    });
</script>

<script>
    $(document).ready(function () {
        $('#deleteModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget);
            var bannerId = button.data('id');
            var modal = $(this);
            modal.find('#deleteBannerLink').attr('href', '/admin/v1/deletevendor/' + bannerId);
        });
    });
</script>

{{>footer}}