{% extends "base.html" %}
{% load i18n %}

{% block title %}{% trans "My Profile" %} - {{ app_settings.app_name|default:"MASAR CARGO" }}{% endblock %}

{% block breadcrumbs %}
<div class="breadcrumb-container">
    <div class="container">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0">
                <li class="breadcrumb-item"><a href="{% url 'home' %}">{% trans "Home" %}</a></li>
                <li class="breadcrumb-item active" aria-current="page">{% trans "My Profile" %}</li>
            </ol>
        </nav>
    </div>
</div>
{% endblock %}

{% block content %}
<div class="container my-5">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card shadow-sm border-0">
                <div class="card-header bg-primary text-white py-3">
                    <h4 class="mb-0"><i class="fa-solid fa-user-edit me-2"></i>{% trans "Edit Profile" %}</h4>
                </div>
                <div class="card-body p-4">
                    <form method="post" enctype="multipart/form-data" id="profileForm">
                        {% csrf_token %}
                        {{ form.email_verified }}
                        {{ form.phone_verified }}
                        
                        <div class="text-center mb-4">
                            {% if profile.profile_picture %}
                                <img src="{{ profile.profile_picture.url }}" alt="{{ user.username }}" class="rounded-circle img-thumbnail mb-3" style="width: 150px; height: 150px; object-fit: cover;">
                            {% else %}
                                <div class="rounded-circle bg-light d-inline-flex align-items-center justify-content-center mb-3" style="width: 150px; height: 150px; border: 2px dashed #ddd;">
                                    <i class="fa-solid fa-user fa-4x text-muted"></i>
                                </div>
                            {% endif %}
                            <p class="text-muted small">{% trans "Update your profile picture" %}</p>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">{% trans "First Name" %}</label>
                                {{ form.first_name }}
                                {% if form.first_name.errors %}
                                    <div class="text-danger small">{{ form.first_name.errors }}</div>
                                {% endif %}
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">{% trans "Last Name" %}</label>
                                {{ form.last_name }}
                                {% if form.last_name.errors %}
                                    <div class="text-danger small">{{ form.last_name.errors }}</div>
                                {% endif %}
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-bold">{% trans "Email" %}</label>
                            <div class="input-group">
                                {{ form.email }}
                                <button class="btn btn-outline-secondary" type="button" id="verifyEmailBtn">
                                    <span id="emailStatus">
                                        {% if profile.email_verified %}
                                            <i class="fa-solid fa-check-circle text-success"></i> {% trans "Verified" %}
                                        {% else %}
                                            {% trans "Verify" %}
                                        {% endif %}
                                    </span>
                                </button>
                            </div>
                            {% if form.email.errors %}
                                <div class="text-danger small">{{ form.email.errors }}</div>
                            {% endif %}
                        </div>

                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label fw-bold">{% trans "Country Code" %}</label>
                                {{ form.country_code }}
                                {% if form.country_code.errors %}
                                    <div class="text-danger small">{{ form.country_code.errors }}</div>
                                {% endif %}
                            </div>
                            <div class="col-md-8 mb-3">
                                <label class="form-label fw-bold">{% trans "Phone Number" %}</label>
                                <div class="input-group">
                                    {{ form.phone_number }}
                                    <button class="btn btn-outline-secondary" type="button" id="verifyPhoneBtn">
                                        <span id="phoneStatus">
                                            {% if profile.phone_verified %}
                                                <i class="fa-solid fa-check-circle text-success"></i> {% trans "Verified" %}
                                            {% else %}
                                                {% trans "Verify" %}
                                            {% endif %}
                                        </span>
                                    </button>
                                </div>
                                {% if form.phone_number.errors %}
                                    <div class="text-danger small">{{ form.phone_number.errors }}</div>
                                {% endif %}
                            </div>
                        </div>

                        <div class="mb-4">
                            <label class="form-label fw-bold">{% trans "Profile Picture" %}</label>
                            {{ form.profile_picture }}
                            {% if form.profile_picture.errors %}
                                <div class="text-danger small">{{ form.profile_picture.errors }}</div>
                            {% endif %}
                        </div>

                        <hr>

                        <div class="d-flex justify-content-between align-items-center">
                            <a href="{% url 'dashboard' %}" class="btn btn-outline-secondary">
                                <i class="fa-solid fa-arrow-left me-1"></i> {% trans "Back to Dashboard" %}
                            </a>
                            <button type="submit" class="btn btn-primary px-4" id="saveProfileBtn">
                                <i class="fa-solid fa-save me-1"></i> {% trans "Save Changes" %}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
            
            <div class="card mt-4 shadow-sm border-0">
                <div class="card-body">
                    <h5 class="fw-bold mb-3">{% trans "Account Information" %}</h5>
                    <div class="row small">
                        <div class="col-sm-4 text-muted">{% trans "Username" %}</div>
                        <div class="col-sm-8 mb-2">{{ user.username }}</div>
                        
                        <div class="col-sm-4 text-muted">{% trans "Role" %}</div>
                        <div class="col-sm-8 mb-2">
                            {% if profile.role == 'SHIPPER' %}
                                <span class="badge bg-info">{% trans "Shipper" %}</span>
                            {% elif profile.role == 'TRUCK_OWNER' %}
                                <span class="badge bg-success">{% trans "Truck Owner" %}</span>
                            {% else %}
                                <span class="badge bg-secondary">{{ profile.role }}</span>
                            {% endif %}
                        </div>

                        <div class="col-sm-4 text-muted">{% trans "Subscription" %}</div>
                        <div class="col-sm-8 mb-2">
                            {{ profile.get_subscription_plan_display }}
                            {% if profile.subscription_expiry %}
                                <br><small class="text-muted">{% trans "Expires on:" %} {{ profile.subscription_expiry }}</small>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- OTP Modal -->
