<?php
include "classes/app.class.php";
?>

<div class="app-content-wrapper">
    <div class="page-header">
        <h2 class="main-title">Clients</h2>
    </div>

    <div class="table-container">
        <div class="table-actions">
            <div class="search-wrapper">
                <input type="text" id="clientSearch" placeholder="Search by client name..." onkeyup="searchClients()">
            </div>
            <button class="btn-primary" onclick="openAddClientModal()">
                <span>+ Add Client</span>
            </button>
        </div>

        <table class="apple-table" id="clientsTable">
            <thead>
                <tr>
                    <th>Client Name</th>
                    <th>Total Tanks</th>
                    <th>Current</th>
                    <th>Progress bar</th>
                    <th>Max</th>
                    <th style="text-align: right;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $clients_res = $db->query("clients", "SELECT * FROM clients WHERE 1 ORDER BY name ASC");
                while ($clients = $clients_res->fetch_assoc()) {
                    // Calculate the values safely
                    $current = (float) $functions->get_capacity_for_client($clients['record_id']);
                    $max = (float) $functions->get_total_max_capacity_for_client($clients['record_id']);
                    ?>
                    <tr>
                        <td data-label="Client Name" class="client-name"><strong><?php echo $clients['name']; ?></strong></td>
                        <td data-label="Tanks" class="hide-mobile"><?php echo $functions->get_total_tanks_for_client($clients['record_id']); ?>
                        </td>
                        <td data-label="Current" class="hide-mobile"><?php echo number_format($current, 0); ?> L</td>
                        <td class="progress-col">
                            <?php echo $functions->get_progress_bar($current, $max); ?>
                        </td>
                        <td data-label="Max" class="hide-mobile"><?php echo number_format($max, 0); ?> L</td>
                        <td data-label="Actions" style="text-align: right;">
                            <button class="btn-edit" onclick="openEditModal('<?php echo $clients['record_id']; ?>', '<?php echo addslashes($clients['name']); ?>')">Edit</button>
                        </td>
                    </tr>
                <?php }
                ?>
            </tbody>
        </table>
    </div>
</div>
<div id="addClientModal" class="modal-overlay">
    <div class="modal-card">
        <div class="modal-header">
            <h3>New Client</h3>
            <button class="close-btn" onclick="closeAddClientModal()">&times;</button>
        </div>
        <div class="modal-body">
            <div class="input-group">
                <label>Client Name</label>
                <input type="text" id="new_client_name" placeholder="Enter company name..." autofocus>
            </div>
            <div id="modal-error" class="error-message" style="display:none; margin-bottom:10px;">Failed to add client.
                Please try again.</div>
        </div>
        <div class="modal-footer">
            <button class="btn-secondary" onclick="closeAddClientModal()">Cancel</button>
            <button id="submitClientBtn" class="btn-primary" onclick="submitNewClient()">
                <span>Save Client</span>
            </button>
        </div>
    </div>
</div>

<div id="editClientModal" class="modal-overlay">
    <div class="modal-card">
        <div class="modal-header">
            <h3>Edit Client</h3>
            <button class="close-btn" onclick="closeEditModal()">&times;</button>
        </div>
        <div class="modal-body">
            <input type="hidden" id="edit_record_id">

            <div class="input-group">
                <label>Client Name</label>
                <input type="text" id="edit_client_name" placeholder="Enter company name...">
            </div>
            <div id="edit-modal-error" class="error-message"
                style="display:none; color: red; margin-bottom:10px; font-size: 13px;">
                Operation failed. Please try again.
            </div>
        </div>
        <div class="modal-footer" style="justify-content: space-between;">
            <button class="btn-danger" onclick="deleteClient()">Delete</button>

            <div style="display: flex; gap: 12px;">
                <button class="btn-secondary" onclick="closeEditModal()">Cancel</button>
                <button id="updateClientBtn" class="btn-primary" onclick="submitEditClient()">
                    <span>Update</span>
                </button>
            </div>
        </div>
    </div>
