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

{% block title %}{{ page_title }} - ECOLUX Dashboard{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="{% static 'css/modal-responsive.css' %}">
{% endblock %}






// Fonctions pour le modal de création de projet

{% block content %}
<style>
.tinymce-editor {
    visibility: hidden;
}
.tox-promotion {
    display: none !important;
}
</style>  
<!-- TinyMCE Editor -->
<script src="https://cdn.tiny.cloud/1/2fssx32bpsx37bdxan8ya9hcmgo4qhqf2ezoncwafvcldzq2/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
<section class="section is-main-section">
    <div class="level">
        <div class="level-left">
            <div class="level-item">
                <div class="title">
                    <h1 class="title is-5 has-text-ecolux-primary">
                        <span class="icon-text">
                            <span class="icon has-text-ecolux-secondary">
                                <i class="fas fa-project-diagram"></i>
                            </span>
                            <span>{{ page_title }}</span>
                        </span>
                    </h1>
                </div>
            </div>
        </div>
        <div class="level-right">
            <div class="level-item">
                <div class="buttons">
                    <a href="{% url 'app:dashboard_home' %}" class="button is-light">
                        <span class="icon">
                            <i class="fas fa-arrow-left"></i>
                        </span>
                        <span>Retour au tableau de bord</span>
                    </a>
                    {% if user_type == 'DRH' or user_type == 'TECHNICIEN' %}
                    <button class="button is-ecolux-primary" onclick="openCreateProjectModal()">
                        <span class="icon">
                            <i class="fas fa-plus"></i>
                        </span>
                        <span>Nouveau Projet</span>
                    </button>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>

    <!-- Filtres -->
    <div class="card ecolux-card mb-5">
        <div class="card-content">
            <form method="GET" class="field is-grouped">
                <div class="control">
                    <div class="field has-addons">
                        <div class="control">
                            <span class="button is-static ecolux-primary">
                                <i class="fas fa-filter"></i>
                            </span>
                        </div>
                        <div class="control">
                            <div class="select">
                                <select name="status" onchange="this.form.submit()">
                                    <option value="">Tous les statuts</option>
                                    {% for value, label in status_choices %}
                                        <option value="{{ value }}" {% if current_status == value %}selected{% endif %}>
                                            {{ label }}
                                        </option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="control is-expanded">
                    <input class="input" type="text" name="search" placeholder="Rechercher un projet..." 
                           value="{{ search_query }}">
                </div>
                <div class="control">
                    <button type="submit" class="button is-ecolux-primary">
                        <span class="icon">
                            <i class="fas fa-search"></i>
                        </span>
                    </button>
                </div>
                {% if current_status or search_query %}
                <div class="control">
                    <a href="{% url 'app:dashboard_projects_list' %}" class="button is-light">
                        <span class="icon">
                            <i class="fas fa-times"></i>
                        </span>
                        <span>Effacer</span>
                    </a>
                </div>
                {% endif %}
            </form>
        </div>
    </div>

    <!-- Liste des projets -->
    <div class="card ecolux-card">
        <header class="card-header ecolux-primary">
            <p class="card-header-title has-text-ecolux-secondary">
                <span class="icon">
                    <i class="fas fa-list"></i>
                </span>
                Liste des projets
            </p>
        </header>
        <div class="card-content">
            {% if page_obj %}
                {% for project in page_obj %}
                <div class="media" style="border-bottom: 1px solid #f1f3f4; padding-bottom: 1rem; margin-bottom: 1rem;">
                    <div class="media-content">
                        <div class="content">
                            <p>
                                <strong>
                                    <a href="{% url 'app:dashboard_project_detail' project.id %}" class="ecolux-link">
                                        {{ project.title }}
                                    </a>
                                </strong>
                                {% if project.status == 'PLANNING' %}
                                    <span class="tag is-ecolux-secondary is-small">{{ project.get_status_display }}</span>
                                {% elif project.status == 'IN_PROGRESS' %}
                                    <span class="tag is-ecolux-primary is-small">{{ project.get_status_display }}</span>
                                {% elif project.status == 'COMPLETED' %}
                                    <span class="tag is-success is-small">{{ project.get_status_display }}</span>
                                {% elif project.status == 'PAUSED' %}
                                    <span class="tag is-warning is-small">{{ project.get_status_display }}</span>
                                {% else %}
                                    <span class="tag is-light is-small">{{ project.get_status_display }}</span>
                                {% endif %}
                                <br>
                                {{ project.description|striptags|truncatewords:20 }}
                                <br>
                                <small>
                                    <strong class="has-text-ecolux-primary">Client:</strong> {{ project.client.user.get_full_name }}
                                    {% if project.budget %}
                                        &nbsp;|&nbsp;
                                        <strong class="has-text-ecolux-primary">Budget:</strong> {{ project.budget|floatformat:0 }} FCFA
                                    {% endif %}
                                </small>
                                <br>
                                <!-- Informations financières basées sur les activités -->
                                {% if project.budget %}
                                <small>
                                    <span class="icon-text">
                                        <span class="icon has-text-danger">
                                            <i class="fas fa-coins"></i>
                                        </span>
                                        <span>
                                            <strong class="has-text-danger">Dépensé:</strong> 
                                            {{ project.total_spent_from_activities|floatformat:0 }} FCFA
                                        </span>
                                    </span>
                                    &nbsp;|&nbsp;
                                    <span class="icon-text">
                                        <span class="icon has-text-success">
                                            <i class="fas fa-wallet"></i>
                                        </span>
                                        <span>
                                            <strong class="has-text-success">Restant:</strong> 
                                            {{ project.budget_remaining_from_activities|floatformat:0 }} FCFA
                                        </span>
                                    </span>
                                    &nbsp;|&nbsp;
                                    <span class="icon-text">
                                        <span class="icon {% if project.budget_usage_percentage >= 90 %}has-text-danger{% elif project.budget_usage_percentage >= 70 %}has-text-warning{% else %}has-text-info{% endif %}">
                                            <i class="fas fa-chart-pie"></i>
                                        </span>
                                        <span>
                                            <strong>Utilisé:</strong> 
                                            <span class="{% if project.budget_usage_percentage >= 90 %}has-text-danger{% elif project.budget_usage_percentage >= 70 %}has-text-warning{% else %}has-text-info{% endif %}">
                                                {{ project.budget_usage_percentage }}%
                                            </span>
                                        </span>
                                    </span>
                                </small>
                                <br>
                                {% endif %}
                                <small class="has-text-grey">
                                    Créé le {{ project.created_at|date:"d/m/Y à H:i" }}
                                    {% if project.start_date %}
                                        - Début: {{ project.start_date|date:"d/m/Y" }}
                                    {% endif %}
                                    {% if project.end_date %}
                                        - Fin prévue: {{ project.end_date|date:"d/m/Y" }}
                                    {% endif %}
                                </small>
                            </p>
                            
                            <!-- Actions -->
                            <div class="buttons are-small">
                                <a href="{% url 'app:project_activities' project.id %}" class="button is-info is-light">
                                    <span class="icon">
                                        <i class="fas fa-tasks"></i>
                                    </span>
                                    <span>Activités ({{ project.activities.count }})</span>
                                </a>
                                {% if user_type == 'DRH' or user_type == 'TECHNICIEN' or user_type == 'CLIENT' %}
                                <button class="button is-info is-light" onclick="addActivity({{ project.id }})">
                                    <span class="icon">
                                        <i class="fas fa-plus"></i>
                                    </span>
                                    <span>Activité</span>
                                </button>
                                {% endif %}
                                {% if user_type == 'DRH' or user_type == 'TECHNICIEN' %}
                                <button class="button is-ecolux-secondary is-light" onclick="editProject({{ project.id }})">
                                    <span class="icon">
                                        <i class="fas fa-edit"></i>
                                    </span>
                                    <span>Modifier</span>
                                </button>
                                <button class="button is-ecolux-primary is-light" onclick="assignTechnician({{ project.id }})">
                                    <span class="icon">
                                        <i class="fas fa-user-plus"></i>
                                    </span>
                                    <span>Affecter</span>
                                </button>
                                {% endif %}
                                {% if user_type == 'DRH' or user_type == 'ADMIN' %}
                                <button class="button is-danger is-light" onclick="confirmDeleteProject({{ project.id }}, '{{ project.title|escapejs }}')">
                                    <span class="icon">
                                        <i class="fas fa-trash"></i>
                                    </span>
                                    <span>Supprimer</span>
                                </button>
                                {% endif %}
                            </div>
                            
                            <!-- Techniciens assignés -->
                            {% if project.assigned_technicians.count > 0 %}
                            <div class="tags">
                                <span class="tag is-light">Techniciens:</span>
                                {% for tech in project.assigned_technicians.all %}
                                    <span class="tag is-ecolux-primary">
                                        {{ tech.user.get_full_name|default:tech.user.username }}
                                    </span>
                                {% endfor %}
                            </div>
                            {% endif %}
                        </div>
                    </div>
                </div>
                {% endfor %}
            {% else %}
                <div class="notification is-ecolux-primary is-light">
                    <div class="content has-text-centered">
                        <p>
                            <span class="icon is-large">
                                <i class="fas fa-info-circle fa-2x"></i>
                            </span>
                        </p>
                        <p class="title is-5">Aucun projet trouvé</p>
                        <p>
                            {% if current_status or search_query %}
                                Aucun projet ne correspond à vos critères de recherche.
                                <br>
                                <a href="{% url 'app:dashboard_projects_list' %}" class="button is-light mt-3">
                                    Voir tous les projets
                                </a>
                            {% else %}
                                Commencez par créer votre premier projet.
                                {% if user_type == 'DRH' or user_type == 'TECHNICIEN' %}
                                <br>
                                <button class="button is-ecolux-primary mt-3" onclick="openCreateProjectModal()">
                                    <span class="icon">
                                        <i class="fas fa-plus"></i>
                                    </span>
                                    <span>Créer un projet</span>
                                </button>
                                {% endif %}
                            {% endif %}
                        </p>
                    </div>
                </div>
            {% endif %}
        </div>
    </div>

    <!-- Pagination -->
    {% if page_obj.has_other_pages %}
    <nav class="pagination is-centered mt-5" role="navigation" aria-label="pagination">
        {% if page_obj.has_previous %}
            <a class="pagination-previous button is-ecolux-primary" href="?page={{ page_obj.previous_page_number }}{% if current_status %}&status={{ current_status }}{% endif %}{% if search_query %}&search={{ search_query }}{% endif %}">
                <span class="icon">
                    <i class="fas fa-chevron-left"></i>
                </span>
                <span>Précédent</span>
            </a>
        {% endif %}
        
        {% if page_obj.has_next %}
            <a class="pagination-next button is-ecolux-primary" href="?page={{ page_obj.next_page_number }}{% if current_status %}&status={{ current_status }}{% endif %}{% if search_query %}&search={{ search_query }}{% endif %}">
                <span>Suivant</span>
                <span class="icon">
                    <i class="fas fa-chevron-right"></i>
                </span>
            </a>
        {% endif %}
        
        <ul class="pagination-list">
            {% for num in page_obj.paginator.page_range %}
                {% if page_obj.number == num %}
                    <li><a class="pagination-link is-current ecolux-primary">{{ num }}</a></li>
                {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                    <li><a class="pagination-link" href="?page={{ num }}{% if current_status %}&status={{ current_status }}{% endif %}{% if search_query %}&search={{ search_query }}{% endif %}">{{ num }}</a></li>
                {% endif %}
            {% endfor %}
        </ul>
    </nav>
    {% endif %}
</section>

<!-- Modal pour créer un projet -->
{% if user_type == 'DRH' or user_type == 'TECHNICIEN' %}
<div class="modal" id="createProjectModal">
    <div class="modal-background" onclick="closeCreateProjectModal()"></div>
    <div class="modal-card ecolux-card" style="width: 95%; max-width: 900px; margin: auto;">
        <header class="modal-card-head ecolux-primary">
            <p class="modal-card-title has-text-ecolux-secondary">
                <span class="icon-text">
                    <span class="icon">
                        <i class="fas fa-plus-circle"></i>
                    </span>
                    <span>Nouveau Projet</span>
                </span>
            </p>
            <button class="delete" aria-label="close" onclick="closeCreateProjectModal()"></button>
        </header>
        <section class="modal-card-body" style="max-height: 80vh; overflow-y: auto;">
            <form id="createProjectForm">
                <div class="field">
                    <label class="label has-text-ecolux-primary">Titre du projet</label>
                    <div class="control has-icons-left">
                        <input class="input" type="text" name="title" placeholder="Nom du projet" required>
                        <span class="icon is-small is-left">
                            <i class="fas fa-tag"></i>
                        </span>
                    </div>
                </div>

                <div class="field">
                    <label class="label has-text-ecolux-primary">Description</label>
                    <div class="control">
                        <textarea class="textarea tinymce-editor" name="description" placeholder="Description détaillée du projet" rows="6" required></textarea>
                    </div>
                    <p class="help has-text-grey">Utilisez l'éditeur pour formater votre texte avec du gras, italique, listes, etc.</p>
                </div>

                <div class="field">
                    <label class="label has-text-ecolux-primary">Client</label>
                    <div class="control has-icons-left">
                        <div class="select is-fullwidth">
                            <select name="client_id" required>
                                <option value="">Sélectionner un client</option>
                            </select>
                        </div>
                        <span class="icon is-small is-left">
                            <i class="fas fa-user"></i>
                        </span>
                    </div>
                </div>

                <div class="columns is-mobile">
                    <div class="column is-full-mobile is-half-tablet">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Catégorie</label>
                            <div class="control has-icons-left">
                                <div class="select is-fullwidth">
                                    <select name="category_id">
                                        <option value="">Aucune</option>
                                    </select>
                                </div>
                                <span class="icon is-small is-left">
                                    <i class="fas fa-layer-group"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Type de projet</label>
                            <div class="control has-icons-left">
                                <div class="select is-fullwidth">
                                    <select name="project_type">
                                        <option value="RESIDENTIEL" selected>Résidentiel</option>
                                        <option value="COMMERCIAL">Commercial</option>
                                        <option value="INDUSTRIEL">Industriel</option>
                                        <option value="INSTITUTIONNEL">Institutionnel</option>
                                        <option value="AUTRE">Autre</option>
                                    </select>
                                </div>
                                <span class="icon is-small is-left">
                                    <i class="fas fa-building"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="columns">
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Budget (FCFA)</label>
                            <div class="control has-icons-left">
                                <input class="input" type="number" name="budget" placeholder="Budget estimé">
                                <span class="icon is-small is-left">
                                    <i class="fas fa-coins"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="column is-full-mobile is-half-tablet">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Statut</label>
                            <div class="control has-icons-left">
                                <div class="select is-fullwidth">
                                    <select name="status">
                                        <option value="PLANNING">Planification</option>
                                        <option value="IN_PROGRESS">En cours</option>
                                        <option value="PAUSED">En pause</option>
                                        <option value="COMPLETED">Terminé</option>
                                        <option value="CANCELLED">Annulé</option>
                                    </select>
                                </div>
                                <span class="icon is-small is-left">
                                    <i class="fas fa-tasks"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="columns is-mobile">
                    <div class="column is-full-mobile is-half-tablet">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Date de début</label>
                            <div class="control has-icons-left">
                                <input class="input" type="date" name="start_date">
                                <span class="icon is-small is-left">
                                    <i class="fas fa-calendar-alt"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="column is-full-mobile is-half-tablet">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Date de fin prévue</label>
                            <div class="control has-icons-left">
                                <input class="input" type="date" name="end_date">
                                <span class="icon is-small is-left">
                                    <i class="fas fa-calendar-check"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </section>
        <footer class="modal-card-foot">
            <button class="button is-ecolux-primary" id="createProjectBtn" onclick="submitCreateProject()">
                <span class="icon">
                    <i class="fas fa-save"></i>
                </span>
                <span>Créer le projet</span>
            </button>
            <button class="button" onclick="closeCreateProjectModal()">Annuler</button>
        </footer>
    </div>
</div>

<!-- Modal pour modifier un projet -->
<div class="modal" id="editProjectModal">
    <div class="modal-background" onclick="closeEditProjectModal()"></div>
    <div class="modal-card ecolux-card" style="width: 95%; max-width: 900px; margin: auto;">
        <header class="modal-card-head ecolux-primary">
            <p class="modal-card-title has-text-ecolux-secondary">
                <span class="icon-text">
                    <span class="icon">
                        <i class="fas fa-edit"></i>
                    </span>
                    <span>Modifier le Projet</span>
                </span>
            </p>
            <button class="delete" aria-label="close" onclick="closeEditProjectModal()"></button>
        </header>
        <section class="modal-card-body" style="max-height: 80vh; overflow-y: auto;">
            <form id="editProjectForm">
                <input type="hidden" id="edit_project_id" name="project_id">
                
                <div class="field">
                    <label class="label has-text-ecolux-primary">Titre du projet</label>
                    <div class="control has-icons-left">
                        <input class="input" type="text" id="edit_title" name="title" required>
                        <span class="icon is-small is-left">
                            <i class="fas fa-tag"></i>
                        </span>
                    </div>
                </div>

                <div class="field">
                    <label class="label has-text-ecolux-primary">Description</label>
                    <div class="control">
                        <textarea class="textarea tinymce-editor" id="edit_description" name="description" rows="6" required></textarea>
                    </div>
                </div>

                <div class="field">
                    <label class="label has-text-ecolux-primary">Client</label>
                    <div class="control has-icons-left">
                        <div class="select is-fullwidth">
                            <select id="edit_client_id" name="client_id" required>
                                <option value="">Sélectionner un client</option>
                            </select>
                        </div>
                        <span class="icon is-small is-left">
                            <i class="fas fa-user"></i>
                        </span>
                    </div>
                </div>

                <div class="columns">
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Catégorie</label>
                            <div class="control has-icons-left">
                                <div class="select is-fullwidth">
                                    <select id="edit_category_id" name="category_id">
                                        <option value="">Aucune</option>
                                    </select>
                                </div>
                                <span class="icon is-small is-left">
                                    <i class="fas fa-layer-group"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Type de projet</label>
                            <div class="control has-icons-left">
                                <div class="select is-fullwidth">
                                    <select id="edit_project_type" name="project_type">
                                        <option value="RESIDENTIEL">Résidentiel</option>
                                        <option value="COMMERCIAL">Commercial</option>
                                        <option value="INDUSTRIEL">Industriel</option>
                                        <option value="INSTITUTIONNEL">Institutionnel</option>
                                        <option value="AUTRE">Autre</option>
                                    </select>
                                </div>
                                <span class="icon is-small is-left">
                                    <i class="fas fa-building"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="columns">
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Budget (FCFA)</label>
                            <div class="control has-icons-left">
                                <input class="input" type="number" id="edit_budget" name="budget">
                                <span class="icon is-small is-left">
                                    <i class="fas fa-coins"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Statut</label>
                            <div class="control has-icons-left">
                                <div class="select is-fullwidth">
                                    <select id="edit_status" name="status">
                                        <option value="PLANNING">Planification</option>
                                        <option value="IN_PROGRESS">En cours</option>
                                        <option value="PAUSED">En pause</option>
                                        <option value="COMPLETED">Terminé</option>
                                        <option value="CANCELLED">Annulé</option>
                                    </select>
                                </div>
                                <span class="icon is-small is-left">
                                    <i class="fas fa-tasks"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="columns">
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Date de début</label>
                            <div class="control has-icons-left">
                                <input class="input" type="date" id="edit_start_date" name="start_date">
                                <span class="icon is-small is-left">
                                    <i class="fas fa-calendar-alt"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Date de fin prévue</label>
                            <div class="control has-icons-left">
                                <input class="input" type="date" id="edit_end_date" name="end_date">
                                <span class="icon is-small is-left">
                                    <i class="fas fa-calendar-check"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Section Assignation des techniciens -->
                <div class="field">
                    <label class="label has-text-ecolux-primary">Techniciens assignés</label>
                    <div class="control">
                        <div class="select is-multiple is-fullwidth">
                            <select id="edit_assigned_technicians" name="assigned_technicians" multiple size="4">
                                <!-- Options chargées dynamiquement -->
                            </select>
                        </div>
                    </div>
                    <p class="help">Maintenez Ctrl (Cmd sur Mac) pour sélectionner plusieurs techniciens</p>
                </div>
            </form>
        </section>
        <footer class="modal-card-foot">
            <button class="button is-ecolux-primary" id="editProjectBtn" onclick="submitEditProject()">
                <span class="icon">
                    <i class="fas fa-save"></i>
                </span>
                <span>Sauvegarder</span>
            </button>
            <button class="button" onclick="closeEditProjectModal()">Annuler</button>
        </footer>
    </div>
</div>

{% endif %}

<!-- Modal pour ajouter une activité -->
{% if user_type == 'DRH' or user_type == 'TECHNICIEN' or user_type == 'CLIENT' %}
<div class="modal" id="addActivityModal">
    <div class="modal-background" onclick="closeAddActivityModal()"></div>
    <div class="modal-card ecolux-card">
        <header class="modal-card-head ecolux-primary">
            <p class="modal-card-title has-text-ecolux-secondary">
                <span class="icon-text">
                    <span class="icon">
                        <i class="fas fa-plus-circle"></i>
                    </span>
                    <span>Nouvelle Activité</span>
                </span>
            </p>
            <button class="delete" aria-label="close" onclick="closeAddActivityModal()"></button>
        </header>
        <section class="modal-card-body">
            <form id="addActivityForm">
                <input type="hidden" id="activity_project_id" name="project_id">
                
                <div class="field">
                    <label class="label has-text-ecolux-primary">Titre de l'activité</label>
                    <div class="control has-icons-left">
                        <input class="input" type="text" name="title" placeholder="Titre de l'activité" required>
                        <span class="icon is-small is-left">
                            <i class="fas fa-tasks"></i>
                        </span>
                    </div>
                </div>

                <div class="field">
                    <label class="label has-text-ecolux-primary">Description</label>
                    <div class="control">
                        <textarea class="textarea tinymce-editor" name="description" placeholder="Description de l'activité" rows="4" required></textarea>
                    </div>
                </div>

                <div class="columns">
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Type d'activité</label>
                            <div class="control has-icons-left">
                                <div class="select is-fullwidth">
                                    <select name="activity_type" required>
                                        <option value="">Sélectionner un type</option>
                                        {% if user_type == 'CLIENT' %}
                                            <option value="NOTE">Note</option>
                                            <option value="JUSTIFICATIF">Justificatif</option>
                                        {% else %}
                                            <option value="DESIGN">Design/Conception</option>
                                            <option value="PLANNING">Planification</option>
                                            <option value="CONSTRUCTION">Construction</option>
                                            <option value="INSPECTION">Inspection</option>
                                            <option value="DOCUMENTATION">Documentation</option>
                                            <option value="MEETING">Réunion</option>
                                            <option value="OTHER">Autre</option>
                                            <option value="NOTE">Note</option>
                                            <option value="JUSTIFICATIF">Justificatif</option>
                                        {% endif %}
                                    </select>
                                </div>
                                <span class="icon is-small is-left">
                                    <i class="fas fa-cog"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Affecter à</label>
                            <div class="control has-icons-left">
                                <div class="select is-multiple is-fullwidth">
                                    <select name="assigned_to" multiple size="6">
                                        <!-- Options: Client / Techniciens / DRH -->
                                    </select>
                                </div>
                                <span class="icon is-small is-left">
                                    <i class="fas fa-user"></i>
                                </span>
                            </div>
                            <p class="help">Maintenez Ctrl (Cmd sur Mac) pour sélectionner plusieurs destinataires</p>
                        </div>
                    </div>
                </div>

                <div class="columns">
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Type de facturation</label>
                            <div class="control has-icons-left">
                                <div class="select is-fullwidth">
                                    <select name="billing_type">
                                        <option value="NONE" selected>Non facturable</option>
                                        <option value="MILESTONE">Par jalon / décompte</option>
                                        <option value="FIXED">Forfait</option>
                                        <option value="TIME">Au temps (TJM)</option>
                                    </select>
                                </div>
                                <span class="icon is-small is-left">
                                    <i class="fas fa-file-invoice"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Activité parente</label>
                            <div class="control has-icons-left">
                                <div class="select is-fullwidth">
                                    <select name="parent" id="activity_parent_select">
                                        <option value="">Aucune</option>
                                    </select>
                                </div>
                                <span class="icon is-small is-left">
                                    <i class="fas fa-sitemap"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="columns">
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Budget activité (FCFA)</label>
                            <div class="control has-icons-left">
                                <input class="input" type="number" name="budget_amount" placeholder="Montant prévu">
                                <span class="icon is-small is-left">
                                    <i class="fas fa-coins"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="column">
                        <div class="field">
                            <label class="checkbox" style="margin-top:2rem;">
                                <input type="checkbox" name="is_active" checked>
                                Activité activée
                            </label>
                        </div>
                    </div>
                </div>

                <div class="columns">
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Date d'échéance</label>
                            <div class="control has-icons-left">
                                <input class="input" type="date" name="due_date">
                                <span class="icon is-small is-left">
                                    <i class="fas fa-calendar-alt"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Priorité</label>
                            <div class="control has-icons-left">
                                <div class="select is-fullwidth">
                                    <select name="priority">
                                        <option value="LOW">Basse</option>
                                        <option value="MEDIUM" selected>Moyenne</option>
                                        <option value="HIGH">Haute</option>
                                        <option value="URGENT">Urgent</option>
                                    </select>
                                </div>
                                <span class="icon is-small is-left">
                                    <i class="fas fa-exclamation-triangle"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Section Fichiers -->
                <div class="field">
                    <label class="label has-text-ecolux-primary">Fichiers joints</label>
                    <div class="field has-addons">
                        <div class="control is-expanded">
                            <div class="file has-name is-fullwidth">
                                <label class="file-label">
                                    <input class="file-input" type="file" name="activity_files" multiple accept="image/*,video/*,.pdf,.doc,.docx,.txt,.zip,.rar">
                                    <span class="file-cta">
                                        <span class="file-icon">
                                            <i class="fas fa-upload"></i>
                                        </span>
                                        <span class="file-label">
                                            Choisir des fichiers...
                                        </span>
                                    </span>
                                    <span class="file-name" id="activity-file-names">
                                        Aucun fichier sélectionné
                                    </span>
                                </label>
                            </div>
                        </div>
                    </div>
                    <p class="help">
                        Types supportés : Images (JPG, PNG, GIF), Vidéos (MP4, AVI, MOV), Documents (PDF, DOC, DOCX, TXT), Archives (ZIP, RAR)
                        <br>Taille max par fichier : 50MB
                    </p>
                    
                    <!-- Prévisualisation des fichiers sélectionnés -->
                    <div id="activity-files-preview" class="mt-3" style="display: none;">
                        <h6 class="subtitle is-6 has-text-ecolux-primary">Fichiers sélectionnés :</h6>
                        <div class="columns is-multiline" id="activity-files-list">
                            <!-- Les fichiers apparaîtront ici -->
                        </div>
                    </div>
                </div>
            </form>
        </section>
        <footer class="modal-card-foot">
            <button class="button is-ecolux-primary" onclick="submitAddActivity()">
                <span class="icon">
                    <i class="fas fa-save"></i>
                </span>
                <span>Créer l'activité</span>
            </button>
            <button class="button" onclick="closeAddActivityModal()">Annuler</button>
        </footer>
    </div>
</div>
{% endif %}

<!-- Modal de confirmation de suppression -->
<div id="deleteProjectModal" class="modal">
    <div class="modal-background" onclick="closeDeleteProjectModal()"></div>
    <div class="modal-card ecolux-card" style="width: 90%; max-width: 500px;">
        <header class="modal-card-head" style="background-color: #dc3545;">
            <p class="modal-card-title has-text-white">
                <span class="icon">
                    <i class="fas fa-exclamation-triangle"></i>
                </span>
                Confirmer la suppression
            </p>
            <button class="delete" aria-label="close" onclick="closeDeleteProjectModal()"></button>
        </header>
        <section class="modal-card-body">
            <div class="content">
                <p class="has-text-centered">
                    <span class="icon is-large has-text-danger">
                        <i class="fas fa-trash fa-3x"></i>
                    </span>
                </p>
                <p class="has-text-centered">
                    <strong>Êtes-vous sûr de vouloir supprimer ce projet ?</strong>
                </p>
                <div class="notification is-warning is-light">
                    <p><strong>Projet :</strong> <span id="deleteProjectName"></span></p>
                    <p class="mt-2">
                        <span class="icon-text">
                            <span class="icon has-text-danger">
                                <i class="fas fa-exclamation-circle"></i>
                            </span>
                            <span><strong>Cette action est irréversible !</strong></span>
                        </span>
                    </p>
                    <p class="mt-2">
                        Toutes les activités, fichiers et données associés à ce projet seront également supprimés.
                    </p>
                </div>
            </div>
        </section>
        <footer class="modal-card-foot">
            <button class="button is-danger" id="confirmDeleteBtn" onclick="deleteProject()">
                <span class="icon">
                    <i class="fas fa-trash"></i>
                </span>
                <span>Supprimer définitivement</span>
            </button>
            <button class="button" onclick="closeDeleteProjectModal()">Annuler</button>
        </footer>
    </div>
</div>

<script>
// Variables globales
let clients = [];
let categories = [];

// Charger les clients au chargement de la page
document.addEventListener('DOMContentLoaded', function() {
    loadClients();
    loadCategories();
});

// Fonctions pour le modal de création de projet
function openCreateProjectModal() {
    document.getElementById('createProjectModal').classList.add('is-active');
    document.getElementById('createProjectForm').reset();
    loadClients();
    loadCategories();
}

function closeCreateProjectModal() {
    document.getElementById('createProjectModal').classList.remove('is-active');
}

function loadClients() {
    fetch('{% url "app:get_clients_list" %}')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                clients = data.clients;
                const clientSelect = document.querySelector('select[name="client_id"]');
                clientSelect.innerHTML = '<option value="">Sélectionner un client</option>';
                
                clients.forEach(client => {
                    const option = document.createElement('option');
                    option.value = client.id;
                    option.textContent = `${client.name} (${client.email})`;
                    clientSelect.appendChild(option);
                });
            }
        })
        .catch(error => {
            console.error('Erreur lors du chargement des clients:', error);
            showNotification('Erreur lors du chargement des clients', 'is-danger');
        });
}

