<template>
  <div>
    <header>
      <div class="container">
        <!-- Login Section -->
        <div v-if="!isLoggedIn" class="login-container">
          <div class="login-card">
            <h2>Login</h2>
            <form @submit.prevent="login">
              <div class="form-group">
                <label for="login_username">Username</label>
                <input 
                  type="text" 
                  id="login_username" 
                  v-model="loginForm.username" 
                  required 
                  placeholder="Enter username"
                >
              </div>
              
              <div class="form-group">
                <label for="login_password">Password</label>
                <input 
                  type="password" 
                  id="login_password" 
                  v-model="loginForm.password" 
                  required 
                  placeholder="Enter password"
                >
              </div>
              
              <button type="submit" class="btn btn-primary btn-block">Login</button>
            </form>
            
            <div v-if="loginError" class="error-message">
              {{ loginError }}
            </div>
          </div>
        </div>
      
      <!-- Navigation Tabs and Main Content (only show when logged in) -->
      <div v-if="isLoggedIn">
        <NavigationTabs 
          :active-section="activeSection"
          :current-user="currentUser"
          @section-change="activeSection = $event"
          @logout="logout"
        />
      
      <!-- Items Section -->
      <div v-if="activeSection === 'items'" class="card">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
          <h2>Tuotteet</h2>
          <button class="btn btn-primary" @click="showAddModal">Lisää uusi tuote</button>
        </div>
        
        <div v-if="loading" class="loading">
          Ladataan tuotteita...
        </div>
        
        <div v-else-if="items.length === 0" class="loading">
          Tuotteita ei löytynyt. Lisää ensimmäinen tuote!
        </div>
        
        <table v-else class="table">
          <thead>
            <tr>
              <th>Tunniste</th>
              <th>Nimi</th>
              <th>Kuvaus</th>
              <th>Sarjanumero</th>
              <th>Määrä</th>
              <th>Hinta</th>
              <th>Ostopäivä</th>
              <th>Kuva</th>
              <th>Luotu</th>
              <th>Toiminnot</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in items" :key="item.id">
              <td>{{ item.id }}</td>
              <td>{{ item.name }}</td>
              <td>{{ item.description || '-' }}</td>
              <td>{{ item.serial_number || '-' }}</td>
              <td>{{ item.quantity }}</td>
              <td>{{ formatCurrency(item.price) }}</td>
              <td>{{ formatDate(item.date_of_purchase) }}</td>
              <td>
                <img v-if="item.picture" :src="item.picture" :alt="item.name" style="width: 50px; height: 50px; object-fit: cover; border-radius: 4px;">
                <span v-else>-</span>
              </td>
              <td>{{ formatDate(item.created_at) }}</td>
              <td>
                <div class="actions">
                  <button class="btn btn-primary" @click="viewItemDetails(item)">Tiedot</button>
                  <button class="btn btn-warning" @click="editItem(item)">Muokkaa</button>
                  <button class="btn btn-danger" @click="deleteItem(item.id)">Poista</button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- Customers Section -->
      <div v-if="activeSection === 'clients'" class="card">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
          <h2>Asiakkaat</h2>
          <div style="display: flex; gap: 10px;">
            <input 
              type="text" 
              v-model="clientSearch" 
              placeholder="Etsi asiakkaita..." 
              @input="searchClients"
              style="padding: 8px; border: 1px solid #ddd; border-radius: 4px;"
            >
            <button class="btn btn-primary" @click="showAddClientModal">Lisää uusi asiakas</button>
          </div>
        </div>
        
        <div v-if="clientsLoading" class="loading">
          Ladataan asiakkaita...
        </div>
        
        <div v-else-if="clients.length === 0" class="loading">
          Asiakkaita ei löytynyt. Lisää ensimmäinen asiakas!
        </div>
        
        <table v-else class="table">
          <thead>
            <tr>
              <th>Tunniste</th>
              <th>Nimi</th>
              <th>Yritys</th>
              <th>Sähköposti</th>
              <th>Puhelin</th>
              <th>Kaupunki</th>
              <th>Tuntihinta</th>
              <th>Yhteyshenkilöt</th>
              <th>Toiminnot</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="client in clients" :key="client.id">
              <td>{{ client.id }}</td>
              <td>{{ client.first_name }} {{ client.last_name }}</td>
              <td>{{ client.company_name || '-' }}</td>
              <td>{{ client.email }}</td>
              <td>{{ client.phone || '-' }}</td>
              <td>{{ client.city || '-' }}</td>
              <td>{{ client.hour_price ? '€' + parseFloat(client.hour_price).toFixed(2) : '-' }}</td>
              <td>
                <div class="contact-persons">
                  <div v-if="client.contact_persons && client.contact_persons.length > 0" class="contact-list">
                    <div v-for="contact in client.contact_persons.slice(0, 2)" :key="contact.id" class="contact-item">
                      {{ contact.first_name }} {{ contact.last_name }}
                      <span v-if="contact.is_primary" class="primary-badge">P</span>
                    </div>
                    <span v-if="client.contact_persons.length > 2" class="more-contacts">
                      +{{ client.contact_persons.length - 2 }} lisää
                    </span>
                  </div>
                  <div v-else class="no-contacts">
                    Ei yhteyshenkilöitä
                  </div>
                  <button class="btn btn-sm btn-primary" @click="manageContacts(client)">
                    Hallitse
                  </button>
                </div>
              </td>
              <td>
                <div class="actions">
                  <button class="btn btn-warning" @click="editClient(client)">Muokkaa</button>
                  <button class="btn btn-danger" @click="deleteClient(client.id)">Poista</button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- Projects Section -->
      <div v-if="activeSection === 'projects'" class="card">
        <ProjectsSection
          :active-section="activeSection"
          :projects="projects"
          :projects-loading="projectsLoading"
          :project-search="projectSearch"
          @add-project="showAddProjectModal"
          @view-project="viewProject"
          @edit-project="editProject"
          @delete-project="deleteProject"
          @search-projects="searchProjects"
          @show-tasks="handleShowTasks"
        />
      </div>
      
      <!-- Users Section -->
      <div v-if="activeSection === 'users'" class="card">
        <UsersSection
          :active-section="activeSection"
          :users="users"
          :users-loading="usersLoading"
          :user-search="userSearch"
          @add-user="showAddUserModal"
          @view-user="viewUser"
          @edit-user="editUser"
          @delete-user="deleteUser"
          @search-users="searchUsers"
        />
      </div>
      
      <!-- Chart of Accounts Section -->
      <div v-if="activeSection === 'chart-of-accounts'" class="card">
        <ChartOfAccountsSection
          :active-section="activeSection"
          :accounts="accounts"
          :accounts-loading="accountsLoading"
          :account-search="accountSearch"
          @add-account="showAddAccountModal"
          @view-account="viewAccount"
          @edit-account="editAccount"
          @delete-account="deleteAccount"
          @search-accounts="searchAccounts"
        />
      </div>
      
      <!-- Excel Accounting Section -->
      <ExcelAccountingSection
        v-if="activeSection === 'accounting'"
        :active-section="activeSection"
      />
      
      <!-- Tuloslaskelma Section -->
      <TuloslaskelmaSection
        v-if="activeSection === 'tuloslaskelma'"
        :active-section="activeSection"
      />
      
      <!-- ALV-laskenta Section -->
      <ALVLaskentaSection
        v-if="activeSection === 'alv-laskenta'"
        :active-section="activeSection"
      />
      
      <!-- Tasks Section -->
      <TaskManagementSection
        v-if="activeSection === 'tasks'"
        :active-section="activeSection"
      />
      
      <!-- User Management Section (Admin Only) -->
      <UserManagement
        v-if="activeSection === 'user-management' && currentUser && currentUser.role === 'admin'"
        :current-user="currentUser"
        @success="showSuccess"
        @error="showError"
      />
      
      <!-- Profile Management Section (All Users) -->
      <ProfileManagement
        v-if="activeSection === 'profile' && currentUser"
        :current-user="currentUser"
        @success="showSuccess"
        @error="showError"
      />
      </div>
    </div>
    </header>
    
    <main class="container">
      <!-- Add/Edit Modal -->
    <div v-if="showModal" class="modal" @click.self="closeModal">
      <div class="modal-content">
        <span class="close" @click="closeModal">&times;</span>
        <h2>{{ isEditing ? 'Muokkaa tuotetta' : 'Lisää uusi tuote' }}</h2>
        
        <form @submit.prevent="saveItem">
          <div class="form-group">
            <label for="name">Nimi *</label>
            <input 
              type="text" 
              id="name" 
              v-model="formData.name" 
              required 
              placeholder="Syötä tuotteen nimi"
            >
          </div>
          
          <div class="form-group">
            <label for="description">Kuvaus</label>
            <textarea 
              id="description" 
              v-model="formData.description" 
              placeholder="Syötä tuotteen kuvaus"
            ></textarea>
          </div>
          
          <div class="form-group">
            <label for="serial_number">Sarjanumero</label>
            <input 
              type="text" 
              id="serial_number" 
              v-model="formData.serial_number" 
              placeholder="Syötä sarjanumero"
            >
          </div>
          
          <div class="form-group">
            <label for="picture">Kuva</label>
            <input 
              type="file" 
              id="picture" 
              @change="handleFileUpload" 
              accept="image/*"
            >
            <div v-if="formData.picture" style="margin-top: 10px;">
              <img :src="formData.picture" :alt="formData.name" style="max-width: 200px; max-height: 200px; border-radius: 4px;">
            </div>
          </div>
          
          <div class="form-group">
            <label for="quantity">Quantity *</label>
            <input 
              type="number" 
              id="quantity" 
              v-model="formData.quantity" 
              required 
              min="0"
              placeholder="Enter quantity"
            >
          </div>
          
          <div class="form-group">
            <label for="price">Price *</label>
            <input 
              type="number" 
              id="price" 
              v-model="formData.price" 
              required 
              min="0" 
              step="0.01"
              placeholder="Enter price"
            >
          </div>
          
          <div class="form-group">
            <label for="date_of_purchase">Date of Purchase</label>
            <input 
              type="date" 
              id="date_of_purchase" 
              v-model="formData.date_of_purchase" 
              placeholder="Select date of purchase"
            >
          </div>
          
          <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
            <button type="button" class="btn" @click="closeModal">Peruuta</button>
            <button type="submit" class="btn btn-success">
              {{ isEditing ? 'Päivitä' : 'Lisää' }} tuote
            </button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- Item Details Modal -->
    <div v-if="showDetailsModal" class="modal" @click.self="closeDetailsModal">
      <div class="modal-content" style="max-width: 800px;">
        <span class="close" @click="closeDetailsModal">&times;</span>
        <h2>Tuotteen tiedot: {{ selectedItem.name }}</h2>
        
        <div class="tabs">
          <button 
            :class="['tab-btn', { active: activeTab === 'info' }]" 
            @click="activeTab = 'info'"
          >
            Tiedot
          </button>
          <button 
            :class="['tab-btn', { active: activeTab === 'rental' }]" 
            @click="activeTab = 'rental'"
          >
            Vuokrahinnat
          </button>
          <button 
            :class="['tab-btn', { active: activeTab === 'attachments' }]" 
            @click="activeTab = 'attachments'"
          >
            Tiedostot
          </button>
          <button 
            :class="['tab-btn', { active: activeTab === 'contacts' }]" 
            @click="activeTab = 'contacts'"
          >
            Yhteyshenkilöt
          </button>
        </div>
        
        <!-- Information Tab -->
        <div v-if="activeTab === 'info'" class="tab-content">
          <div class="item-info">
            <div class="info-row">
              <strong>ID:</strong> {{ selectedItem.id }}
            </div>
            <div class="info-row">
              <strong>Name:</strong> {{ selectedItem.name }}
            </div>
            <div class="info-row">
              <strong>Description:</strong> {{ selectedItem.description || 'No description' }}
            </div>
            <div class="info-row">
              <strong>Serial Number:</strong> {{ selectedItem.serial_number || 'No serial number' }}
            </div>
            <div class="info-row">
              <strong>Quantity:</strong> {{ selectedItem.quantity }}
            </div>
            <div class="info-row">
              <strong>Price:</strong> ${{ parseFloat(selectedItem.price).toFixed(2) }}
            </div>
            <div class="info-row">
              <strong>Created:</strong> {{ formatDate(selectedItem.created_at) }}
            </div>
            <div class="info-row" v-if="selectedItem.picture">
              <strong>Picture:</strong><br>
              <img :src="selectedItem.picture" :alt="selectedItem.name" style="max-width: 300px; border-radius: 4px; margin-top: 10px;">
            </div>
          </div>
        </div>
        
        <!-- Rental Prices Tab -->
        <div v-if="activeTab === 'rental'" class="tab-content">
          <div style="margin-bottom: 20px;">
            <button class="btn btn-primary" @click="showAddRentalModal">Add Rental Price</button>
          </div>
          
          <div v-if="rentalPrices.length === 0" class="loading">
            No rental prices found.
          </div>
          
          <table v-else class="table">
            <thead>
              <tr>
                <th>Client</th>
                <th>Start Date</th>
                <th>End Date</th>
                <th>Daily Price</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="rental in rentalPrices" :key="rental.id">
                <td>{{ getClientName(rental.client_id) }}</td>
                <td>{{ formatDate(rental.start_date) }}</td>
                <td>{{ formatDate(rental.end_date) }}</td>
                <td>${{ parseFloat(rental.daily_price).toFixed(2) }}</td>
                <td>
                  <button class="btn btn-danger" @click="deleteRentalPrice(rental.id)">Delete</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        
        <!-- Contact Persons Tab -->
        <div v-if="activeTab === 'contacts'" class="tab-content">
          <div style="margin-bottom: 20px;">
            <button class="btn btn-primary" @click="showAddContactPersonModal">Add Contact Person</button>
          </div>
          
          <div v-if="contactPersons.length === 0" class="loading">
            No contact persons found.
          </div>
          
          <div v-else class="contacts-list">
            <div v-for="person in contactPersons" :key="person.id" class="contact-person-item">
              <div class="contact-person-info">
                <strong>{{ person.first_name }} {{ person.last_name }}</strong>
                <span v-if="person.position" class="contact-position">- {{ person.position }}</span>
                <span v-if="person.is_primary" class="contact-primary">(Primary)</span>
              </div>
              <div class="contact-person-details">
                <div v-if="person.email">📧 {{ person.email }}</div>
                <div v-if="person.phone">📞 {{ person.phone }}</div>
              </div>
              <div class="contact-person-actions">
                <button class="btn btn-warning" @click="editContactPerson(person)">Edit</button>
                <button class="btn btn-danger" @click="deleteContactPerson(person.id)">Delete</button>
              </div>
            </div>
          </div>
        </div>
        
        <!-- Attachments Tab -->
        <div v-if="activeTab === 'attachments'" class="tab-content">
          <div style="margin-bottom: 20px;">
            <button class="btn btn-primary" @click="showAddAttachmentModal">Add Attachment</button>
          </div>
          
          <div v-if="attachments.length === 0" class="loading">
            No attachments found.
          </div>
          
          <div v-else class="attachments-list">
            <div v-for="attachment in attachments" :key="attachment.id" class="attachment-item">
              <div class="attachment-info">
                <strong>{{ attachment.original_name }}</strong>
                <span class="attachment-type">{{ attachment.file_type }}</span>
                <span class="attachment-size">({{ formatFileSize(attachment.file_size) }})</span>
              </div>
              <div class="attachment-actions">
                <a :href="`/uploads/${attachment.file_path}`" target="_blank" class="btn btn-primary">View</a>
                <button class="btn btn-danger" @click="deleteAttachment(attachment.id)">Delete</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- Add Rental Price Modal -->
    <div v-if="showRentalModal" class="modal" @click.self="closeRentalModal">
      <div class="modal-content">
        <span class="close" @click="closeRentalModal">&times;</span>
        <h2>Add Rental Price</h2>
        
        <form @submit.prevent="saveRentalPrice">
          <div class="form-group">
            <label for="client_id">Client</label>
            <select id="client_id" v-model="rentalForm.client_id">
              <option value="">Select client (optional)</option>
              <option v-for="client in clients" :key="client.id" :value="client.id">
                {{ client.company_name ? client.company_name + ' - ' : '' }}{{ client.first_name }} {{ client.last_name }}
              </option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="start_date">Start Date *</label>
            <input 
              type="date" 
              id="start_date" 
              v-model="rentalForm.start_date" 
              required
            >
          </div>
          
          <div class="form-group">
            <label for="end_date">End Date *</label>
            <input 
              type="date" 
              id="end_date" 
              v-model="rentalForm.end_date" 
              required
            >
          </div>
          
          <div class="form-group">
            <label for="daily_price">Daily Price *</label>
            <input 
              type="number" 
              id="daily_price" 
              v-model="rentalForm.daily_price" 
              required 
              min="0" 
              step="0.01"
              placeholder="Enter daily price"
            >
          </div>
          
          <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
            <button type="button" class="btn" @click="closeRentalModal">Cancel</button>
            <button type="submit" class="btn btn-success">Add Rental Price</button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- Add Attachment Modal -->
    <div v-if="showAttachmentModal" class="modal" @click.self="closeAttachmentModal">
      <div class="modal-content">
        <span class="close" @click="closeAttachmentModal">&times;</span>
        <h2>Add Attachment</h2>
        
        <form @submit.prevent="saveAttachment">
          <div class="form-group">
            <label for="file_type">Document Type *</label>
            <select id="file_type" v-model="attachmentForm.file_type" required>
              <option value="">Select type</option>
              <option value="receipt">Receipt</option>
              <option value="warranty">Warranty</option>
              <option value="other">Other</option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="attachment_file">File *</label>
            <input 
              type="file" 
              id="attachment_file" 
              @change="handleAttachmentUpload" 
              required
              accept=".pdf,.doc,.docx,.txt,.jpg,.jpeg,.png,.gif"
            >
          </div>
          
          <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
            <button type="button" class="btn" @click="closeAttachmentModal">Cancel</button>
            <button type="submit" class="btn btn-success">Add Attachment</button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- Accounting Section (Hidden - ExcelAccounting is in use) -->
    <!-- <AccountingSection
      :active-section="activeSection"
      :invoices="invoices"
      :invoices-loading="invoicesLoading"
      :journal-entries="journalEntries"
      :journal-entries-loading="journalEntriesLoading"
      :transactions="transactions"
      :transactions-loading="transactionsLoading"
      :search-term="accountingSearch"
      @add-invoice="showAddInvoiceModal"
      @view-invoice="viewInvoice"
      @edit-invoice="editInvoice"
      @delete-invoice="deleteInvoice"
      @search-invoices="searchInvoices"
      @add-journal-entry="showAddJournalEntryModal"
      @view-journal-entry="viewJournalEntry"
      @edit-journal-entry="editJournalEntry"
      @delete-journal-entry="deleteJournalEntry"
      @search="searchAccounting"
    /> -->
    
    <!-- Add/Edit Client Modal -->
    <div v-if="showClientModal" class="modal" @click.self="closeClientModal">
      <div class="modal-content">
        <span class="close" @click="closeClientModal">&times;</span>
        <h2>{{ isEditingClient ? 'Edit Client' : 'Add New Client' }}</h2>
        
        <form @submit.prevent="saveClient">
          <div class="form-group">
            <label for="y_tunnus">Y-Tunnus</label>
            <input 
              type="text" 
              id="y_tunnus" 
              v-model="clientForm.y_tunnus" 
              placeholder="Enter Y-tunnus"
            >
          </div>
          
          <div class="form-group">
            <label for="company_name">Company Name</label>
            <input 
              type="text" 
              id="company_name" 
              v-model="clientForm.company_name" 
              placeholder="Enter company name"
            >
          </div>
          
          <div class="form-group">
            <label for="first_name">First Name *</label>
            <input 
              type="text" 
              id="first_name" 
              v-model="clientForm.first_name" 
              required 
              placeholder="Enter first name"
            >
          </div>
          
          <div class="form-group">
            <label for="last_name">Last Name *</label>
            <input 
              type="text" 
              id="last_name" 
              v-model="clientForm.last_name" 
              required 
              placeholder="Enter last name"
            >
          </div>
          
          <div class="form-group">
            <label for="email">Email *</label>
            <input 
              type="email" 
              id="email" 
              v-model="clientForm.email" 
              required 
              placeholder="Enter email address"
            >
          </div>
          
          <div class="form-group">
            <label for="phone">Phone</label>
            <input 
              type="tel" 
              id="phone" 
              v-model="clientForm.phone" 
              placeholder="Enter phone number"
            >
          </div>
          
          <div class="form-group">
            <label for="address">Address</label>
            <input 
              type="text" 
              id="address" 
              v-model="clientForm.address" 
              placeholder="Enter street address"
            >
          </div>
          
          <div class="form-group">
            <label for="city">City</label>
            <input 
              type="text" 
              id="city" 
              v-model="clientForm.city" 
              placeholder="Enter city"
            >
          </div>
          
          <div class="form-group">
            <label for="state">State/Province</label>
            <input 
              type="text" 
              id="state" 
              v-model="clientForm.state" 
              placeholder="Enter state or province"
            >
          </div>
          
          <div class="form-group">
            <label for="postal_code">Postal Code</label>
            <input 
              type="text" 
              id="postal_code" 
              v-model="clientForm.postal_code" 
              placeholder="Enter postal code"
            >
          </div>
          
          <div class="form-group">
            <label for="country">Country</label>
            <input 
              type="text" 
              id="country" 
              v-model="clientForm.country" 
              placeholder="Enter country"
            >
          </div>
          
          <div class="form-group">
            <label for="hour_price">Hour Price (€)</label>
            <input 
              type="number" 
              id="hour_price" 
              v-model="clientForm.hour_price" 
              step="0.01"
              min="0"
              placeholder="Enter hourly rate"
            >
          </div>
          
          <div class="form-group">
            <label for="notes">Notes</label>
            <textarea 
              id="notes" 
              v-model="clientForm.notes" 
              placeholder="Enter any additional notes"
              rows="3"
            ></textarea>
          </div>
          
          <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
            <button type="button" class="btn" @click="closeClientModal">Cancel</button>
            <button type="submit" class="btn btn-success">
              {{ isEditingClient ? 'Update' : 'Add' }} Client
            </button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- Add/Edit Contact Person Modal -->
    <div v-if="showContactPersonModal" class="modal" @click.self="closeContactPersonModal">
      <div class="modal-content">
        <span class="close" @click="closeContactPersonModal">&times;</span>
        <h2>{{ isEditingContactPerson ? 'Edit Contact Person' : 'Add Contact Person' }}</h2>
        
        <form @submit.prevent="saveContactPerson">
          <div class="form-group">
            <label for="contact_first_name">First Name *</label>
            <input 
              type="text" 
              id="contact_first_name" 
              v-model="contactPersonForm.first_name" 
              required 
              placeholder="Enter first name"
            >
          </div>
          
          <div class="form-group">
            <label for="contact_last_name">Last Name *</label>
            <input 
              type="text" 
              id="contact_last_name" 
              v-model="contactPersonForm.last_name" 
              required 
              placeholder="Enter last name"
            >
          </div>
          
          <div class="form-group">
            <label for="contact_email">Email</label>
            <input 
              type="email" 
              id="contact_email" 
              v-model="contactPersonForm.email" 
              placeholder="Enter email address"
            >
          </div>
          
          <div class="form-group">
            <label for="contact_phone">Phone</label>
            <input 
              type="tel" 
              id="contact_phone" 
              v-model="contactPersonForm.phone" 
              placeholder="Enter phone number"
            >
          </div>
          
          <div class="form-group">
            <label for="contact_position">Position</label>
            <input 
              type="text" 
              id="contact_position" 
              v-model="contactPersonForm.position" 
              placeholder="Enter position/title"
            >
          </div>
          
          <div class="form-group">
            <label>
              <input 
                type="checkbox" 
                id="contact_is_primary" 
                v-model="contactPersonForm.is_primary"
              >
              Primary Contact
            </label>
          </div>
          
          <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
            <button type="button" class="btn" @click="closeContactPersonModal">Cancel</button>
            <button type="submit" class="btn btn-success">
              {{ isEditingContactPerson ? 'Update' : 'Add' }} Contact Person
            </button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- Invoice Items Modal -->
    <div v-if="showInvoiceItemsModal" class="modal" @click.self="closeInvoiceItemsModal">
      <div class="modal-content">
        <span class="close" @click="closeInvoiceItemsModal">&times;</span>
        <h2>{{ invoiceItemsForm.id ? 'Edit Invoice Item' : 'Add Invoice Item' }}</h2>
        
        <form @submit.prevent="saveInvoiceItem">
          <div class="form-group">
            <label for="item_id">Item *</label>
            <select id="item_id" v-model="invoiceItemsForm.item_id" required>
              <option value="">Select item</option>
              <option v-for="item in items" :key="item.id" :value="item.id">{{ item.name }}</option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="item_description">Description</label>
            <input 
              type="text" 
              id="item_description" 
              v-model="invoiceItemsForm.description" 
              placeholder="Enter item description"
            >
          </div>
          
          <div class="form-group">
            <label for="item_quantity">Quantity *</label>
            <input 
              type="number" 
              id="item_quantity" 
              v-model="invoiceItemsForm.quantity" 
              required 
              min="0.01" 
              step="0.01"
              placeholder="Enter quantity"
            >
          </div>
          
          <div class="form-group">
            <label for="item_unit_price">Unit Price *</label>
            <input 
              type="number" 
              id="item_unit_price" 
              v-model="invoiceItemsForm.unit_price" 
              required 
              min="0.01" 
              step="0.01"
              placeholder="Enter unit price"
            >
          </div>
          
          <div class="form-group">
            <label for="item_line_total">Line Total</label>
            <input 
              type="number" 
              id="item_line_total" 
              v-model="invoiceItemsForm.line_total" 
              required 
              min="0.01" 
              step="0.01"
              placeholder="Enter line total"
            >
          </div>
          
          <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
            <button type="button" class="btn" @click="closeInvoiceItemsModal">Cancel</button>
            <button type="submit" class="btn btn-success">
              {{ invoiceItemsForm.id ? 'Update' : 'Add' }} Item
            </button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- Invoice Details Modal -->
    <div v-if="showInvoiceModal" class="modal" @click.self="closeInvoiceModal">
      <div class="modal-content" style="max-width: 900px;">
        <span class="close" @click="closeInvoiceModal">&times;</span>
        <h2>{{ isEditingInvoice ? 'Edit Invoice' : 'Create Invoice' }}</h2>
        
        <form @submit.prevent="saveInvoice">
          <div class="form-group">
            <label for="invoice_client_id">Client *</label>
            <select id="invoice_client_id" v-model="invoiceForm.client_id" required>
              <option value="">Select client</option>
              <option v-for="client in clients" :key="client.id" :value="client.id">{{ client.first_name }} {{ client.last_name }}</option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="invoice_number">Invoice Number *</label>
            <input 
              type="text" 
              id="invoice_number" 
              v-model="invoiceForm.invoice_number" 
              required 
              placeholder="Enter invoice number"
            >
          </div>
          
          <div class="form-group">
            <label for="issue_date">Issue Date *</label>
            <input 
              type="date" 
              id="issue_date" 
              v-model="invoiceForm.issue_date" 
              required
            >
          </div>
          
          <div class="form-group">
            <label for="due_date">Due Date *</label>
            <input 
              type="date" 
              id="due_date" 
              v-model="invoiceForm.due_date" 
              required
            >
          </div>
          
          <div class="form-group">
            <label for="invoice_status">Status</label>
            <select id="invoice_status" v-model="invoiceForm.status">
              <option value="draft">Draft</option>
              <option value="sent">Sent</option>
              <option value="paid">Paid</option>
              <option value="overdue">Overdue</option>
              <option value="cancelled">Cancelled</option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="invoice_subtotal">Subtotal</label>
            <input 
              type="number" 
              id="invoice_subtotal" 
              v-model="invoiceForm.subtotal" 
              min="0.01" 
              step="0.01"
              placeholder="Enter subtotal"
            >
          </div>
          
          <div class="form-group">
            <label for="invoice_tax_amount">Tax Amount</label>
            <input 
              type="number" 
              id="invoice_tax_amount" 
              v-model="invoiceForm.tax_amount" 
              min="0.01" 
              step="0.01"
              placeholder="Enter tax amount"
            >
          </div>
          
          <div class="form-group">
            <label for="invoice_total_amount">Total Amount</label>
            <input 
              type="number" 
              id="invoice_total_amount" 
              v-model="invoiceForm.total_amount" 
              min="0.01" 
              step="0.01"
              placeholder="Enter total amount"
            >
          </div>
          
          <div class="form-group">
            <label for="invoice_notes">Notes</label>
            <textarea 
              id="invoice_notes" 
              v-model="invoiceForm.notes" 
              placeholder="Enter any notes"
              rows="3"
            ></textarea>
          </div>
          
          <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
            <button type="button" class="btn" @click="closeInvoiceModal">Cancel</button>
            <button type="submit" class="btn btn-success">
              {{ isEditingInvoice ? 'Update' : 'Create' }} Invoice
            </button>
          </div>
        </form>
        
        <!-- Invoice Items -->
        <div v-if="selectedInvoice.id" style="margin-top: 20px;">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h3>Invoice Items</h3>
            <button class="btn btn-primary" @click="showAddInvoiceItemModal">Add Item</button>
          </div>
          
          <div v-if="invoiceItems.length === 0" class="loading">
            No items found for this invoice.
          </div>
          
          <table v-else class="table">
            <thead>
              <tr>
                <th>Item</th>
                <th>Description</th>
                <th>Quantity</th>
                <th>Unit Price</th>
                <th>Line Total</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item in invoiceItems" :key="item.id">
                <td>{{ item.item_name }}</td>
                <td>{{ item.description }}</td>
                <td>{{ item.quantity }}</td>
                <td>${{ parseFloat(item.unit_price).toFixed(2) }}</td>
                <td>${{ parseFloat(item.line_total).toFixed(2) }}</td>
                <td>
                  <div class="actions">
                    <button class="btn btn-warning" @click="editInvoiceItem(item)">Edit</button>
                    <button class="btn btn-danger" @click="deleteInvoiceItem(item.id)">Delete</button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    
    <!-- User Modal -->
    <div v-if="showUserModal" class="modal" @click.self="closeUserModal">
      <div class="modal-content">
        <span class="close" @click="closeUserModal">&times;</span>
        <h2>{{ isEditingUser ? 'Edit User' : 'User Details' }}</h2>
        
        <div v-if="!isEditingUser">
          <!-- View Mode -->
          <div class="user-details">
            <div class="detail-row">
              <strong>ID:</strong> {{ selectedUser.id }}
            </div>
            <div class="detail-row">
              <strong>Username:</strong> {{ selectedUser.username }}
            </div>
            <div class="detail-row">
              <strong>Name:</strong> {{ selectedUser.first_name }} {{ selectedUser.last_name }}
            </div>
            <div class="detail-row">
              <strong>Email:</strong> {{ selectedUser.email }}
            </div>
            <div class="detail-row">
              <strong>Role:</strong> {{ selectedUser.role || 'User' }}
            </div>
            <div class="detail-row">
              <strong>Status:</strong> {{ selectedUser.is_active ? 'Active' : 'Inactive' }}
            </div>
            <div class="detail-row">
              <strong>Created:</strong> {{ formatDateTime(selectedUser.created_at) }}
            </div>
            <div class="detail-row">
              <strong>Last Login:</strong> {{ formatDateTime(selectedUser.last_login) || 'Never' }}
            </div>
          </div>
          
          <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
            <button type="button" class="btn btn-warning" @click="editUser(selectedUser)">Edit User</button>
            <button type="button" class="btn" @click="closeUserModal">Close</button>
          </div>
        </div>
        
        <form v-else @submit.prevent="saveUser">
          <!-- Edit Mode -->
          <div class="form-group">
            <label for="username">Username *</label>
            <input 
              type="text" 
              id="username" 
              v-model="userForm.username" 
              required 
              placeholder="Enter username"
            >
          </div>
          
          <div class="form-group">
            <label for="first_name">First Name *</label>
            <input 
              type="text" 
              id="first_name" 
              v-model="userForm.first_name" 
              required 
              placeholder="Enter first name"
            >
          </div>
          
          <div class="form-group">
            <label for="last_name">Last Name *</label>
            <input 
              type="text" 
              id="last_name" 
              v-model="userForm.last_name" 
              required 
              placeholder="Enter last name"
            >
          </div>
          
          <div class="form-group">
            <label for="email">Email *</label>
            <input 
              type="email" 
              id="email" 
              v-model="userForm.email" 
              required 
              placeholder="Enter email"
            >
          </div>
          
          <div class="form-group">
            <label for="role">Role</label>
            <select id="role" v-model="userForm.role">
              <option value="user">User</option>
              <option value="admin">Admin</option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="password">Password</label>
            <input 
              type="password" 
              id="password" 
              v-model="userForm.password" 
              placeholder="Leave blank to keep current password"
            >
          </div>
          
          <div class="form-group">
            <label>
              <input type="checkbox" v-model="userForm.is_active">
              Active
            </label>
          </div>
          
          <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
            <button type="button" class="btn" @click="closeUserModal">Cancel</button>
            <button type="submit" class="btn btn-success">
              {{ userForm.id ? 'Update' : 'Add' }} User
            </button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- Project Modal -->
    <div v-if="showProjectModal" class="modal" @click.self="closeProjectModal">
      <div class="modal-content">
        <span class="close" @click="closeProjectModal">&times;</span>
        <h2>{{ isEditingProject ? 'Edit Project' : 'Add New Project' }}</h2>
        
        <div v-if="!isEditingProject && selectedProject.id">
          <!-- View Mode -->
          <div class="project-details">
            <div class="detail-row">
              <strong>ID:</strong> {{ selectedProject.id }}
            </div>
            <div class="detail-row">
              <strong>Project Name:</strong> {{ selectedProject.project_name }}
            </div>
            <div class="detail-row">
              <strong>Customer:</strong> {{ getCustomerName(selectedProject.customer_id) || 'Not specified' }}
            </div>
            <div class="detail-row">
              <strong>Description:</strong> {{ selectedProject.description || 'No description' }}
            </div>
            <div class="detail-row">
              <strong>Status:</strong> {{ selectedProject.status || 'Unknown' }}
            </div>
            <div class="detail-row">
              <strong>Start Date:</strong> {{ formatDate(selectedProject.start_date) || 'Not set' }}
            </div>
            <div class="detail-row">
              <strong>End Date:</strong> {{ formatDate(selectedProject.end_date) || 'Not set' }}
            </div>
            <div class="detail-row">
              <strong>Budget:</strong> {{ formatCurrency(selectedProject.budget) || 'Not set' }}
            </div>
            <div class="detail-row">
              <strong>Created:</strong> {{ formatDateTime(selectedProject.created_at) }}
            </div>
          </div>
          
          <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
            <button type="button" class="btn btn-warning" @click="editProject(selectedProject)">Edit Project</button>
            <button type="button" class="btn" @click="closeProjectModal">Close</button>
          </div>
        </div>
        
        <form v-else @submit.prevent="saveProject">
          <!-- Add/Edit Mode -->
          <div class="form-group">
            <label for="project_name">Project Name *</label>
            <input 
              type="text" 
              id="project_name" 
              v-model="projectForm.project_name" 
              required 
              placeholder="Enter project name"
            >
          </div>
          
          <div class="form-group">
            <label for="customer_id">Customer *</label>
            <select 
              id="customer_id" 
              v-model="projectForm.customer_id" 
              required
            >
              <option value="">Select a customer</option>
              <option 
                v-for="client in clients" 
                :key="client.id" 
                :value="client.id"
              >
                {{ client.company_name || (client.first_name + ' ' + client.last_name) }}
              </option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="description">Description</label>
            <textarea 
              id="description" 
              v-model="projectForm.description" 
              placeholder="Enter project description"
              rows="3"
            ></textarea>
          </div>
          
          <div class="form-group">
            <label for="status">Status</label>
            <select id="status" v-model="projectForm.status">
              <option value="planning">Planning</option>
              <option value="in_progress">In Progress</option>
              <option value="completed">Completed</option>
              <option value="on_hold">On Hold</option>
              <option value="cancelled">Cancelled</option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="start_date">Start Date</label>
            <input 
              type="date" 
              id="start_date" 
              v-model="projectForm.start_date"
            >
          </div>
          
          <div class="form-group">
            <label for="end_date">End Date</label>
            <input 
              type="date" 
              id="end_date" 
              v-model="projectForm.end_date"
            >
          </div>
          
          <div class="form-group">
            <label for="budget">Budget</label>
            <input 
              type="number" 
              id="budget" 
              v-model="projectForm.budget" 
              step="0.01"
              placeholder="Enter project budget"
            >
          </div>
          
          <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
            <button type="button" class="btn" @click="closeProjectModal">Cancel</button>
            <button type="submit" class="btn btn-success">
              {{ projectForm.id ? 'Update' : 'Add' }} Project
            </button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- Contact Persons Modal -->
    <div v-if="showContactModal" class="modal" @click.self="closeContactModal">
      <div class="modal-content">
        <span class="close" @click="closeContactModal">&times;</span>
        <h2>Manage Contacts - {{ selectedCustomer.company_name || (selectedCustomer.first_name + ' ' + selectedCustomer.last_name) }}</h2>
        
        <div class="contacts-management">
          <!-- Add New Contact Form -->
          <div class="add-contact-section">
            <h3>Add New Contact</h3>
            <form @submit.prevent="addContact">
              <div class="form-row">
                <div class="form-group">
                  <label for="contact_first_name">First Name *</label>
                  <input 
                    type="text" 
                    id="contact_first_name" 
                    v-model="contactForm.first_name" 
                    required 
                    placeholder="Enter first name"
                  >
                </div>
                <div class="form-group">
                  <label for="contact_last_name">Last Name *</label>
                  <input 
                    type="text" 
                    id="contact_last_name" 
                    v-model="contactForm.last_name" 
                    required 
                    placeholder="Enter last name"
                  >
                </div>
              </div>
              
              <div class="form-row">
                <div class="form-group">
                  <label for="contact_email">Email</label>
                  <input 
                    type="email" 
                    id="contact_email" 
                    v-model="contactForm.email" 
                    placeholder="Enter email"
                  >
                </div>
                <div class="form-group">
                  <label for="contact_phone">Phone</label>
                  <input 
                    type="text" 
                    id="contact_phone" 
                    v-model="contactForm.phone" 
                    placeholder="Enter phone"
                  >
                </div>
              </div>
              
              <div class="form-row">
                <div class="form-group">
                  <label for="contact_position">Position</label>
                  <input 
                    type="text" 
                    id="contact_position" 
                    v-model="contactForm.position" 
                    placeholder="Enter position"
                  >
                </div>
                <div class="form-group">
                  <label for="contact_department">Department</label>
                  <input 
                    type="text" 
                    id="contact_department" 
                    v-model="contactForm.department" 
                    placeholder="Enter department"
                  >
                </div>
              </div>
              
              <div class="form-group">
                <label for="contact_notes">Notes</label>
                <textarea 
                  id="contact_notes" 
                  v-model="contactForm.notes" 
                  placeholder="Enter notes"
                  rows="3"
                ></textarea>
              </div>
              
              <div class="form-group">
                <label>
                  <input type="checkbox" v-model="contactForm.is_primary">
                  Primary Contact
                </label>
              </div>
              
              <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
                <button type="button" class="btn" @click="resetContactForm">Clear</button>
                <button type="submit" class="btn btn-success">Add Contact</button>
              </div>
            </form>
          </div>
          
          <!-- Existing Contacts List -->
          <div class="existing-contacts-section">
            <h3>Existing Contacts</h3>
            <div v-if="customerContacts.length === 0" class="no-contacts">
              No contacts found for this customer.
            </div>
            <div v-else class="contacts-list">
              <div v-for="contact in customerContacts" :key="contact.id" class="contact-item">
                <div class="contact-info">
                  <h4>{{ contact.first_name }} {{ contact.last_name }}</h4>
                  <div class="contact-details">
                    <div v-if="contact.position" class="detail"><strong>Position:</strong> {{ contact.position }}</div>
                    <div v-if="contact.department" class="detail"><strong>Department:</strong> {{ contact.department }}</div>
                    <div v-if="contact.email" class="detail"><strong>Email:</strong> {{ contact.email }}</div>
                    <div v-if="contact.phone" class="detail"><strong>Phone:</strong> {{ contact.phone }}</div>
                    <div v-if="contact.notes" class="detail"><strong>Notes:</strong> {{ contact.notes }}</div>
                  </div>
                  <div class="contact-badges">
                    <span v-if="contact.is_primary" class="badge badge-primary">Primary</span>
                  </div>
                </div>
                <div class="contact-actions">
                  <button class="btn btn-sm btn-warning" @click="editContact(contact)">Edit</button>
                  <button class="btn btn-sm btn-danger" @click="deleteContact(contact.id)">Delete</button>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
          <button type="button" class="btn" @click="closeContactModal">Close</button>
        </div>
      </div>
    </div>
    </main>
  </div>