</div>
<script>
    function searchClients() {
        // Declare variables
        var input, filter, table, tr, td, i, txtValue;
        input = document.getElementById("clientSearch");
        filter = input.value.toUpperCase();
        table = document.getElementById("clientsTable");
        tr = table.getElementsByTagName("tr");

        // Loop through all table rows, and hide those who don't match the search query
        for (i = 1; i < tr.length; i++) {
            // We search in the first column (Client Name)
            td = tr[i].getElementsByClassName("client-name")[0];
            if (td) {
                txtValue = td.textContent || td.innerText;
                if (txtValue.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
    }
    function openAddClientModal() {
        document.getElementById('addClientModal').style.display = 'flex';
        document.getElementById('new_client_name').focus();
    }

    function closeAddClientModal() {
        document.getElementById('addClientModal').style.display = 'none';
        document.getElementById('new_client_name').value = '';
        document.getElementById('modal-error').style.display = 'none';
    }

    function submitNewClient() {
        const nameInput = document.getElementById('new_client_name');
        const submitBtn = document.getElementById('submitClientBtn');
        const name = nameInput.value.trim();

        if (name === "") {
            nameInput.style.borderColor = "red";
            return;
        }

        // Show loading state on button
        submitBtn.disabled = true;
        submitBtn.innerHTML = "<span>Saving...</span>";

        // Create Form Data
        const formData = new FormData();
        formData.append('name', name);

        fetch('ajax/add_client.php', {
            method: 'POST',
            body: formData
        })
            .then(response => response.text())
            .then(data => {
                if (data.trim() === "1") {
                    // Success: Refresh the page
                    window.location.reload();
                } else {
                    // Failed
                    document.getElementById('modal-error').style.display = 'block';
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = "<span>Save Client</span>";
                }
            })
            .catch(error => {
                console.error('Error:', error);
                submitBtn.disabled = false;
                submitBtn.innerHTML = "<span>Save Client</span>";
            });
    }

    // Close modal if user clicks outside the card
    window.onclick = function (event) {
        const modal = document.getElementById('addClientModal');
        if (event.target == modal) {
            closeAddClientModal();
        }
    }

    function openEditModal(id, name) {
        document.getElementById('edit_record_id').value = id;
        document.getElementById('edit_client_name').value = name;
        document.getElementById('editClientModal').style.display = 'flex';
        document.getElementById('edit_client_name').focus();
    }

    function closeEditModal() {
        document.getElementById('editClientModal').style.display = 'none';
        document.getElementById('edit-modal-error').style.display = 'none';
    }

    // UPDATE CLIENT
    function submitEditClient() {
        const id = document.getElementById('edit_record_id').value;
        const name = document.getElementById('edit_client_name').value.trim();
        const btn = document.getElementById('updateClientBtn');

        if (name === "") return;

        btn.disabled = true;
        btn.innerHTML = "<span>Updating...</span>";

        const formData = new FormData();
        formData.append('record_id', id);
        formData.append('name', name);

        fetch('ajax/edit_client.php', {
            method: 'POST',
            body: formData
        })
            .then(response => response.text())
            .then(data => {
                console.log(data);
                if (data.trim() === "1") {
                    window.location.reload();
                } else {
                    document.getElementById('edit-modal-error').style.display = 'block';
                    btn.disabled = false;
                    btn.innerHTML = "<span>Update</span>";
                }
            });
    }

    // DELETE CLIENT
    function deleteClient() {
        if (!confirm("Are you sure you want to delete this client? This cannot be undone.")) return;

        const id = document.getElementById('edit_record_id').value;
        const formData = new FormData();
        formData.append('record_id', id);
        formData.append('action', 'delete'); // Tell PHP we want to delete

        fetch('ajax/edit_client.php', {
            method: 'POST',
            body: formData
        })
            .then(response => response.text())
            .then(data => {
                console.log(data);
                if (data == "1") {
                    window.location.reload();
                } else {
                    alert("Delete failed. Client might have linked tanks.");
                }
            });
    }

    // Update the global window.onclick to handle both modals
    window.onclick = function (event) {
        const addModal = document.getElementById('addClientModal');
        const editModal = document.getElementById('editClientModal');
        if (event.target == addModal) closeAddClientModal();
        if (event.target == editModal) closeEditModal();
    }
</script>