function loadCategories(selectedId = null, selectSelector = 'select[name="category_id"]') {
    fetch('{% url "app:get_project_categories" %}')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                categories = data.categories;
                const select = document.querySelector(selectSelector);
                if (!select) return;
                select.innerHTML = '<option value="">Aucune</option>';
                categories.forEach(cat => {
                    const option = document.createElement('option');
                    option.value = cat.id;
                    option.textContent = cat.name;
                    if (selectedId && String(cat.id) === String(selectedId)) {
                        option.selected = true;
                    }
                    select.appendChild(option);
                });
            }
        })
        .catch(error => {
            console.error('Erreur lors du chargement des catégories:', error);
            showNotification('Erreur lors du chargement des catégories', 'is-danger');
        });
}

function submitCreateProject() {
    // Récupérer le contenu de TinyMCE
    tinymce.triggerSave();
    
    const form = document.getElementById('createProjectForm');
    const formData = new FormData(form);
    
    const projectData = {
        title: formData.get('title'),
        description: formData.get('description'), // Le contenu TinyMCE est maintenant disponible
        client_id: formData.get('client_id'),
        category_id: formData.get('category_id') || null,
        project_type: formData.get('project_type') || 'RESIDENTIEL',
        budget: formData.get('budget') || null,
        status: formData.get('status'),
        start_date: formData.get('start_date') || null,
        end_date: formData.get('end_date') || null,
    };
    
    // Validation
    if (!projectData.title || !projectData.description || !projectData.client_id) {
        showNotification('Veuillez remplir tous les champs obligatoires', 'is-warning');
        return;
    }
    
    // Afficher le loader sur le bouton
    const createBtn = document.getElementById('createProjectBtn');
    const originalContent = createBtn.innerHTML;
    createBtn.disabled = true;
    createBtn.classList.add('is-loading');
    createBtn.innerHTML = '<span class="icon"><i class="fas fa-spinner fa-pulse"></i></span><span>Création en cours...</span>';
    
    fetch('{% url "app:create_dashboard_project" %}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
        },
        body: JSON.stringify(projectData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification(data.message, 'is-success');
            closeCreateProjectModal();
            // Recharger la page pour voir le nouveau projet
            setTimeout(() => {
                window.location.reload();
            }, 1500);
        } else {
            showNotification(data.error || 'Erreur lors de la création du projet', 'is-danger');
            // Réactiver le bouton en cas d'erreur
            createBtn.disabled = false;
            createBtn.classList.remove('is-loading');
            createBtn.innerHTML = originalContent;
        }
    })
    .catch(error => {
        console.error('Erreur:', error);
        showNotification('Erreur lors de la création du projet', 'is-danger');
        // Réactiver le bouton en cas d'erreur
        createBtn.disabled = false;
        createBtn.classList.remove('is-loading');
        createBtn.innerHTML = originalContent;
    });
}