</template>

<script>
import api from './api/axios'
import { formatDate, formatCurrency, formatDateTime } from './utils/locale.js'
import NavigationTabs from './components/common/NavigationTabs.vue'
import ProjectsSection from './components/projects/ProjectsSection.vue'
import UsersSection from './components/users/UsersSection.vue'
import ChartOfAccountsSection from './components/accounting/ChartOfAccountsSection.vue'
import AccountingSection from './components/accounting/AccountingSection.vue'
import ExcelAccountingSection from './components/accounting/ExcelAccountingSection.vue'
import TuloslaskelmaSection from './components/accounting/TuloslaskelmaSection.vue'
import ALVLaskentaSection from './components/accounting/ALVLaskentaSection.vue'
import TaskManagementSection from './components/projects/TaskManagementSection.vue'
import UserManagement from './components/UserManagement.vue'
import ProfileManagement from './components/ProfileManagement.vue'

export default {
  name: 'App',
  components: {
    NavigationTabs,
    ProjectsSection,
    UsersSection,
    ChartOfAccountsSection,
    AccountingSection,
    ExcelAccountingSection,
    TuloslaskelmaSection,
    ALVLaskentaSection,
    TaskManagementSection,
    UserManagement,
    ProfileManagement
  },
  data() {
    return {
      activeSection: 'items',
      items: [],
      loading: false,
      showModal: false,
      isEditing: false,
      message: '',
      messageType: '',
      formData: {
        id: null,
        name: '',
        description: '',
        serial_number: '',
        picture: '',
        quantity: 0,
        price: 0,
        date_of_purchase: ''
      },
      showDetailsModal: false,
      selectedItem: {},
      activeTab: 'info',
      rentalPrices: [],
      attachments: [],
      showRentalModal: false,
      rentalForm: {
        item_id: null,
        client_id: null,
        start_date: '',
        end_date: '',
        daily_price: 0
      },
      showAttachmentModal: false,
      attachmentForm: {
        item_id: null,
        file_type: '',
        file: null
      },
      clients: [],
      clientsLoading: false,
      clientSearch: '',
      showClientModal: false,
      isEditingClient: false,
      clientForm: {
        id: null,
        y_tunnus: '',
        company_name: '',
        first_name: '',
        last_name: '',
        email: '',
        phone: '',
        address: '',
        city: '',
        state: '',
        postal_code: '',
        country: '',
        hour_price: '',
        notes: ''
      },
      contactPersons: [],
      contactPersonsLoading: false,
      contactPersonForm: {
        id: null,
        client_id: null,
        first_name: '',
        last_name: '',
        email: '',
        phone: '',
        position: '',
        is_primary: false
      },
      showContactPersonModal: false,
      isEditingContactPerson: false,
      // Authentication data
      isLoggedIn: false,
      currentUser: null,
      loginForm: {
        username: '',
        password: ''
      },
      loginError: '',
      invoices: [],
      invoicesLoading: false,
      invoiceSearch: '',
      showInvoiceModal: false,
      isEditingInvoice: false,
      selectedInvoice: {},
      invoiceForm: {
        id: null,
        client_id: null,
        invoice_number: '',
        issue_date: '',
        due_date: '',
        status: 'draft',
        subtotal: 0,
        tax_amount: 0,
        total_amount: 0,
        notes: ''
      },
      showInvoiceItemsModal: false,
      invoiceItems: [],
      invoiceItemsForm: {
        id: null,
        invoice_id: null,
        item_id: null,
        description: '',
        quantity: 1,
        unit_price: 0,
        line_total: 0
      },
      projects: [],
      projectsLoading: false,
      projectSearch: '',
      showProjectModal: false,
      isEditingProject: false,
      selectedProject: {},
      projectForm: {
        id: null,
        customer_id: null,
        project_name: '',
        description: '',
        status: 'planning',
        start_date: '',
        end_date: '',
        budget: 0
      },
      users: [],
      usersLoading: false,
      userSearch: '',
      showUserModal: false,
      isEditingUser: false,
      selectedUser: {},
      userForm: {
        id: null,
        username: '',
        email: '',
        first_name: '',
        last_name: '',
        role: 'user',
        is_active: true,
        password: ''
      },
      accounts: [],
      accountsLoading: false,
      accountSearch: '',
      showAccountModal: false,
      isEditingAccount: false,
      selectedAccount: {},
      accountForm: {
        id: null,
        account_number: '',
        account_name: '',
        account_type: 'asset',
        parent_id: null,
        description: '',
        opening_balance: 0,
        is_active: true
      },
      journalEntries: [],
      journalEntriesLoading: false,
      transactions: [],
      transactionsLoading: false,
      accountingSearch: '',
      selectedJournalEntry: {},
      // Contact persons data
      showContactModal: false,
      selectedCustomer: {},
      customerContacts: [],
      contactForm: {
        id: null,
        client_id: null,
        first_name: '',
        last_name: '',
        email: '',
        phone: '',
        position: '',
        department: '',
        is_primary: false,
        notes: ''
      }
    }
  },
  mounted() {
    // Check auth status on app load
    this.checkAuthStatus()
    
    // Add event listener for session expiration
    window.addEventListener('auth-expired', this.handleSessionExpired)
  },
  beforeUnmount() {
    // Remove event listener when component is destroyed
    window.removeEventListener('auth-expired', this.handleSessionExpired)
  },
  methods: {
    formatDate,
    formatCurrency,
    formatDateTime,
    async fetchItems() {
      this.loading = true
      try {
        const response = await api.get('/items.php')
        this.items = response.data.records || []
      } catch (error) {
        this.showMessage('Error fetching items: ' + error.message, 'error')
      } finally {
        this.loading = false
      }
    },
    
    async saveItem() {
      try {
        if (this.isEditing) {
          await api.put('/items.php', this.formData)
          this.showMessage('Item updated successfully!', 'success')
        } else {
          await api.post('/items.php', this.formData)
          this.showMessage('Item added successfully!', 'success')
        }
        
        this.closeModal()
        this.fetchItems()
      } catch (error) {
        this.showMessage('Error saving item: ' + error.message, 'error')
      }
    },
    
    async deleteItem(id) {
      if (!confirm('Are you sure you want to delete this item?')) {
        return
      }
      
      try {
        await api.delete(`/items.php?id=${id}`)
        this.showMessage('Item deleted successfully!', 'success')
        this.fetchItems()
      } catch (error) {
        this.showMessage('Error deleting item: ' + error.message, 'error')
      }
    },
    
    // User management methods
    showSuccess(message) {
      this.showMessage(message, 'success')
    },
    
    showError(message) {
      this.showMessage(message, 'error')
    },

    showAddModal() {
      this.isEditing = false
      this.formData = {
        id: null,
        name: '',
        description: '',
        serial_number: '',
        picture: '',
        quantity: 0,
        price: 0,
        date_of_purchase: ''
      }
      this.showModal = true
    },
    
    editItem(item) {
      this.isEditing = true
      this.formData = {
        id: item.id,
        name: item.name,
        description: item.description || '',
        serial_number: item.serial_number || '',
        picture: item.picture || '',
        quantity: item.quantity,
        price: item.price,
        date_of_purchase: item.date_of_purchase || ''
      }
      this.showModal = true
    },
    
    closeModal() {
      this.showModal = false
      this.formData = {
        id: null,
        name: '',
        description: '',
        serial_number: '',
        picture: '',
        quantity: 0,
        price: 0
      }
    },
    
    async handleFileUpload(event) {
      const file = event.target.files[0]
      if (!file) return
      
      const formData = new FormData()
      formData.append('picture', file)
      
      try {
        const response = await api.post('/upload.php', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        
        this.formData.picture = response.data.url
      } catch (error) {
        this.showMessage('Error uploading picture: ' + error.message, 'error')
      }
    },
    
    showMessage(text, type) {
      this.message = text
      this.messageType = type
      setTimeout(() => {
        this.message = ''
        this.messageType = ''
      }, 5000)
    },
    
    formatDate(dateString) {
      return new Date(dateString).toLocaleDateString()
    },
    
    async viewItemDetails(item) {
      this.selectedItem = item
      this.activeTab = 'info'
      this.showDetailsModal = true
      
      if (this.activeSection === 'items') {
        await Promise.all([
          this.fetchRentalPrices(item.id),
          this.fetchAttachments(item.id)
        ])
      } else if (this.activeSection === 'clients') {
        await this.fetchContactPersons(item.id)
      }
    },
    
    closeDetailsModal() {
      this.showDetailsModal = false
      this.selectedItem = {}
      this.rentalPrices = []
      this.attachments = []
    },
    
    async fetchRentalPrices(itemId) {
      try {
        const response = await api.get(`/rental_prices.php?item_id=${itemId}`)
        this.rentalPrices = response.data.records || []
      } catch (error) {
        this.showMessage('Error fetching rental prices: ' + error.message, 'error')
      }
    },
    
    async fetchAttachments(itemId) {
      try {
        const response = await api.get(`/attachments.php?item_id=${itemId}`)
        this.attachments = response.data.records || []
      } catch (error) {
        this.showMessage('Error fetching attachments: ' + error.message, 'error')
      }
    },
    
    showAddRentalModal() {
      this.rentalForm = {
        item_id: this.selectedItem.id,
        client_id: null,
        start_date: '',
        end_date: '',
        daily_price: 0
      }
      this.showRentalModal = true
    },
    
    closeRentalModal() {
      this.showRentalModal = false
      this.rentalForm = {
        item_id: null,
        client_id: null,
        start_date: '',
        end_date: '',
        daily_price: 0
      }
    },
    
    async saveRentalPrice() {
      try {
        await api.post('/rental_prices.php', this.rentalForm)
        this.showMessage('Rental price added successfully!', 'success')
        this.closeRentalModal()
        await this.fetchRentalPrices(this.selectedItem.id)
      } catch (error) {
        this.showMessage('Error saving rental price: ' + error.message, 'error')
      }
    },
    
    async deleteRentalPrice(id) {
      if (!confirm('Are you sure you want to delete this rental price?')) {
        return
      }
      
      try {
        await api.delete(`/rental_prices.php?id=${id}`)
        this.showMessage('Rental price deleted successfully!', 'success')
        await this.fetchRentalPrices(this.selectedItem.id)
      } catch (error) {
        this.showMessage('Error deleting rental price: ' + error.message, 'error')
      }
    },
    
    showAddAttachmentModal() {
      this.attachmentForm = {
        item_id: this.selectedItem.id,
        file_type: '',
        file: null
      }
      this.showAttachmentModal = true
    },
    
    closeAttachmentModal() {
      this.showAttachmentModal = false
      this.attachmentForm = {
        item_id: null,
        file_type: '',
        file: null
      }
    },
    
    handleAttachmentUpload(event) {
      this.attachmentForm.file = event.target.files[0]
    },
    
    async saveAttachment() {
      if (!this.attachmentForm.file) {
        this.showMessage('Please select a file to upload', 'error')
        return
      }
      
      try {
        const formData = new FormData()
        formData.append('attachment', this.attachmentForm.file)
        formData.append('item_id', this.attachmentForm.item_id)
        formData.append('file_type', this.attachmentForm.file_type)
        
        await api.post('/attachments.php', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        
        this.showMessage('Attachment uploaded successfully!', 'success')
        this.closeAttachmentModal()
        await this.fetchAttachments(this.selectedItem.id)
      } catch (error) {
        this.showMessage('Error uploading attachment: ' + error.message, 'error')
      }
    },
    
    async deleteAttachment(id) {
      if (!confirm('Are you sure you want to delete this attachment?')) {
        return
      }
      
      try {
        await api.delete(`/attachments.php?id=${id}`)
        this.showMessage('Attachment deleted successfully!', 'success')
        await this.fetchAttachments(this.selectedItem.id)
      } catch (error) {
        this.showMessage('Error deleting attachment: ' + error.message, 'error')
      }
    },
    
    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]
    },
    
    getClientName(clientId) {
      if (!clientId) return 'Unassigned'
      const client = this.clients.find(c => c.id === clientId)
      if (!client) return 'Unknown Client'
      return client.company_name ? `${client.company_name} - ${client.first_name} ${client.last_name}` : `${client.first_name} ${client.last_name}`
    },
    
    // Client management methods
    async fetchClients() {
      this.clientsLoading = true
      try {
        const response = await api.get('/clients.php')
        this.clients = response.data.records || []
      } catch (error) {
        this.showMessage('Error fetching clients: ' + error.message, 'error')
      } finally {
        this.clientsLoading = false
      }
    },
    
    async searchClients() {
      if (this.clientSearch.trim() === '') {
        await this.fetchClients()
        return
      }
      
      this.clientsLoading = true
      try {
        const response = await api.get(`/api/clients.php?search=${this.clientSearch}`)
        this.clients = response.data.records || []
      } catch (error) {
        this.showMessage('Error searching clients: ' + error.message, 'error')
      } finally {
        this.clientsLoading = false
      }
    },
    
    showAddClientModal() {
      this.isEditingClient = false
      this.clientForm = {
        id: null,
        y_tunnus: '',
        company_name: '',
        first_name: '',
        last_name: '',
        email: '',
        phone: '',
        address: '',
        city: '',
        state: '',
        postal_code: '',
        country: '',
        hour_price: '',
        notes: ''
      }
      this.showClientModal = true
    },
    
    editClient(client) {
      this.isEditingClient = true
      this.clientForm = {
        id: client.id,
        y_tunnus: client.y_tunnus || '',
        company_name: client.company_name || '',
        first_name: client.first_name,
        last_name: client.last_name,
        email: client.email,
        phone: client.phone || '',
        address: client.address || '',
        city: client.city || '',
        state: client.state || '',
        postal_code: client.postal_code || '',
        country: client.country || '',
        hour_price: client.hour_price || '',
        notes: client.notes || ''
      }
      this.showClientModal = true
    },
    
    closeClientModal() {
      this.showClientModal = false
      this.clientForm = {
        id: null,
        y_tunnus: '',
        company_name: '',
        first_name: '',
        last_name: '',
        email: '',
        phone: '',
        address: '',
        city: '',
        state: '',
        postal_code: '',
        country: '',
        hour_price: '',
        notes: ''
      }
    },
    
    async saveClient() {
      try {
        if (this.isEditingClient) {
          await api.put('/api/clients.php', this.clientForm)
          this.showMessage('Client updated successfully!', 'success')
        } else {
          await api.post('/api/clients.php', this.clientForm)
          this.showMessage('Client added successfully!', 'success')
        }
        
        this.closeClientModal()
        await this.fetchClients()
      } catch (error) {
        this.showMessage('Error saving client: ' + error.message, 'error')
      }
    },
    
    async deleteClient(id) {
      if (!confirm('Are you sure you want to delete this client?')) {
        return
      }
      
      try {
        await api.delete(`/api/clients.php?id=${id}`)
        this.showMessage('Client deleted successfully!', 'success')
        await this.fetchClients()
      } catch (error) {
        this.showMessage('Error deleting client: ' + error.message, 'error')
      }
    },
    
    // Contact Persons management methods
    handleShowTasks() {
      this.activeSection = 'tasks'
    },
    
    async fetchContactPersons(customerId) {
      this.contactPersonsLoading = true
      try {
        const response = await api.get(`/api/contact_persons.php?client_id=${customerId}`)
        this.contactPersons = response.data.records || []
      } catch (error) {
        this.showMessage('Error fetching contact persons: ' + error.message, 'error')
      } finally {
        this.contactPersonsLoading = false
      }
    },
    
    showAddContactPersonModal() {
      this.isEditingContactPerson = false
      this.contactPersonForm = {
        id: null,
        client_id: this.selectedClient ? this.selectedClient.id : null,
        first_name: '',
        last_name: '',
        email: '',
        phone: '',
        position: '',
        is_primary: false
      }
      this.showContactPersonModal = true
    },
    
    editContactPerson(person) {
      this.isEditingContactPerson = true
      this.contactPersonForm = {
        id: person.id,
        client_id: person.client_id,
        first_name: person.first_name,
        last_name: person.last_name,
        email: person.email || '',
        phone: person.phone || '',
        position: person.position || '',
        is_primary: person.is_primary
      }
      this.showContactPersonModal = true
    },
    
    closeContactPersonModal() {
      this.showContactPersonModal = false
      this.contactPersonForm = {
        id: null,
        client_id: null,
        first_name: '',
        last_name: '',
        email: '',
        phone: '',
        position: '',
        is_primary: false
      }
    },
    
    async saveContactPerson() {
      try {
        if (this.isEditingContactPerson) {
          await api.put('/api/contact_persons.php', this.contactPersonForm)
          this.showMessage('Contact person updated successfully!', 'success')
        } else {
          await api.post('/api/contact_persons.php', this.contactPersonForm)
          this.showMessage('Contact person added successfully!', 'success')
        }
        
        this.closeContactPersonModal()
        await this.fetchContactPersons(this.contactPersonForm.client_id)
      } catch (error) {
        this.showMessage('Error saving contact person: ' + error.message, 'error')
      }
    },
    
    async deleteContactPerson(id) {
      if (!confirm('Are you sure you want to delete this contact person?')) {
        return
      }
      
      try {
        await api.delete(`/api/contact_persons.php?id=${id}`)
        this.showMessage('Contact person deleted successfully!', 'success')
        await this.fetchContactPersons(this.selectedClient ? this.selectedClient.id : null)
      } catch (error) {
        this.showMessage('Error deleting contact person: ' + error.message, 'error')
      }
    },
    
    // Invoice management methods
    async fetchInvoices() {
      this.invoicesLoading = true
      try {
        const response = await api.get('/invoices.php')
        this.invoices = response.data.records || []
      } catch (error) {
        this.showMessage('Error fetching invoices: ' + error.message, 'error')
      } finally {
        this.invoicesLoading = false
      }
    },
    
    async searchInvoices() {
      if (this.invoiceSearch.trim() === '') {
        await this.fetchInvoices()
        return
      }
      
      this.invoicesLoading = true
      try {
        const response = await api.get(`/invoices.php?search=${this.invoiceSearch}`)
        this.invoices = response.data.records || []
      } catch (error) {
        this.showMessage('Error searching invoices: ' + error.message, 'error')
      } finally {
        this.invoicesLoading = false
      }
    },
    
    showAddInvoiceModal() {
      this.isEditingInvoice = false
      this.invoiceForm = {
        id: null,
        client_id: null,
        invoice_number: '',
        issue_date: '',
        due_date: '',
        status: 'draft',
        subtotal: 0,
        tax_amount: 0,
        total_amount: 0,
        notes: ''
      }
      this.showInvoiceModal = true
    },
    
    editInvoice(invoice) {
      this.isEditingInvoice = true
      this.invoiceForm = {
        id: invoice.id,
        client_id: invoice.client_id,
        invoice_number: invoice.invoice_number,
        issue_date: invoice.issue_date,
        due_date: invoice.due_date,
        status: invoice.status,
        subtotal: invoice.subtotal,
        tax_amount: invoice.tax_amount,
        total_amount: invoice.total_amount,
        notes: invoice.notes
      }
      this.showInvoiceModal = true
    },
    
    closeInvoiceModal() {
      this.showInvoiceModal = false
      this.invoiceForm = {
        id: null,
        client_id: null,
        invoice_number: '',
        issue_date: '',
        due_date: '',
        status: 'draft',
        subtotal: 0,
        tax_amount: 0,
        total_amount: 0,
        notes: ''
      }
    },
    
    async saveInvoice() {
      try {
        if (this.isEditingInvoice) {
          await api.put('/invoices.php', this.invoiceForm)
          this.showMessage('Invoice updated successfully!', 'success')
        } else {
          await api.post('/invoices.php', this.invoiceForm)
          this.showMessage('Invoice created successfully!', 'success')
        }
        
        this.closeInvoiceModal()
        await this.fetchInvoices()
      } catch (error) {
        this.showMessage('Error saving invoice: ' + error.message, 'error')
      }
    },
    
    async deleteInvoice(id) {
      if (!confirm('Are you sure you want to delete this invoice?')) {
        return
      }
      
      try {
        await api.delete(`/invoices.php?id=${id}`)
        this.showMessage('Invoice deleted successfully!', 'success')
        await this.fetchInvoices()
      } catch (error) {
        this.showMessage('Error deleting invoice: ' + error.message, 'error')
      }
    },
    
    viewInvoice(invoice) {
      this.selectedInvoice = invoice
      this.showInvoiceItemsModal = true
    },
    
    closeInvoiceItemsModal() {
      this.showInvoiceItemsModal = false
      this.selectedInvoice = {}
      this.invoiceItems = []
    },
    
    async saveInvoiceItem() {
      try {
        if (this.invoiceItemsForm.id) {
          await api.put('/api/invoice_items.php', this.invoiceItemsForm)
          this.showMessage('Invoice item updated successfully!', 'success')
        } else {
          await api.post('/api/invoice_items.php', this.invoiceItemsForm)
          this.showMessage('Invoice item added successfully!', 'success')
        }
        
        this.closeInvoiceItemsModal()
        await this.viewInvoice(this.selectedInvoice)
      } catch (error) {
        this.showMessage('Error saving invoice item: ' + error.message, 'error')
      }
    },
    
    async deleteInvoiceItem(id) {
      if (!confirm('Are you sure you want to delete this invoice item?')) {
        return
      }
      
      try {
        await api.delete(`/api/invoice_items.php?id=${id}`)
        this.showMessage('Invoice item deleted successfully!', 'success')
        await this.viewInvoice(this.selectedInvoice)
      } catch (error) {
        this.showMessage('Error deleting invoice item: ' + error.message, 'error')
      }
    },
    
    // Authentication methods
    async login() {
      this.loginError = ''
      
      try {
        const response = await api.post('/auth.php', {
          action: 'login',
          username: this.loginForm.username,
          password: this.loginForm.password
        })
        
        if (response.data.user) {
          this.isLoggedIn = true
          this.currentUser = response.data.user
          this.loginForm = { username: '', password: '' }
          this.showMessage('Login successful!', 'success')
          this.fetchInitialData()
          this.$refs.loginUsername.value = ''
          this.$refs.loginPassword.value = ''
        } else {
          this.loginError = response.data.message || 'Login failed'
          this.showMessage('Login failed', 'error')
        }
      } catch (error) {
        this.loginError = 'Network error. Please try again.'
        this.showMessage('Error during login: ' + error.message, 'error')
      }
    },
    
    async logout() {
      try {
        // Call backend logout endpoint to clear PHP session
        await api.post('/auth.php', { action: 'logout' })
        
        // Clear frontend data
        this.isLoggedIn = false
        this.currentUser = null
        
        // Clear any stored authentication data
        localStorage.removeItem('authToken')
        sessionStorage.removeItem('authToken')
        sessionStorage.removeItem('currentUser')
        
        // Clear application data
        this.items = []
        this.clients = []
        this.projects = []
        this.users = []
        this.invoices = []
        this.accounts = []
        this.journalEntries = []
        this.transactions = []
        
        this.showMessage('Logged out successfully!', 'success')
      } catch (error) {
        console.error('Logout error:', error)
        // Still clear frontend data even if backend call fails
        this.isLoggedIn = false
        this.currentUser = null
        localStorage.removeItem('authToken')
        sessionStorage.removeItem('authToken')
        sessionStorage.removeItem('currentUser')
        this.showMessage('Logged out successfully!', 'success')
      }
    },
    
    async checkAuthStatus() {
      try {
        const response = await api.get('/auth.php?action=status')
        if (response.status === 200 && response.data.user) {
          this.isLoggedIn = true
          this.currentUser = response.data.user
          // Fetch data only after successful authentication
          this.fetchInitialData()
        } else {
          // Session invalid or expired
          this.isLoggedIn = false
          this.currentUser = null
        }
      } catch (error) {
        // Network error or server error - assume not logged in
        this.isLoggedIn = false
        this.currentUser = null
        // Don't show warning on initial load when not logged in
      }
    },
    
    fetchInitialData() {
      // Fetch all initial data after successful login
      this.fetchItems()
      this.fetchClients()
      this.fetchUsers()
      this.fetchProjects()
      this.fetchAccounts()
      this.fetchJournalEntries()
      this.fetchInvoices()
    },
    
    handleSessionExpired(event) {
      // Clear authentication state
      this.isLoggedIn = false
      this.currentUser = null
      
      // Show message to user
      const message = event.detail?.message || 'Session expired. Please login again.'
      this.showMessage(message, 'warning')
      
      // Clear any stored data
      localStorage.removeItem('authToken')
      sessionStorage.removeItem('currentUser')
    },
    
    // Project management methods
    async fetchProjects() {
      this.projectsLoading = true
      try {
        const response = await api.get('/projects.php')
        this.projects = response.data.records || []
      } catch (error) {
        this.showMessage('Error fetching projects: ' + error.message, 'error')
      } finally {
        this.projectsLoading = false
      }
    },
    
    async searchProjects(searchTerm) {
      this.projectSearch = searchTerm
      this.projectsLoading = true
      try {
        const response = await api.get(`/api/projects.php?search=${this.projectSearch}`)
        this.projects = response.data.records || []
      } catch (error) {
        this.showMessage('Error searching projects: ' + error.message, 'error')
      } finally {
        this.projectsLoading = false
      }
    },
    
    showAddProjectModal() {
      this.isEditingProject = false
      this.projectForm = {
        id: null,
        customer_id: null,
        project_name: '',
        description: '',
        status: 'planning',
        start_date: '',
        end_date: '',
        budget: 0
      }
      this.showProjectModal = true
    },
    
    viewProject(project) {
      this.selectedProject = project
      // Show project details modal or navigate to project details
    },
    
    editProject(project) {
      this.isEditingProject = true
      this.projectForm = { ...project }
      this.showProjectModal = true
    },
    
    async deleteProject(id) {
      if (!confirm('Are you sure you want to delete this project?')) {
        return
      }
      
      try {
        await api.delete(`/api/projects.php?id=${id}`)
        this.showMessage('Project deleted successfully!', 'success')
        this.fetchProjects()
      } catch (error) {
        this.showMessage('Error deleting project: ' + error.message, 'error')
      }
    },
    
    // User management methods
    async fetchUsers() {
      this.usersLoading = true
      try {
        const response = await api.get('/api/users.php')
        this.users = response.data.records || []
      } catch (error) {
        this.showMessage('Error fetching users: ' + error.message, 'error')
      } finally {
        this.usersLoading = false
      }
    },
    
    async searchUsers(searchTerm) {
      this.userSearch = searchTerm
      this.usersLoading = true
      try {
        const response = await api.get(`/api/users.php?search=${this.userSearch}`)
        this.users = response.data.records || []
      } catch (error) {
        this.showMessage('Error searching users: ' + error.message, 'error')
      } finally {
        this.usersLoading = false
      }
    },
    
    showAddUserModal() {
      this.isEditingUser = false
      this.userForm = {
        id: null,
        username: '',
        email: '',
        first_name: '',
        last_name: '',
        role: 'user',
        is_active: true,
        password: ''
      }
      this.showUserModal = true
    },
    
    viewUser(user) {
      this.selectedUser = user
      this.isEditingUser = false
      this.userForm = { 
        ...user,
        password: '' // Don't populate password field for security
      }
      this.showUserModal = true
    },
    
    editUser(user) {
      this.isEditingUser = true
      this.userForm = { 
        ...user,
        password: '' // Don't populate password field for security
      }
      this.showUserModal = true
    },
    
    async deleteUser(id) {
      if (!confirm('Are you sure you want to delete this user?')) {
        return
      }
      
      try {
        await api.delete(`/api/users.php?id=${id}`)
        this.showMessage('User deleted successfully!', 'success')
        this.fetchUsers()
      } catch (error) {
        this.showMessage('Error deleting user: ' + error.message, 'error')
      }
    },
    
    closeUserModal() {
      this.showUserModal = false
      this.selectedUser = {}
      this.userForm = {
        id: null,
        username: '',
        first_name: '',
        last_name: '',
        email: '',
        role: 'user',
        is_active: true,
        password: ''
      }
      this.isEditingUser = false
    },
    
    async saveUser() {
      try {
        const userData = {
          username: this.userForm.username,
          first_name: this.userForm.first_name,
          last_name: this.userForm.last_name,
          email: this.userForm.email,
          role: this.userForm.role,
          is_active: this.userForm.is_active
        }
        
        // Only include password if it's provided
        if (this.userForm.password) {
          userData.password = this.userForm.password
        }
        
        let response
        if (this.userForm.id) {
          // Update existing user
          response = await api.put(`/api/users.php?id=${this.userForm.id}`, userData)
          this.showMessage('User updated successfully!', 'success')
        } else {
          // Create new user
          response = await api.post('/api/users.php', userData)
          this.showMessage('User created successfully!', 'success')
        }
        
        this.closeUserModal()
        this.fetchUsers()
      } catch (error) {
        this.showMessage('Error saving user: ' + error.message, 'error')
      }
    },
    
    closeProjectModal() {
      this.showProjectModal = false
      this.selectedProject = {}
      this.projectForm = {
        id: null,
        customer_id: null,
        project_name: '',
        description: '',
        status: 'planning',
        start_date: '',
        end_date: '',
        budget: 0
      }
      this.isEditingProject = false
    },
    
    async saveProject() {
      try {
        const projectData = {
          customer_id: this.projectForm.customer_id,
          project_name: this.projectForm.project_name,
          description: this.projectForm.description,
          status: this.projectForm.status,
          start_date: this.projectForm.start_date,
          end_date: this.projectForm.end_date,
          budget: this.projectForm.budget
        }
        
        let response
        if (this.projectForm.id) {
          // Update existing project
          response = await api.put(`/api/projects.php?id=${this.projectForm.id}`, projectData)
          this.showMessage('Project updated successfully!', 'success')
        } else {
          // Create new project
          response = await api.post('/api/projects.php', projectData)
          this.showMessage('Project created successfully!', 'success')
        }
        
        this.closeProjectModal()
        this.fetchProjects()
      } catch (error) {
        this.showMessage('Error saving project: ' + error.message, 'error')
      }
    },
    
    getCustomerName(customerId) {
      if (!customerId) return null
      const customer = this.clients.find(c => c.id === customerId)
      if (customer) {
        return customer.company_name || `${customer.first_name} ${customer.last_name}`
      }
      return null
    },
    
    // Contact persons management methods
    async manageContacts(customer) {
      this.selectedCustomer = customer
      this.contactForm.client_id = customer.id
      await this.fetchCustomerContacts(customer.id)
      this.showContactModal = true
    },
    
    async fetchCustomerContacts(customerId) {
      try {
        const response = await api.get(`/api/contact_persons.php?client_id=${customerId}`)
        this.customerContacts = response.data.records || []
      } catch (error) {
        this.showMessage('Error fetching contacts: ' + error.message, 'error')
      }
    },
    
    async addContact() {
      try {
        const contactData = {
          client_id: this.contactForm.client_id,
          first_name: this.contactForm.first_name,
          last_name: this.contactForm.last_name,
          email: this.contactForm.email,
          phone: this.contactForm.phone,
          position: this.contactForm.position,
          department: this.contactForm.department,
          is_primary: this.contactForm.is_primary,
          notes: this.contactForm.notes
        }
        
        await api.post('/api/contact_persons.php', contactData)
        this.showMessage('Contact added successfully!', 'success')
        this.resetContactForm()
        await this.fetchCustomerContacts(this.selectedCustomer.id)
        await this.fetchClients() // Refresh clients to show updated contact info
      } catch (error) {
        this.showMessage('Error adding contact: ' + error.message, 'error')
      }
    },
    
    editContact(contact) {
      this.contactForm = { ...contact }
    },
    
    async updateContact() {
      try {
        const contactData = {
          id: this.contactForm.id,
          client_id: this.contactForm.client_id,
          first_name: this.contactForm.first_name,
          last_name: this.contactForm.last_name,
          email: this.contactForm.email,
          phone: this.contactForm.phone,
          position: this.contactForm.position,
          department: this.contactForm.department,
          is_primary: this.contactForm.is_primary,
          notes: this.contactForm.notes
        }
        
        await api.put(`/api/contact_persons.php?id=${this.contactForm.id}`, contactData)
        this.showMessage('Contact updated successfully!', 'success')
        this.resetContactForm()
        await this.fetchCustomerContacts(this.selectedCustomer.id)
        await this.fetchClients()
      } catch (error) {
        this.showMessage('Error updating contact: ' + error.message, 'error')
      }
    },
    
    async deleteContact(contactId) {
      if (!confirm('Are you sure you want to delete this contact?')) {
        return
      }
      
      try {
        await api.delete(`/api/contact_persons.php?id=${contactId}`)
        this.showMessage('Contact deleted successfully!', 'success')
        await this.fetchCustomerContacts(this.selectedCustomer.id)
        await this.fetchClients()
      } catch (error) {
        this.showMessage('Error deleting contact: ' + error.message, 'error')
      }
    },
    
    resetContactForm() {
      this.contactForm = {
        id: null,
        client_id: this.selectedCustomer.id,
        first_name: '',
        last_name: '',
        email: '',
        phone: '',
        position: '',
        department: '',
        is_primary: false,
        notes: ''
      }
    },
    
    closeContactModal() {
      this.showContactModal = false
      this.selectedCustomer = {}
      this.customerContacts = []
      this.resetContactForm()
    },
    
    // Chart of Accounts methods
    async fetchAccounts() {
      this.accountsLoading = true
      try {
        const response = await api.get('/chart_of_accounts.php')
        this.accounts = response.data.records || []
      } catch (error) {
        this.showMessage('Error fetching accounts: ' + error.message, 'error')
      } finally {
        this.accountsLoading = false
      }
    },
    
    async searchAccounts(searchTerm) {
      this.accountSearch = searchTerm
      this.accountsLoading = true
      try {
        const response = await api.get(`/chart_of_accounts.php?search=${this.accountSearch}`)
        this.accounts = response.data.records || []
      } catch (error) {
        this.showMessage('Error searching accounts: ' + error.message, 'error')
      } finally {
        this.accountsLoading = false
      }
    },
    
    showAddAccountModal() {
      this.isEditingAccount = false
      this.accountForm = {
        id: null,
        account_number: '',
        account_name: '',
        account_type: 'asset',
        parent_id: null,
        description: '',
        opening_balance: 0,
        is_active: true
      }
      this.showAccountModal = true
    },
    
    viewAccount(account) {
      this.selectedAccount = account
      // Show account details modal or navigate to account details
    },
    
    editAccount(account) {
      this.isEditingAccount = true
      this.accountForm = { ...account }
      this.showAccountModal = true
    },
    
    async deleteAccount(id) {
      if (!confirm('Are you sure you want to delete this account?')) {
        return
      }
      
      try {
        await api.delete(`/chart_of_accounts.php?id=${id}`)
        this.showMessage('Account deleted successfully!', 'success')
        this.fetchAccounts()
      } catch (error) {
        this.showMessage('Error deleting account: ' + error.message, 'error')
      }
    },
    
    // Journal Entries methods
    async fetchJournalEntries() {
      this.journalEntriesLoading = true
      try {
        const response = await api.get('/journal_entries.php')
        this.journalEntries = response.data.records || []
      } catch (error) {
        this.showMessage('Error fetching journal entries: ' + error.message, 'error')
      } finally {
        this.journalEntriesLoading = false
      }
    },
    
    // Transactions methods
    async fetchTransactions() {
      this.transactionsLoading = true
      try {
        const response = await api.get('/api/account_transactions.php')
        this.transactions = response.data.records || []
      } catch (error) {
        this.showMessage('Error fetching transactions: ' + error.message, 'error')
      } finally {
        this.transactionsLoading = false
      }
    },
    
    // Journal Entry methods
    showAddJournalEntryModal() {
      // Placeholder for journal entry modal
      this.showMessage('Journal entry modal not yet implemented', 'info')
    },
    
    viewJournalEntry(entry) {
      this.selectedJournalEntry = entry
      // Placeholder for viewing journal entry details
      this.showMessage('Journal entry details not yet implemented', 'info')
    },
    
    editJournalEntry(entry) {
      this.selectedJournalEntry = entry
      // Placeholder for editing journal entry
      this.showMessage('Journal entry editing not yet implemented', 'info')
    },
    
    async deleteJournalEntry(id) {
      if (!confirm('Are you sure you want to delete this journal entry?')) {
        return
      }
      
      try {
        await api.delete(`/journal_entries.php?id=${id}`)
        this.showMessage('Journal entry deleted successfully!', 'success')
        this.fetchJournalEntries()
      } catch (error) {
        this.showMessage('Error deleting journal entry: ' + error.message, 'error')
      }
    },
    
    searchAccounting(searchTerm) {
      this.accountingSearch = searchTerm
      // Placeholder for accounting search
      this.showMessage('Accounting search not yet implemented', 'info')
    }
  }
}
</script>

