<?php
    require'include/cabeza.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ePatient Management | HealthBuro</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <!-- [favicon] begin -->
    <link rel="shortcut icon" type="image/x-icon" href="https://sylvianettebox.net/favicon.ico" />
    <link rel="icon" type="image/x-icon" href="https://sylvianettebox.net/favicon.ico" />
    <!-- [favicon] end -->
    <link rel="stylesheet" href="assets/css/core.css" type="text/css"/>
</head>
<body>
    <div class="dashboard-container">
        <?php 
            $page = 'ePatient';
            include 'include/sidebar.php'
        ?>
        
        <!-- Main Content -->
        <div class="main-content">
            <div class="content-wrapper">
                <!-- Topbar -->
                <? include 'include/topbar.php' ?>
                
                <!-- Page Content -->
                <div class="page-header">
                    <div class="page-title">Patient Management</div>
                    <div class="page-actions">
                        <button class="btn btn-outline">
                            <i class="fas fa-file-export"></i>
                            Export Data
                        </button>
                        <button class="btn btn-primary" id="add-patient-btn">
                            <i class="fas fa-plus"></i>
                            Add New Patient
                        </button>
                    </div>
                </div>
                
                <!-- Analytics Section -->
                <div class="analytics-section">
                    <div class="analytics-card">
                        <div class="analytics-header">
                            <div class="analytics-title">Total Patients</div>
                            <div class="analytics-icon">
                                <i class="fas fa-user-injured"></i>
                            </div>
                        </div>
                        <div class="analytics-value">2,842</div>
                        <div class="analytics-change">
                            <i class="fas fa-arrow-up"></i>
                            12.5% increase from last month
                        </div>
                    </div>
                    
                    <div class="analytics-card">
                        <div class="analytics-header">
                            <div class="analytics-title">Active Patients</div>
                            <div class="analytics-icon">
                                <i class="fas fa-heartbeat"></i>
                            </div>
                        </div>
                        <div class="analytics-value">2,156</div>
                        <div class="analytics-change">
                            <i class="fas fa-arrow-up"></i>
                            8.3% increase from last month
                        </div>
                    </div>
                    
                    <div class="analytics-card">
                        <div class="analytics-header">
                            <div class="analytics-title">New This Month</div>
                            <div class="analytics-icon">
                                <i class="fas fa-user-plus"></i>
                            </div>
                        </div>
                        <div class="analytics-value">186</div>
                        <div class="analytics-change">
                            <i class="fas fa-arrow-up"></i>
                            5.2% increase from last month
                        </div>
                    </div>
                </div>
                
                <!-- Patients Table -->
                <div class="patients-table-container">
                    <div class="table-header">
                        <div class="table-title">
                            <select class="search-input">
                                <option>10</option>
                                <option>50</option>
                                <option>100</option>
                                <option>500</option>
                            </select>
                            Patient Records
                        </div>
                        <div class="search-filter">
                            <input type="text" class="search-input" placeholder="Search patients...">
                            <select class="search-input">
                                <option>All Status</option>
                                <option>Active</option>
                                <option>Inactive</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="table-wrapper">
                        <table class="patients-table">
                            <thead>
                                <tr>
                                    <th>Patient ID</th>
                                    <th>Name</th>
                                    <th>Contact</th>
                                    <th>Gender</th>
                                    <th>Age</th>
                                    <th>Blood Group</th>
                                    <th>Last Visit</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>#P-1001</td>
                                    <td>
                                        <div style="display: flex; align-items: center; gap: 10px;">
                                            <div class="patient-avatar">JD</div>
                                            <div>
                                                <div>John Doe</div>
                                                <div style="font-size: 0.85rem; color: var(--text-secondary);">johndoe@example.com</div>
                                            </div>
                                        </div>
                                    </td>
                                    <td>+1 (555) 123-4567</td>
                                    <td>Male</td>
                                    <td>42</td>
                                    <td>O+</td>
                                    <td>2023-06-15</td>
                                    <td><span class="status-badge status-active">Active</span></td>
                                    <td>
                                        <div class="action-buttons">
                                            <button class="action-btn-table view-btn">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            <button class="action-btn-table edit-btn">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button class="action-btn-table delete-btn">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td>#P-1002</td>
                                    <td>
                                        <div style="display: flex; align-items: center; gap: 10px;">
                                            <div class="patient-avatar">MJ</div>
                                            <div>
                                                <div>Michael Johnson</div>
                                                <div style="font-size: 0.85rem; color: var(--text-secondary);">michaelj@example.com</div>
                                            </div>
                                        </div>
                                    </td>
                                    <td>+1 (555) 456-7890</td>
                                    <td>Male</td>
                                    <td>58</td>
                                    <td>AB+</td>
                                    <td>2023-05-22</td>
                                    <td><span class="status-badge status-inactive">Inactive</span></td>
                                    <td>
                                        <div class="action-buttons">
                                            <button class="action-btn-table view-btn">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            <button class="action-btn-table edit-btn">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button class="action-btn-table delete-btn">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    
                    <div class="pagination">
                        <div class="pagination-info">Showing 1 to 5 of 2,842 patients</div>
                        <div class="pagination-controls">
                            <button class="pagination-btn">
                                <i class="fas fa-chevron-left"></i>
                            </button>
                            <button class="pagination-btn active">1</button>
                            <button class="pagination-btn">2</button>
                            <button class="pagination-btn">3</button>
                            <button class="pagination-btn">...</button>
                            <button class="pagination-btn">24</button>
                            <button class="pagination-btn">
                                <i class="fas fa-chevron-right"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <? include 'include/footer.php' ?>
        </div>
        <?php
            include 'include/messenger.php';
            include 'include/notification.php';
        ?>
        <!-- Add Patient Modal -->
        <div class="modal" id="patient-modal">
          <div class="modal-content">
            <div class="modal-header">
              <div class="modal-title">Add New Patient</div>
              <button class="close-modal" type="button">
                <i class="fas fa-times"></i>
              </button>
            </div>
        
            <div class="modal-body">
              <form id="registrationForm" class="form-grid" autocomplete="off" novalidate>
                <div class="form-group">
                  <label class="form-label">UserID*</label>
                  <input type="text" class="form-input" id="userID" name="userID" placeholder="Enter UserID..." required>
                </div>
        
                <div class="form-group">
                  <label class="form-label">Full Name*</label>
                  <input type="text" class="form-input" id="name" name="name" placeholder="Enter full name..." required>
                </div>
        
                <div class="form-group">
                  <label class="form-label">Email Address</label>
                  <input type="email" class="form-input" id="email" name="email" placeholder="Enter email address...">
                </div>
        
                <div class="form-group">
                  <label class="form-label">Password*</label>
                  <input type="password" class="form-input" id="password" name="password" placeholder="Create password..." required>
                </div>
        
                <div class="form-group">
                  <label class="form-label">Phone Number*</label>
                  <input type="tel" class="form-input" id="phone" name="phone" placeholder="Enter phone number..." required>
                </div>
        
                <div class="form-group">
                  <label class="form-label">Phone Number 2</label>
                  <input type="tel" class="form-input" id="phone2" name="phone2" placeholder="Enter another phone number...">
                </div>
        
                <div class="form-group">
                  <label class="form-label">Date of Birth*</label>
                  <input type="date" class="form-input" id="dob" name="dob" required>
                </div>
        
                <div class="form-group">
                  <label class="form-label">Gender</label>
                  <select class="form-input" id="gender" name="gender" required>
                    <option value="">Select gender</option>
                    <option>Male</option>
                    <option>Female</option>
                    <option>Other</option>
                  </select>
                </div>
        
                <div class="form-group">
                  <label class="form-label">Nationality*</label>
                  <input type="text" class="form-input" id="nationality" name="nationality" placeholder="Enter nationality..." required>
                </div>
        
                <div class="form-group">
                  <label class="form-label">State of Origin*</label>
                  <input type="text" class="form-input" id="state" name="state" placeholder="Enter state..." required>
                </div>
        
                <div class="form-group">
                  <label class="form-label">LGA of Origin*</label>
                  <input type="text" class="form-input" id="lga" name="lga" placeholder="Enter LGA..." required>
                </div>
        
                <div class="form-group">
                  <label class="form-label">Religion*</label>
                  <input type="text" class="form-input" id="religion" name="religion" placeholder="Enter religion..." required>
                </div>
        
                <div class="form-group">
                  <label class="form-label">Blood Group</label>
                  <select class="form-input" id="blood_group" name="blood_group">
                    <option value="">Select blood group</option>
                    <option>A+</option><option>A-</option><option>B+</option><option>B-</option>
                    <option>AB+</option><option>AB-</option><option>O+</option><option>O-</option>
                  </select>
                </div>
        
                <div class="form-group">
                  <label class="form-label">Blood Genotype</label>
                  <select class="form-input" id="genotype" name="genotype">
                    <option value="">Select genotype</option>
                    <option>AA</option><option>AS</option><option>SS</option><option>AC</option>
                  </select>
                </div>
        
                <div class="form-group">
                  <label class="form-label">Address*</label>
                  <textarea class="form-input" id="address" name="address" placeholder="Enter address..." rows="3" required></textarea>
                </div>
        
                <div class="form-group">
                  <label class="form-label">Adverse Reactions</label>
                  <textarea class="form-input" id="adverse" name="adverse_reactions" placeholder="List any adverse reactions..." rows="3"></textarea>
                </div>
        
                <div style="grid-column: 1 / -1; margin-top: 20px; padding-top: 20px; border-top: 1px solid var(--border);">
                  <h3 style="margin-bottom: 20px; color: var(--primary);">Next of Kin Information</h3>
        
                  <div class="form-row">
                    <div class="form-group">
                      <label class="form-label">Full Name*</label>
                      <input type="text" class="form-input" id="nok_name" name="nok_name" placeholder="Enter full name..." required>
                    </div>
        
                    <div class="form-group">
                      <label class="form-label">Relationship*</label>
                      <input type="text" class="form-input" id="nok_relationship" name="nok_relationship" placeholder="Enter relationship..." required>
                    </div>
        
                    <div class="form-group">
                      <label class="form-label">Phone Number*</label>
                      <input type="tel" class="form-input" id="nok_phone" name="nok_phone" placeholder="Enter phone number..." required>
                    </div>
        
                    <div class="form-group">
                      <label class="form-label">Phone Number 2</label>
                      <input type="tel" class="form-input" id="nok_phone2" name="nok_phone2" placeholder="Enter another phone number...">
                    </div>
                  </div>
        
                  <div class="form-group">
                    <label class="form-label">Address*</label>
                    <textarea class="form-input" id="nok_address" name="nok_address" placeholder="Enter address..." rows="5" required></textarea>
                  </div>
                </div>
              </form>
            </div>
        
            <div class="modal-footer">
              <div id="loader" style="display:none;">
                <i class="fas fa-spinner fa-spin"></i> Saving...
              </div>
        
              <button class="btn btn-outline" id="cancel-btn" type="button">Cancel</button>
              <button class="btn btn-primary" id="saveBtn" type="button" form="registrationForm">Save Patient</button>
            </div>
          </div>
        </div>
    </div>
    <script src="/assets/js/main.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
          const form = document.getElementById('registrationForm');
          const saveBtn = document.getElementById('saveBtn');
          const cancelBtn = document.getElementById('cancel-btn');
          const loader = document.getElementById('loader');
        
          const showLoader = () => { loader.style.display = 'inline-block'; saveBtn.disabled = true; cancelBtn.disabled = true; };
          const hideLoader = () => { loader.style.display = 'none'; saveBtn.disabled = false; cancelBtn.disabled = false; };
        
          // Extra safety: remove any action so a fallback native submit won't accidentally navigate.
          try { form.removeAttribute('action'); } catch(e) { /* ignore */ }
        
          // Universal submit function (used by button click and by intercepting form submit)
          async function submitForm() {
            // basic client side validation example (expand as needed)
            const userID = form.querySelector('[name="userID"]')?.value?.trim();
            if (!userID) { alert('Please enter User ID'); return; }
        
            const fullName = form.querySelector('[name="name"]')?.value?.trim();
            if (!fullName) { alert('Please enter full name'); return; }
        
            const password = form.querySelector('[name="password"]')?.value?.trim();
            if (!password) { alert('Please enter password'); return; }
            if (password.length < 6) { alert('Password must be at least 6 characters'); return; }
        
            const phone = form.querySelector('[name="phone"]')?.value?.trim();
            if (!phone) { alert('Please enter phone number'); return; }
        
            const dob = form.querySelector('[name="dob"]')?.value?.trim();
            if (!dob) { alert('Please enter date of birth'); return; }
        
            const gender = form.querySelector('[name="gender"]')?.value?.trim();
            if (!gender) { alert('Please select gender'); return; }
        
            const nationality = form.querySelector('[name="nationality"]')?.value?.trim();
            if (!nationality) { alert('Please enter nationality'); return; }
        
            const state = form.querySelector('[name="state"]')?.value?.trim();
            if (!state) { alert('Please enter state of origin'); return; }
        
            const lga = form.querySelector('[name="lga"]')?.value?.trim();
            if (!lga) { alert('Please enter LGA of origin'); return; }
        
            const religion = form.querySelector('[name="religion"]')?.value?.trim();
            if (!religion) { alert('Please enter religion'); return; }
        
            const address = form.querySelector('[name="address"]')?.value?.trim();
            if (!address) { alert('Please enter address'); return; }
        
            const nok_name = form.querySelector('[name="nok_name"]')?.value?.trim();
            if (!nok_name) { alert('Please enter next of kin name'); return; }
        
            const nok_relationship = form.querySelector('[name="nok_relationship"]')?.value?.trim();
            if (!nok_relationship) { alert('Please enter next of kin relationship'); return; }
        
            const nok_phone1 = form.querySelector('[name="nok_phone"]')?.value?.trim();
            if (!nok_phone1) { alert('Please enter next of kin phone number'); return; }
        
            const nok_address = form.querySelector('[name="nok_address"]')?.value?.trim();
            if (!nok_address) { alert('Please enter next of kin address'); return; }
        
            showLoader();
            try {
              const formData = new FormData(form);
        
              const resp = await fetch('/api/patientCRUD.php', { // change endpoint if needed
                method: 'POST',
                body: formData,
                credentials: 'same-origin',
                headers: {
                  // do NOT set Content-Type when sending FormData; browser sets boundary automatically
                  'X-Requested-With': 'XMLHttpRequest'
                }
              });
        
              // read text first and attempt to parse JSON (safer for debugging)
              const text = await resp.text();
              let data;
              try { data = JSON.parse(text); } catch (e) {
                // server did not return JSON — show raw response for debugging
                throw new Error('Server response is not valid JSON: ' + text);
              }
        
              if (resp.ok && (data.success || data.status === 'success')) {
                // success path (adjust to your JSON shape)
                alert(data.message || 'Patient saved');
                // close modal, reset form or update UI:
                form.reset();
                // close modal implementation depends on your modal code:
                document.getElementById('patient-modal').style.display = 'none';
              } else {
                // server returned JSON but indicates an error
                throw new Error(data.message || 'Save failed');
              }
            } catch (err) {
              console.error('Submit error:', err);
              alert('Error saving patient: ' + err.message);
            } finally {
              hideLoader();
            }
          }
        
          // Click -> submit
          saveBtn.addEventListener('click', (ev) => {
            ev.preventDefault();
            submitForm();
          });
        
          // In case user presses Enter inside the form, intercept native submit
          form.addEventListener('submit', (ev) => {
            ev.preventDefault();
            submitForm();
          });
        
          // Cancel button
          cancelBtn.addEventListener('click', () => {
            if (confirm('Discard changes?')) {
              form.reset();
              document.getElementById('patient-modal').style.display = 'none';
            }
          });
        });
        
        /* --------------------
        Table edit/delete delegation
        -------------------- */
        const patientTableBody = document.querySelector('.patients-table tbody');
        const paginationContainer = document.querySelector('.pagination-controls');
        const rowsPerPageSelect = document.querySelector('.table-title select');
        const searchInput = document.querySelector('.search-filter input');
        
        let currentPage = 1;
        let rowsPerPage = parseInt(rowsPerPageSelect.value);
        let searchQuery = "";
        
        // Load patients
        async function loadPatients(page = 1) {
            const formData = new FormData();
            formData.append('action', 'read');
            formData.append('page', page);
            formData.append('limit', rowsPerPage);
            formData.append('search', searchQuery);
        
            const resp = await fetch('/api/get_patients.php', {
                method: 'POST',
                body: formData
            });
            const data = await resp.json();
        
            if (data.status === 'success') {
                renderTable(data.data);
                renderPagination(data.page, data.totalPages);
            }
        }
        
        // Render table rows
        function renderTable(rows) {
            patientTableBody.innerHTML = rows.map(row => `
                <tr data-patient-id="${row.id}">
                    <td>#P-${row.id}</td>
                    <td>
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <div class="patient-avatar">${row.name.split(' ').map(w => w[0]).join('')}</div>
                            <div>
                                <div>${row.name}</div>
                                <div style="font-size: 0.85rem; color: var(--text-secondary);">${row.email}</div>
                            </div>
                        </div>
                    </td>
                    <td>${row.contact}</td>
                    <td>${row.gender}</td>
                    <td>${row.age}</td>
                    <td>${row.blood_group}</td>
                    <td>${row.last_visit}</td>
                    <td><span class="status-badge status-${row.status.toLowerCase()}">${row.status}</span></td>
                    <td>
                        <div class="action-buttons">
                            <button class="action-btn-table view-btn"><i class="fas fa-eye"></i></button>
                            <button class="action-btn-table edit-btn"><i class="fas fa-edit"></i></button>
                            <button class="action-btn-table delete-btn"><i class="fas fa-trash"></i></button>
                        </div>
                    </td>
                </tr>
            `).join('');
        }
        
        // Render pagination
        function renderPagination(current, totalPages) {
            paginationContainer.innerHTML = '';
            for (let i = 1; i <= totalPages; i++) {
                const btn = document.createElement('button');
                btn.className = 'pagination-btn' + (i === current ? ' active' : '');
                btn.textContent = i;
                btn.addEventListener('click', () => {
                    currentPage = i;
                    loadPatients(currentPage);
                });
                paginationContainer.appendChild(btn);
            }
        }
        
        // Event listeners
        rowsPerPageSelect.addEventListener('change', () => {
            rowsPerPage = parseInt(rowsPerPageSelect.value);
            currentPage = 1;
            loadPatients();
        });
        
        searchInput.addEventListener('input', debounce(() => {
            searchQuery = searchInput.value;
            currentPage = 1;
            loadPatients();
        }, 300));
        
        function debounce(func, delay) {
            let timeout;
            return (...args) => {
                clearTimeout(timeout);
                timeout = setTimeout(() => func(...args), delay);
            };
        }
        
        // Initial load
        loadPatients();

    </script>

</body>
</html>