<div class="modal fade" id="otpModal" tabindex="-1" aria-labelledby="otpModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="otpModalLabel">{% trans "Enter OTP" %}</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p class="small text-muted" id="otpSentMsg"></p>
        <input type="text" id="otpInput" class="form-control text-center" maxlength="6" placeholder="123456" style="letter-spacing: 5px; font-size: 1.5rem; font-weight: bold;">
        <div id="otpError" class="text-danger small mt-2 d-none"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{% trans "Cancel" %}</button>
        <button type="button" class="btn btn-primary" id="confirmOtpBtn">{% trans "Verify" %}</button>
      </div>
    </div>
  </div>
</div>

{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    console.log("Profile JS loaded");

    const emailInput = document.getElementById('id_email');
    const phoneInput = document.getElementById('id_phone_number');
    const countryCodeInput = document.getElementById('id_country_code');
    const emailVerifiedInput = document.getElementById('id_email_verified');
    const phoneVerifiedInput = document.getElementById('id_phone_verified');
    const verifyEmailBtn = document.getElementById('verifyEmailBtn');
    const verifyPhoneBtn = document.getElementById('verifyPhoneBtn');
    const emailStatus = document.getElementById('emailStatus');
    const phoneStatus = document.getElementById('phoneStatus');
    const saveBtn = document.getElementById('saveProfileBtn');
    
    const otpModalElem = document.getElementById('otpModal');
    if (!otpModalElem) {
        console.error("OTP Modal element not found!");
        return;
    }
    const otpModal = new bootstrap.Modal(otpModalElem);
    const otpInput = document.getElementById('otpInput');
    const confirmOtpBtn = document.getElementById('confirmOtpBtn');
    const otpError = document.getElementById('otpError');
    const otpSentMsg = document.getElementById('otpSentMsg');

    let currentVerificationMethod = '';
    let currentVerificationValue = '';

    const initialEmail = emailInput ? emailInput.value : '';
    const initialPhone = phoneInput ? phoneInput.value : '';
    const initialCountryCode = countryCodeInput ? countryCodeInput.value : '';

    const csrfTokenElem = document.querySelector('[name=csrfmiddlewaretoken]');
    const csrfToken = csrfTokenElem ? csrfTokenElem.value : '';

    function isVerified(val) {
        return val === 'True' || val === 'true' || val === '1';
    }

    function updateSaveButtonState() {
        if (!emailVerifiedInput || !phoneVerifiedInput || !saveBtn) return;
        
        const isEmailVerified = isVerified(emailVerifiedInput.value);
        const isPhoneVerified = isVerified(phoneVerifiedInput.value);
        
        console.log("Status - Email Verified:", isEmailVerified, "Phone Verified:", isPhoneVerified);
        
        // Enable if at least one is verified
        if (isEmailVerified || isPhoneVerified) {
            saveBtn.disabled = false;
        } else {
            saveBtn.disabled = true;
        }
    }

    if (emailInput) {
        emailInput.addEventListener('input', function() {
            if (this.value !== initialEmail) {
                emailVerifiedInput.value = 'False';
                emailStatus.innerHTML = '{% trans "Verify" %}';
                verifyEmailBtn.classList.remove('btn-success');
                verifyEmailBtn.classList.add('btn-outline-secondary');
            } else {
                if ("{{ profile.email_verified|yesno:'true,false' }}" === "true") {
                    emailVerifiedInput.value = 'True';
                    emailStatus.innerHTML = '<i class="fa-solid fa-check-circle text-success"></i> {% trans "Verified" %}';
                }
            }
            updateSaveButtonState();
        });
    }

    if (phoneInput) {
        phoneInput.addEventListener('input', function() {
            if (this.value !== initialPhone) {
                phoneVerifiedInput.value = 'False';
                phoneStatus.innerHTML = '{% trans "Verify" %}';
                verifyPhoneBtn.classList.remove('btn-success');
                verifyPhoneBtn.classList.add('btn-outline-secondary');
            } else {
                if ("{{ profile.phone_verified|yesno:'true,false' }}" === "true" && countryCodeInput.value === initialCountryCode) {
                    phoneVerifiedInput.value = 'True';
                    phoneStatus.innerHTML = '<i class="fa-solid fa-check-circle text-success"></i> {% trans "Verified" %}';
                }
            }
            updateSaveButtonState();
        });
    }

    if (countryCodeInput) {
        countryCodeInput.addEventListener('change', function() {
            if (this.value !== initialCountryCode) {
                phoneVerifiedInput.value = 'False';
                phoneStatus.innerHTML = '{% trans "Verify" %}';
            } else {
                if ("{{ profile.phone_verified|yesno:'true,false' }}" === "true" && phoneInput.value === initialPhone) {
                    phoneVerifiedInput.value = 'True';
                    phoneStatus.innerHTML = '<i class="fa-solid fa-check-circle text-success"></i> {% trans "Verified" %}';
                }
            }
            updateSaveButtonState();
        });
    }

    if (verifyEmailBtn) {
        verifyEmailBtn.addEventListener('click', function() {
            console.log("Verify Email clicked");
            if (isVerified(emailVerifiedInput.value)) {
                console.log("Email already verified");
                return;
            }
            
            const email = emailInput.value;
            if (!email) {
                alert('{% trans "Please enter an email address" %}');
                return;
            }

            verifyEmailBtn.disabled = true;
            const originalHTML = verifyEmailBtn.innerHTML;
            verifyEmailBtn.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';

            fetch("{% url 'send_otp_profile' %}", {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrfToken
                },
                body: JSON.stringify({
                    method: 'email',
                    value: email
                })
            })
            .then(response => {
                if (!response.ok) throw new Error('Network response was not ok');
                return response.json();
            })
            .then(data => {
                verifyEmailBtn.disabled = false;
                verifyEmailBtn.innerHTML = originalHTML;
                if (data.success) {
                    currentVerificationMethod = 'email';
                    currentVerificationValue = email;
                    otpSentMsg.innerText = '{% trans "A code was sent to" %} ' + email;
                    otpInput.value = '';
                    otpError.classList.add('d-none');
                    otpModal.show();
                } else {
                    alert(data.error || '{% trans "Failed to send code" %}');
                }
            })
            .catch(error => {
                console.error("Fetch error:", error);
                verifyEmailBtn.disabled = false;
                verifyEmailBtn.innerHTML = originalHTML;
                alert('{% trans "An error occurred. Please try again." %}');
            });
        });
    }

    if (verifyPhoneBtn) {
        verifyPhoneBtn.addEventListener('click', function() {
            console.log("Verify Phone clicked");
            if (isVerified(phoneVerifiedInput.value)) {
                console.log("Phone already verified");
                return;
            }
            
            const phone = phoneInput.value;
            const countryCode = countryCodeInput.value;
            if (!phone) {
                alert('{% trans "Please enter a phone number" %}');
                return;
            }

            verifyPhoneBtn.disabled = true;
            const originalHTML = verifyPhoneBtn.innerHTML;
            verifyPhoneBtn.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';

            fetch("{% url 'send_otp_profile' %}", {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrfToken
                },
                body: JSON.stringify({
                    method: 'phone',
                    value: phone,
                    country_code: countryCode
                })
            })
            .then(response => {
                if (!response.ok) throw new Error('Network response was not ok');
                return response.json();
            })
            .then(data => {
                verifyPhoneBtn.disabled = false;
                verifyPhoneBtn.innerHTML = originalHTML;
                if (data.success) {
                    currentVerificationMethod = 'phone';
                    currentVerificationValue = phone;
                    otpSentMsg.innerText = '{% trans "A code was sent to WhatsApp number" %} ' + countryCode + phone;
                    otpInput.value = '';
                    otpError.classList.add('d-none');
                    otpModal.show();
                } else {
                    alert(data.error || '{% trans "Failed to send code" %}');
                }
            })
            .catch(error => {
                console.error("Fetch error:", error);
                verifyPhoneBtn.disabled = false;
                verifyPhoneBtn.innerHTML = originalHTML;
                alert('{% trans "An error occurred. Please try again." %}');
            });
        });
    }

    if (confirmOtpBtn) {
        confirmOtpBtn.addEventListener('click', function() {
            const otp = otpInput.value;
            if (otp.length !== 6) {
                otpError.innerText = '{% trans "Please enter a 6-digit code" %}';
                otpError.classList.remove('d-none');
                return;
            }

            confirmOtpBtn.disabled = true;
            const originalHTML = confirmOtpBtn.innerHTML;
            confirmOtpBtn.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';

            fetch("{% url 'verify_otp_profile' %}", {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrfToken
                },
                body: JSON.stringify({
                    method: currentVerificationMethod,
                    value: currentVerificationValue,
                    country_code: countryCodeInput.value,
                    code: otp
                })
            })
            .then(response => {
                if (!response.ok) throw new Error('Network response was not ok');
                return response.json();
            })
            .then(data => {
                confirmOtpBtn.disabled = false;
                confirmOtpBtn.innerHTML = originalHTML;
                if (data.success) {
                    if (currentVerificationMethod === 'email') {
                        emailVerifiedInput.value = 'True';
                        emailStatus.innerHTML = '<i class="fa-solid fa-check-circle text-success"></i> {% trans "Verified" %}';
                    } else {
                        phoneVerifiedInput.value = 'True';
                        phoneStatus.innerHTML = '<i class="fa-solid fa-check-circle text-success"></i> {% trans "Verified" %}';
                    }
                    otpModal.hide();
                    updateSaveButtonState();
                } else {
                    otpError.innerText = data.error || '{% trans "Invalid code" %}';
                    otpError.classList.remove('d-none');
                }
            })
            .catch(error => {
                console.error("Fetch error:", error);
                confirmOtpBtn.disabled = false;
                confirmOtpBtn.innerHTML = originalHTML;
                otpError.innerText = '{% trans "An error occurred. Please try again." %}';
                otpError.classList.remove('d-none');
            });
        });
    }
    
    // Initial check
    updateSaveButtonState();
});
</script>
{% endblock %}