<style scoped>
.alert {
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #333;
}

.alert.error {
  background-color: #fdf2f2;
  color: #e74c3c;
  border: 1px solid #f5c6cb;
}

.alert.success {
  background-color: #f2f9f4;
  color: #27ae60;
  border: 1px solid #c3e6cb;
}

.nav-tabs {
  display: flex;
  border-bottom: 2px solid #e9ecef;
  margin-bottom: 20px;
}

.nav-tab {
  background: none;
  border: none;
  padding: 12px 24px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
  color: #6c757d !important;
}

.nav-tab:hover {
  background-color: #f8f9fa;
  color: #495057 !important;
}

.nav-tab.active {
  border-bottom-color: #3498db;
  color: #3498db !important;
  font-weight: 600;
}

.tabs {
  display: flex;
  border-bottom: 2px solid #e9ecef;
  margin-bottom: 20px;
}

.tab-btn {
  background: none;
  border: none;
  padding: 12px 20px;
  cursor: pointer;
  font-size: 14px;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
}

.tab-btn:hover {
  background-color: #f8f9fa;
}

.tab-btn.active {
  border-bottom-color: #3498db;
  color: #3498db;
  font-weight: 600;
}

.tab-content {
  min-height: 200px;
}

.item-info {
  display: grid;
  gap: 15px;
}