// Fonctions pour les actions sur les projets
function editProject(projectId) {
    showNotification('Fonction d\'édition en cours de développement', 'is-info');
}

function assignTechnician(projectId) {
    showNotification('Fonction d\'affectation en cours de développement', 'is-info');
}

function deleteProject(projectId) {
    if (confirm('Êtes-vous sûr de vouloir supprimer ce projet ?')) {
        showNotification('Fonction de suppression en cours de développement', 'is-info');
    }
}

// Fonction pour afficher les notifications
function showNotification(message, type) {
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.style.cssText = 'position: fixed; top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    notification.innerHTML = `
        <button class="delete" onclick="this.parentElement.remove()"></button>
        ${message}
    `;
    
    document.body.appendChild(notification);
    
    // Supprimer automatiquement après 5 secondes
    setTimeout(() => {
        if (notification.parentElement) {
            notification.remove();
        }
    }, 5000);
}

// Initialisation de TinyMCE pour l'éditeur de description
function initTinyMCE() {
    tinymce.init({
        selector: '.tinymce-editor',
        height: 300,
        language: 'fr_FR',
        plugins: [
            'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
            'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
            'insertdatetime', 'media', 'table', 'help', 'wordcount', 'emoticons'
        ],
        toolbar: 'undo redo | blocks | bold italic forecolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help',
        menubar: false,
        branding: false,
        setup: function (editor) {
            editor.on('change', function () {
                editor.save();
            });
        }
    });
}

// Gestion de l'ouverture/fermeture du modal
function openCreateProjectModal() {
    loadClients();
    document.getElementById('createProjectModal').classList.add('is-active');
    // Initialiser TinyMCE après que le modal soit visible
    setTimeout(() => {
        initTinyMCE();
    }, 200);
}

function closeCreateProjectModal() {
    // Détruire l'instance TinyMCE avant de fermer le modal
    tinymce.remove('.tinymce-editor');
    document.getElementById('createProjectModal').classList.remove('is-active');
    document.getElementById('createProjectForm').reset();
}

// Fonctions pour modifier un projet
function editProject(projectId) {
    // Charger les données du projet
    fetch(`/dashboard/projects/${projectId}/data/`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const project = data.project;
                
                // Remplir le formulaire de modification
                document.getElementById('edit_project_id').value = project.id;
                document.getElementById('edit_title').value = project.title;
                document.getElementById('edit_budget').value = project.budget || '';
                document.getElementById('edit_status').value = project.status;
                document.getElementById('edit_start_date').value = project.start_date || '';
                document.getElementById('edit_end_date').value = project.end_date || '';
                
                // Charger les clients dans le select
                populateClientSelect('edit_client_id', project.client_id);
                // Charger les catégories et sélectionner la bonne
                loadCategories(project.category_id, '#edit_category_id');
                // Définir le type de projet si présent
                if (project.project_type) {
                    const selType = document.getElementById('edit_project_type');
                    if (selType) selType.value = project.project_type;
                }
                
                // Ouvrir le modal
                document.getElementById('editProjectModal').classList.add('is-active');
                
                // Initialiser TinyMCE pour la description
                setTimeout(() => {
                    tinymce.init({
                        selector: '#edit_description',
                        height: 200,
                        language: 'fr_FR',
                        plugins: [
                            'advlist', 'autolink', 'lists', 'link', 'charmap', 'preview',
                            'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
                            'insertdatetime', 'table', 'help', 'wordcount'
                        ],
                        toolbar: 'undo redo | blocks | bold italic forecolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat',
                        menubar: false,
                        branding: false,
                        setup: function (editor) {
                            editor.on('init', function () {
                                editor.setContent(project.description || '');
                            });
                        }
                    });
                }, 200);
            } else {
                showNotification('Erreur lors du chargement du projet', 'is-danger');
            }
        })
        .catch(error => {
            console.error('Erreur:', error);
            showNotification('Erreur lors du chargement du projet', 'is-danger');
        });
}

function closeEditProjectModal() {
    tinymce.remove('#edit_description');
    document.getElementById('editProjectModal').classList.remove('is-active');
    document.getElementById('editProjectForm').reset();
}

// Fonctions pour ajouter une activité
function addActivity(projectId) {
    document.getElementById('activity_project_id').value = projectId;
    
    // Charger les destinataires (Client du projet, Techniciens, DRH)
    populateAssignees(projectId);
    
    // Charger les activités pour le sélecteur parent
    populateParentActivities(projectId);

    // Ouvrir le modal
    document.getElementById('addActivityModal').classList.add('is-active');
    
    // Initialiser TinyMCE pour la description d'activité
    setTimeout(() => {
        initTinyMCEForActivity();
    }, 200);
}

function populateParentActivities(projectId) {
    const select = document.getElementById('activity_parent_select');
    if (!select) return;
    select.innerHTML = '<option value="">Aucune</option>';
    fetch(`/dashboard/projects/${projectId}/activities/options/`)
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                data.activities.forEach(a => {
                    const opt = document.createElement('option');
                    opt.value = a.id;
                    opt.textContent = a.title;
                    select.appendChild(opt);
                });
            }
        })
        .catch(err => console.error('Erreur chargement activités:', err));
}

function closeAddActivityModal() {
    tinymce.remove('#addActivityForm .tinymce-editor');
    document.getElementById('addActivityModal').classList.remove('is-active');
    document.getElementById('addActivityForm').reset();
}

function submitAddActivity() {
    // Sauvegarder le contenu TinyMCE
    tinymce.triggerSave();
    
    const form = document.getElementById('addActivityForm');
    const formData = new FormData(form);
    
    const activityData = {
        project_id: formData.get('project_id'),
        title: formData.get('title'),
        description: formData.get('description'),
        activity_type: formData.get('activity_type'),
        assigned_to: formData.get('assigned_to') || null,
        due_date: formData.get('due_date') || null,
        priority: formData.get('priority'),
    };
    
    // Validation
    if (!activityData.title || !activityData.description || !activityData.activity_type) {
        showNotification('Veuillez remplir tous les champs obligatoires', 'is-warning');
        return;
    }
    
    fetch('/dashboard/activities/create/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
        },
        body: JSON.stringify(activityData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification(data.message, 'is-success');
            closeAddActivityModal();
            // Optionnel: rafraîchir la liste ou rediriger vers le détail du projet
            setTimeout(() => {
                window.location.reload();
            }, 1500);
        } else {
            showNotification(data.message, 'is-danger');
        }
    })
    .catch(error => {
        console.error('Erreur:', error);
        showNotification('Erreur lors de la création de l\'activité', 'is-danger');
    });
}

// Fonctions utilitaires
function populateClientSelect(selectId, selectedClientId = null) {
    const select = document.getElementById(selectId);
    select.innerHTML = '<option value="">Sélectionner un client</option>';
    
    clients.forEach(client => {
        const option = document.createElement('option');
        option.value = client.id;
        option.textContent = `${client.name} (${client.email})`;
        if (selectedClientId && client.id == selectedClientId) {
            option.selected = true;
        }
        select.appendChild(option);
    });
}

// Peupler la liste des destinataires (Client, Techniciens, DRH)
function populateAssignees(projectId) {
    const select = document.querySelector('#addActivityModal select[name="assigned_to"]');
    if (!select) return;
    select.innerHTML = '';

    // Préparer les requêtes parallèles
    const reqTech = fetch('/dashboard/technicians/list/')
        .then(r => r.json())
        .catch(() => ({ success: false, technicians: [] }));
    const reqDrh = fetch('/dashboard/drh/list/')
        .then(r => r.json())
        .catch(() => ({ success: false, drh: [] }));
    const reqProject = fetch(`/dashboard/projects/${projectId}/data/`)
        .then(r => r.json())
        .catch(() => ({ success: false }));

    Promise.all([reqTech, reqDrh, reqProject]).then(([techData, drhData, projectData]) => {
        // Client du projet
        if (projectData && projectData.success && Array.isArray(clients)) {
            const clientId = projectData.project.client_id;
            const client = clients.find(c => c.id == clientId);
            if (client) {
                const og = document.createElement('optgroup');
                og.label = 'Client';
                const opt = document.createElement('option');
                opt.value = client.id;
                opt.textContent = `${client.name} (${client.email})`;
                og.appendChild(opt);
                select.appendChild(og);
            }
        }

        // Techniciens
        if (techData && techData.success && Array.isArray(techData.technicians)) {
            const og = document.createElement('optgroup');
            og.label = 'Techniciens';
            techData.technicians.forEach(t => {
                const opt = document.createElement('option');
                opt.value = t.id;
                opt.textContent = t.name;
                og.appendChild(opt);
            });
            select.appendChild(og);
        }

        // DRH
        const drhList = (drhData && drhData.success && (drhData.drh || drhData.users || drhData.drh_users)) || [];
        if (Array.isArray(drhList) && drhList.length > 0) {
            const og = document.createElement('optgroup');
            og.label = 'DRH';
            drhList.forEach(u => {
                const opt = document.createElement('option');
                opt.value = u.id;
                opt.textContent = u.name || u.full_name || u.username || `DRH #${u.id}`;
                og.appendChild(opt);
            });
            select.appendChild(og);
        }

        // Si aucune option ajoutée
        if (!select.children.length) {
            const opt = document.createElement('option');
            opt.disabled = true;
            opt.textContent = 'Aucune personne disponible';
            select.appendChild(opt);
        }
    }).catch(err => {
        console.error('Erreur lors du chargement des destinataires:', err);
    });
}