.info-row {
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.attachments-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.attachment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.attachment-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.attachment-type {
  background-color: #6c757d;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  text-transform: uppercase;
  font-weight: 500;
  width: fit-content;
}

.attachment-size {
  color: #6c757d;
  font-size: 12px;
}

.attachment-actions {
  display: flex;
  gap: 10px;
}

.attachment-actions .btn {
  text-decoration: none;
  display: inline-block;
}

.contacts-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.contact-person-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.contact-person-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.contact-position {
  background-color: #6c757d;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  text-transform: uppercase;
  font-weight: 500;
  width: fit-content;
}

.contact-primary {
  background-color: #28a745;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  width: fit-content;
  margin-left: 5px;
}

.contact-person-details {
  display: flex;
  flex-direction: column;
  gap: 5px;
  font-size: 14px;
}

.contact-person-actions {
  display: flex;
  gap: 10px;
}

/* Login Styles */
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.login-card {
  background: white;
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
}

.app-header {
  background: white;
  padding: 1rem 2rem;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.user-role {
  background: #6c757d;
  color: white;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.875rem;
  font-weight: 500;
  text-transform: uppercase;
}

.main-content {
  padding-top: 2rem;
}

/* Table Styles */
.table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table th,
.table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #dee2e6;
  color: #333 !important;
}

.table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #495057 !important;
  border-bottom: 2px solid #dee2e6;
}