function initTinyMCEForActivity() {
    tinymce.init({
        selector: '#addActivityModal .tinymce-editor',
        height: 200,
        language: 'fr_FR',
        plugins: [
            'advlist', 'autolink', 'lists', 'link', 'charmap', 'preview',
            'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
            'table', 'help', 'wordcount'
        ],
        toolbar: 'undo redo | blocks | bold italic forecolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat',
        menubar: false,
        branding: false,
        setup: function (editor) {
            editor.on('change', function () {
                editor.save();
            });
        }
    });
}

// Gestion des fichiers dans le modal d'activité
document.addEventListener('DOMContentLoaded', function() {
    const fileInput = document.querySelector('#addActivityModal input[name="activity_files"]');
    if (fileInput) {
        fileInput.addEventListener('change', function() {
            handleFileSelection(this);
        });
    }
});

function handleFileSelection(input) {
    const files = input.files;
    const fileNames = document.getElementById('activity-file-names');
    const preview = document.getElementById('activity-files-preview');
    const filesList = document.getElementById('activity-files-list');

    if (files.length === 0) {
        fileNames.textContent = 'Aucun fichier sélectionné';
        preview.style.display = 'none';
        return;
    }

    // Mettre à jour le nom du fichier
    if (files.length === 1) {
        fileNames.textContent = files[0].name;
    } else {
        fileNames.textContent = `${files.length} fichiers sélectionnés`;
    }

    // Afficher la prévisualisation
    preview.style.display = 'block';
    filesList.innerHTML = '';

    Array.from(files).forEach((file, index) => {
        const fileItem = document.createElement('div');
        fileItem.className = 'column is-half';
        
        const fileIcon = getFileIcon(file.type, file.name);
        const fileSize = formatFileSize(file.size);
        
        fileItem.innerHTML = `
            <div class="box" style="padding: 0.75rem;">
                <div class="media">
                    <div class="media-left">
                        <span class="icon is-large has-text-ecolux-primary">
                            <i class="fas ${fileIcon} fa-2x"></i>
                        </span>
                    </div>
                    <div class="media-content">
                        <p class="subtitle is-6 mb-1">${file.name}</p>
                        <p class="is-size-7 has-text-grey">${fileSize}</p>
                    </div>
                    <div class="media-right">
                        <button type="button" class="delete" onclick="removeFile(${index})"></button>
                    </div>
                </div>
            </div>
        `;
        
        filesList.appendChild(fileItem);
    });
}