.table tbody tr:hover {
  background-color: #f8f9fa;
}

.table tbody tr:last-child td {
  border-bottom: none;
}

/* Modal Styles */
.modal {
  position: fixed;
  z-index: 1000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  position: relative;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.close {
  position: absolute;
  right: 15px;
  top: 10px;
  font-size: 28px;
  font-weight: bold;
  cursor: pointer;
  color: #aaa;
}

.close:hover {
  color: #000;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.form-group textarea {
  resize: vertical;
  min-height: 80px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s ease;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover {
  background-color: #0056b3;
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background-color: #545b62;
}

/* User Modal Styles */
.user-details {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin: 20px 0;
}

.detail-row {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.detail-row strong {
  min-width: 120px;
  color: #333;
  font-weight: 600;
}

.detail-row:last-child {
  border-bottom: none;
}

/* Project Details Styles */
.project-details {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin: 20px 0;
}

/* Contact Persons Styles */
.contact-persons {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.contact-list {
  display: flex;
  flex-direction: column;
  gap: 3px;
}

.contact-item {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.primary-badge {
  background-color: #007bff;
  color: white;
  padding: 1px 4px;
  border-radius: 8px;
  font-size: 10px;
  font-weight: 500;
}

.more-contacts {
  font-size: 11px;
  color: #666;
  font-style: italic;
}

.no-contacts {
  font-size: 12px;
  color: #999;
  font-style: italic;
}

.btn-sm {
  padding: 2px 6px;
  font-size: 11px;
}

/* Contact Modal Styles */
.contacts-management {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
  margin: 20px 0;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.add-contact-section, .existing-contacts-section {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 20px;
}

.add-contact-section h3, .existing-contacts-section h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
}

.no-contacts {
  text-align: center;
  padding: 20px;
  color: #666;
  font-style: italic;
}

.contacts-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.contact-item {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
  background: #fafafa;
}

.contact-info h4 {
  margin: 0 0 10px 0;
  color: #333;
}

.contact-details .detail {
  margin-bottom: 5px;
  font-size: 14px;
}

.contact-badges {
  margin-top: 10px;
}

.badge {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  text-transform: uppercase;
}

.badge-primary {
  background-color: #007bff;
  color: white;
}

.contact-actions {
  margin-top: 15px;
  display: flex;
  gap: 5px;
}
</style>