function getFileIcon(fileType, fileName) {
    const extension = fileName.split('.').pop().toLowerCase();
    
    if (fileType.startsWith('image/')) return 'fa-image';
    if (fileType.startsWith('video/')) return 'fa-video';
    if (extension === 'pdf') return 'fa-file-pdf';
    if (['doc', 'docx'].includes(extension)) return 'fa-file-word';
    if (['xls', 'xlsx'].includes(extension)) return 'fa-file-excel';
    if (['zip', 'rar', '7z'].includes(extension)) return 'fa-file-archive';
    if (['txt', 'csv'].includes(extension)) return 'fa-file-text';
    
    return 'fa-file';
}

function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function removeFile(index) {
    const fileInput = document.querySelector('#addActivityModal input[name="activity_files"]');
    const dt = new DataTransfer();
    
    Array.from(fileInput.files).forEach((file, i) => {
        if (i !== index) {
            dt.items.add(file);
        }
    });
    
    fileInput.files = dt.files;
    handleFileSelection(fileInput);
}

// Mise à jour de submitAddActivity pour gérer les fichiers
function submitAddActivity() {
    // Sauvegarder le contenu TinyMCE
    tinymce.triggerSave();
    
    const form = document.getElementById('addActivityForm');
    const formData = new FormData(form);
    
    // Les fichiers sont automatiquement inclus dans FormData
    
    // Validation
    if (!formData.get('title') || !formData.get('description') || !formData.get('activity_type')) {
        showNotification('Veuillez remplir tous les champs obligatoires', 'is-warning');
        return;
    }
    
    fetch('/dashboard/activities/create/', {
        method: 'POST',
        headers: {
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
        },
        body: formData  // FormData au lieu de JSON pour les fichiers
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification(data.message, 'is-success');
            closeAddActivityModal();
            setTimeout(() => {
                window.location.reload();
            }, 1500);
        } else {
            showNotification(data.message, 'is-danger');
        }
    })
    .catch(error => {
        console.error('Erreur:', error);
        showNotification('Erreur lors de la création de l\'activité', 'is-danger');
    });
}

// Mise à jour de la fonction editProject pour charger les techniciens
function editProject(projectId) {
    // Charger les données du projet
    fetch(`/dashboard/projects/${projectId}/data/`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const project = data.project;
                
                // Remplir le formulaire de modification
                document.getElementById('edit_project_id').value = project.id;
                document.getElementById('edit_title').value = project.title;
                document.getElementById('edit_budget').value = project.budget || '';
                document.getElementById('edit_status').value = project.status;
                document.getElementById('edit_start_date').value = project.start_date || '';
                document.getElementById('edit_end_date').value = project.end_date || '';
                
                // Charger les clients et techniciens
                populateClientSelect('edit_client_id', project.client_id);
                populateTechniciansSelect('edit_assigned_technicians', project.assigned_technicians || []);
                
                // Ouvrir le modal
                document.getElementById('editProjectModal').classList.add('is-active');
                
                // Initialiser TinyMCE pour la description
                setTimeout(() => {
                    tinymce.init({
                        selector: '#edit_description',
                        height: 200,
                        language: 'fr_FR',
                        plugins: [
                            'advlist', 'autolink', 'lists', 'link', 'charmap', 'preview',
                            'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
                            'insertdatetime', 'table', 'help', 'wordcount'
                        ],
                        toolbar: 'undo redo | blocks | bold italic forecolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat',
                        menubar: false,
                        branding: false,
                        setup: function (editor) {
                            editor.on('init', function () {
                                editor.setContent(project.description || '');
                            });
                        }
                    });
                }, 200);
            } else {
                showNotification('Erreur lors du chargement du projet', 'is-danger');
            }
        })
        .catch(error => {
            console.error('Erreur:', error);
            showNotification('Erreur lors du chargement du projet', 'is-danger');
        });
}

function populateTechniciansSelect(selectId, selectedTechIds = []) {
    fetch('/api/dashboard/technicians/')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const select = document.getElementById(selectId);
                select.innerHTML = '';
                
                data.technicians.forEach(tech => {
                    const option = document.createElement('option');
                    option.value = tech.id;
                    option.textContent = `${tech.name} (${tech.email})`;
                    if (selectedTechIds.includes(tech.id)) {
                        option.selected = true;
                    }
                    select.appendChild(option);
                });
            }
        })
        .catch(error => {
            console.error('Erreur lors du chargement des techniciens:', error);
        });
}

// Mise à jour de submitEditProject pour inclure les techniciens
function submitEditProject() {
    // Sauvegarder le contenu TinyMCE
    tinymce.triggerSave();
    
    const form = document.getElementById('editProjectForm');
    const formData = new FormData(form);
    
    // Récupérer les techniciens sélectionnés
    const selectedTechnicians = Array.from(
        document.getElementById('edit_assigned_technicians').selectedOptions
    ).map(option => option.value);
    
    const projectData = {
        project_id: formData.get('project_id'),
        title: formData.get('title'),
        description: formData.get('description'),
        client_id: formData.get('client_id'),
        category_id: formData.get('category_id') || null,
        project_type: formData.get('project_type') || 'RESIDENTIEL',
        budget: formData.get('budget') || null,
        status: formData.get('status'),
        start_date: formData.get('start_date') || null,
        end_date: formData.get('end_date') || null,
        assigned_technicians: selectedTechnicians,
    };
    
    // Validation
    if (!projectData.title || !projectData.description || !projectData.client_id) {
        showNotification('Veuillez remplir tous les champs obligatoires', 'is-warning');
        return;
    }
    
    // Afficher le loader sur le bouton
    const editBtn = document.getElementById('editProjectBtn');
    const originalContent = editBtn.innerHTML;
    editBtn.disabled = true;
    editBtn.classList.add('is-loading');
    editBtn.innerHTML = '<span class="icon"><i class="fas fa-spinner fa-pulse"></i></span><span>Modification en cours...</span>';
    
    fetch('/dashboard/projects/update/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
        },
        body: JSON.stringify(projectData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification(data.message, 'is-success');
            closeEditProjectModal();
            setTimeout(() => {
                window.location.reload();
            }, 1500);
        } else {
            showNotification(data.message, 'is-danger');
            // Réactiver le bouton en cas d'erreur
            editBtn.disabled = false;
            editBtn.classList.remove('is-loading');
            editBtn.innerHTML = originalContent;
        }
    })
    .catch(error => {
        console.error('Erreur:', error);
        showNotification('Erreur lors de la modification', 'is-danger');
        // Réactiver le bouton en cas d'erreur
        editBtn.disabled = false;
        editBtn.classList.remove('is-loading');
        editBtn.innerHTML = originalContent;
    });
}

// Fonctions existantes (anciennes - à supprimer plus tard)
function assignTechnician(projectId) {
    showNotification('Utilisez le bouton "Modifier" pour assigner des techniciens', 'is-info');
}

// Variable pour stocker l'ID du projet à supprimer
let projectToDelete = null;

// Ouvrir la modale de confirmation de suppression
function confirmDeleteProject(projectId, projectName) {
    projectToDelete = projectId;
    document.getElementById('deleteProjectName').textContent = projectName;
    document.getElementById('deleteProjectModal').classList.add('is-active');
}

// Fermer la modale de confirmation
function closeDeleteProjectModal() {
    projectToDelete = null;
    document.getElementById('deleteProjectModal').classList.remove('is-active');
}

// Supprimer le projet
function deleteProject() {
    if (!projectToDelete) {
        showNotification('Erreur: Aucun projet sélectionné', 'is-danger');
        return;
    }
    
    const deleteBtn = document.getElementById('confirmDeleteBtn');
    const originalContent = deleteBtn.innerHTML;
    
    // Désactiver le bouton et afficher un loader
    deleteBtn.disabled = true;
    deleteBtn.innerHTML = '<span class="icon"><i class="fas fa-spinner fa-pulse"></i></span><span>Suppression...</span>';
    
    fetch(`/api/dashboard/projects/${projectToDelete}/delete/`, {
        method: 'DELETE',
        headers: {
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification(data.message, 'is-success');
            closeDeleteProjectModal();

            // actualiser la page
            window.location.reload();
            
            // Supprimer visuellement le projet de la liste
            const projectCards = document.querySelectorAll('.media');
            projectCards.forEach(card => {
                const projectLink = card.querySelector(`a[href*="/dashboard/projects/${projectToDelete}/"]`);
                if (projectLink) {
                    // Animation de suppression
                    card.style.transition = 'opacity 0.5s, transform 0.5s';
                    card.style.opacity = '0';
                    card.style.transform = 'translateX(-100%)';
                    
                    setTimeout(() => {
                        card.remove();
                        
                        // Vérifier s'il reste des projets
                        const remainingProjects = document.querySelectorAll('.media').length;
                        if (remainingProjects === 0) {
                            // Recharger la page pour afficher le message "Aucun projet"
                            window.location.reload();
                        }
                    }, 500);
                }
            });
        } else {
            showNotification(data.error || 'Erreur lors de la suppression', 'is-danger');
            deleteBtn.disabled = false;
            deleteBtn.innerHTML = originalContent;
        }
    })
    .catch(error => {
        console.error('Erreur:', error);
        showNotification('Erreur lors de la suppression du projet', 'is-danger');
        deleteBtn.disabled = false;
        deleteBtn.innerHTML = originalContent;
    });
}
</script>

{% csrf_token %}
{% endblock %}
