<template>
  <div class="card">
    <div class="section-header">
      <h2>ALV-laskenta</h2>
      <div class="header-actions">
        <select v-model="selectedPeriod" @change="loadALVLaskenta" class="period-selector">
          <option value="current">Nykyinen kausi</option>
          <option value="month">Kuukausi</option>
          <option value="quarter">Neljännes</option>
          <option value="year">Vuosi</option>
        </select>
        <input 
          type="month" 
          v-model="selectedMonth" 
          v-if="selectedPeriod === 'month'"
          @change="loadALVLaskenta"
          class="month-input"
        >
        <input 
          type="number" 
          v-model="selectedYear" 
          v-if="selectedPeriod === 'year'"
          @change="loadALVLaskenta"
          placeholder="Vuosi"
          min="2020"
          max="2030"
          class="year-input"
        >
        <select 
          v-model="selectedQuarter" 
          v-if="selectedPeriod === 'quarter'"
          @change="loadALVLaskenta"
          class="quarter-input"
        >
          <option value="1">Q1 (Tammi-Maaliskuu)</option>
          <option value="2">Q2 (Huhti-Kesäkuu)</option>
          <option value="3">Q3 (Heinä-Syyskuu)</option>
          <option value="4">Q4 (Loka-Joulukuu)</option>
        </select>
        <button class="btn btn-info" @click="toggleMonthlySummary">
          {{ showMonthlySummary ? 'Normaali raportti' : 'Kuukausikooste' }}
        </button>
        <button class="btn btn-primary" @click="exportToPDF">Export PDF</button>
        <button class="btn btn-secondary" @click="printReport">Tulosta</button>
      </div>
    </div>

    <div v-if="loading" class="loading">
      Ladataan ALV-laskentaa...
    </div>

    <div v-else class="alv-container">
      <!-- Header Information -->
      <div class="report-header">
        <div class="company-info">
          <h3>{{ companyName || 'Yritys Oy' }}</h3>
          <p>Y-tunnus: {{ companyYtunnus || '1234567-8' }}</p>
        </div>
        <div class="period-info">
          <h4>ALV-laskenta</h4>
          <p>{{ periodDescription }}</p>
        </div>
      </div>

      <!-- Monthly Summary Report -->
      <div v-if="showMonthlySummary && monthlySummaryData" class="monthly-summary">
        <h3>Kuukausikooste</h3>
        <table class="monthly-summary-table">
          <thead>
            <tr>
              <th>Kuukausi</th>
              <th>ALV maksettava</th>
              <th>ALV vähennettävä</th>
              <th>ALV netto</th>
              <th>Liikevaihto</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="month in monthlySummaryData" :key="month.month">
              <td>{{ month.month_name }}</td>
              <td class="summary-card payable">{{ formatCurrency(month.payable) }}</td>
              <td class="summary-card deductible">{{ formatCurrency(month.deductible) }}</td>
              <td class="summary-card net">{{ formatCurrency(month.net) }}</td>
              <td class="summary-card turnover">{{ formatCurrency(month.turnover) }}</td>
            </tr>
          </tbody>
          <tfoot>
            <tr class="total-row">
              <td><strong>Yhteensä</strong></td>
              <td class="summary-card payable"><strong>{{ formatCurrency(monthlySummaryData.reduce((sum, m) => sum + m.payable, 0)) }}</strong></td>
              <td class="summary-card deductible"><strong>{{ formatCurrency(monthlySummaryData.reduce((sum, m) => sum + m.deductible, 0)) }}</strong></td>
              <td class="summary-card net"><strong>{{ formatCurrency(monthlySummaryData.reduce((sum, m) => sum + m.net, 0)) }}</strong></td>
              <td class="summary-card turnover"><strong>{{ formatCurrency(monthlySummaryData.reduce((sum, m) => sum + m.turnover, 0)) }}</strong></td>
            </tr>
          </tfoot>
        </table>
      </div>

      <!-- VAT Calculation Table -->
      <div v-else>
      <table class="alv-table">
        <thead>
          <tr>
            <th>ALV %</th>
            <th>Verotettavat myynnit</th>
            <th>Verolliset ostot</th>
            <th>Maksettava ALV</th>
            <th>Vähennettävä ALV</th>
            <th>Netto ALV</th>
          </tr>
        </thead>
        <tbody>
          <!-- 0% VAT -->
          <tr>
            <td class="vat-rate">0%</td>
            <td class="amount">{{ formatCurrency(vatData['0'].taxable_sales) }}</td>
            <td class="amount">{{ formatCurrency(vatData['0'].taxable_purchases) }}</td>
            <td class="amount">{{ formatCurrency(vatData['0'].payable_vat) }}</td>
            <td class="amount">{{ formatCurrency(vatData['0'].deductible_vat) }}</td>
            <td class="amount net-vat">{{ formatCurrency(vatData['0'].net_vat) }}</td>
          </tr>

          <!-- 10% VAT -->
          <tr>
            <td class="vat-rate">10%</td>
            <td class="amount">{{ formatCurrency(vatData['10'].taxable_sales) }}</td>
            <td class="amount">{{ formatCurrency(vatData['10'].taxable_purchases) }}</td>
            <td class="amount">{{ formatCurrency(vatData['10'].payable_vat) }}</td>
            <td class="amount">{{ formatCurrency(vatData['10'].deductible_vat) }}</td>
            <td class="amount net-vat">{{ formatCurrency(vatData['10'].net_vat) }}</td>
          </tr>

          <!-- 14% VAT -->
          <tr>
            <td class="vat-rate">14%</td>
            <td class="amount">{{ formatCurrency(vatData['14'].taxable_sales) }}</td>
            <td class="amount">{{ formatCurrency(vatData['14'].taxable_purchases) }}</td>
            <td class="amount">{{ formatCurrency(vatData['14'].payable_vat) }}</td>
            <td class="amount">{{ formatCurrency(vatData['14'].deductible_vat) }}</td>
            <td class="amount net-vat">{{ formatCurrency(vatData['14'].net_vat) }}</td>
          </tr>

          <!-- 24% VAT (Standard rate) -->
          <tr>
            <td class="vat-rate">24%</td>
            <td class="amount">{{ formatCurrency(vatData['24'].taxable_sales) }}</td>
            <td class="amount">{{ formatCurrency(vatData['24'].taxable_purchases) }}</td>
            <td class="amount">{{ formatCurrency(vatData['24'].payable_vat) }}</td>
            <td class="amount">{{ formatCurrency(vatData['24'].deductible_vat) }}</td>
            <td class="amount net-vat">{{ formatCurrency(vatData['24'].net_vat) }}</td>
          </tr>

          <!-- 25.5% VAT -->
          <tr>
            <td class="vat-rate">25,5%</td>
            <td class="amount">{{ formatCurrency(vatData['25.5'].taxable_sales) }}</td>
            <td class="amount">{{ formatCurrency(vatData['25.5'].taxable_purchases) }}</td>
            <td class="amount">{{ formatCurrency(vatData['25.5'].payable_vat) }}</td>
            <td class="amount">{{ formatCurrency(vatData['25.5'].deductible_vat) }}</td>
            <td class="amount net-vat">{{ formatCurrency(vatData['25.5'].net_vat) }}</td>
          </tr>

          <!-- Totals -->
          <tr class="total-row">
            <td>Yhteensä</td>
            <td class="amount total">{{ formatCurrency(totals.taxable_sales) }}</td>
            <td class="amount total">{{ formatCurrency(totals.taxable_purchases) }}</td>
            <td class="amount total">{{ formatCurrency(totals.payable_vat) }}</td>
            <td class="amount total">{{ formatCurrency(totals.deductible_vat) }}</td>
            <td class="amount total net-total">{{ formatCurrency(totals.net_vat) }}</td>
          </tr>
        </tbody>
      </table>

      <!-- VAT Summary Cards -->
      <div class="summary-cards">
        <div class="summary-card payable">
          <h3>Maksettava ALV</h3>
          <p class="amount">{{ formatCurrency(totals.payable_vat) }}</p>
          <p class="description">Kerättävä arvonlisävero</p>
        </div>
        <div class="summary-card deductible">
          <h3>Vähennettävä ALV</h3>
          <p class="amount">{{ formatCurrency(totals.deductible_vat) }}</p>
          <p class="description">Vähennettävä arvonlisävero</p>
        </div>
        <div class="summary-card net">
          <h3>Netto ALV</h3>
          <p class="amount">{{ formatCurrency(totals.net_vat) }}</p>
          <p class="description">Maksettava tai palautettava ALV</p>
        </div>
        <div class="summary-card turnover">
          <h3>Verollinen liikevaihto</h3>
          <p class="amount">{{ formatCurrency(totals.taxable_sales) }}</p>
          <p class="description">ALV:n alainen myynti</p>
        </div>
      </div>

      <!-- Detailed Breakdown -->
      <div class="detailed-breakdown">
        <h3>ALV-laskelman erittely</h3>
        
        <div class="breakdown-section">
          <h4>Myyntien ALV</h4>
          <table class="breakdown-table">
            <thead>
              <tr>
                <th>ALV %</th>
                <th>Veroton summa</th>
                <th>ALV määrä</th>
                <th>Verollinen summa</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(data, rate) in vatData" :key="rate">
                <td>{{ formatVatRate(rate) }}%</td>
                <td class="amount">{{ formatCurrency(data.taxable_sales) }}</td>
                <td class="amount">{{ formatCurrency(data.payable_vat) }}</td>
                <td class="amount">{{ formatCurrency(data.taxable_sales + data.payable_vat) }}</td>
              </tr>
            </tbody>
          </table>
        </div>

        <div class="breakdown-section">
          <h4>Ostojen ALV</h4>
          <table class="breakdown-table">
            <thead>
              <tr>
                <th>ALV %</th>
                <th>Veroton summa</th>
                <th>ALV määrä</th>
                <th>Verollinen summa</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(data, rate) in vatData" :key="rate">
                <td>{{ formatVatRate(rate) }}%</td>
                <td class="amount">{{ formatCurrency(data.taxable_purchases) }}</td>
                <td class="amount">{{ formatCurrency(data.deductible_vat) }}</td>
                <td class="amount">{{ formatCurrency(data.taxable_purchases + data.deductible_vat) }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      </div>
    </div>
  </div>
</template>

<script>
import api from '../../api/axios'
import { formatCurrency, formatDate } from '../../utils/locale'

export default {
  name: 'ALVLaskentaSection',
  props: {
    activeSection: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      selectedPeriod: 'year',
      selectedMonth: new Date().toISOString().slice(0, 7),
      selectedYear: 2024,
      selectedQuarter: Math.ceil((new Date().getMonth() + 1) / 3),
      companyName: '',
      companyYtunnus: '',
      alvData: null,
      monthlySummaryData: null,
      showMonthlySummary: false,
      
      // VAT data structure
      vatData: {
        '0': {
          taxable_sales: 0,
          taxable_purchases: 0,
          payable_vat: 0,
          deductible_vat: 0,
          net_vat: 0
        },
        '10': {
          taxable_sales: 0,
          taxable_purchases: 0,
          payable_vat: 0,
          deductible_vat: 0,
          net_vat: 0
        },
        '14': {
          taxable_sales: 0,
          taxable_purchases: 0,
          payable_vat: 0,
          deductible_vat: 0,
          net_vat: 0
        },
        '24': {
          taxable_sales: 0,
          taxable_purchases: 0,
          payable_vat: 0,
          deductible_vat: 0,
          net_vat: 0
        },
        '25.5': {
          taxable_sales: 0,
          taxable_purchases: 0,
          payable_vat: 0,
          deductible_vat: 0,
          net_vat: 0
        }
      }
    }
  },
  
  computed: {
    periodDescription() {
      switch (this.selectedPeriod) {
        case 'current':
          return 'Nykyinen kausi'
        case 'month':
          return `Kuukausi: ${this.formatMonth(this.selectedMonth)}`
        case 'quarter':
          const quarterNames = {
            1: 'Q1 (Tammi-Maaliskuu)',
            2: 'Q2 (Huhti-Kesäkuu)', 
            3: 'Q3 (Heinä-Syyskuu)',
            4: 'Q4 (Loka-Joulukuu)'
          }
          return `Neljännes: ${quarterNames[this.selectedQuarter]} ${this.selectedYear}`
        case 'year':
          return `Vuosi: ${this.selectedYear}`
        default:
          return 'Nykyinen kausi'
      }
    },
    
    totals() {
      const totals = {
        taxable_sales: 0,
        taxable_purchases: 0,
        payable_vat: 0,
        deductible_vat: 0,
        net_vat: 0
      }
      
      Object.values(this.vatData).forEach(data => {
        totals.taxable_sales += data.taxable_sales || 0
        totals.taxable_purchases += data.taxable_purchases || 0
        totals.payable_vat += data.payable_vat || 0
        totals.deductible_vat += data.deductible_vat || 0
        totals.net_vat += data.net_vat || 0
      })
      
      return totals
    }
  },
  
  methods: {
    formatCurrency,
    formatDate,
    
    async loadALVLaskenta() {
      this.loading = true
      try {
        // Load company details
        await this.loadCompanyDetails()
        
        const response = await api.get('/alv_laskenta.php', {
          params: {
            period: this.selectedPeriod,
            month: this.selectedMonth,
            quarter: this.selectedQuarter,
            year: this.selectedYear,
            report_type: this.showMonthlySummary ? 'monthly_summary' : 'standard'
          }
        })
        
        if (response.data.success) {
          if (this.showMonthlySummary) {
            console.log('Monthly summary data:', response.data.data.monthly_summary)
            this.monthlySummaryData = response.data.data.monthly_summary
          } else {
            this.alvData = response.data.data
            this.updateDataFromAPI(response.data.data)
          }
        } else {
          console.error('API error:', response.data.message)
        }
      } catch (error) {
        console.error('Error loading ALV-laskenta:', error)
      } finally {
        this.loading = false
      }
    },
    
    toggleMonthlySummary() {
      this.showMonthlySummary = !this.showMonthlySummary
      this.loadALVLaskenta()
    },
    
    async loadCompanyDetails() {
      try {
        const response = await api.get('/company.php')
        if (response.data.success) {
          const companyData = response.data.data
          this.companyName = companyData.name
          this.companyYtunnus = companyData.y_tunnus
        }
      } catch (error) {
        console.error('Error loading company details:', error)
        // Keep default values if API fails
      }
    },
    
    updateDataFromAPI(data) {
      // Update VAT data with API response
      if (data.vat_breakdown) {
        this.vatData = { ...this.vatData, ...data.vat_breakdown }
      }
    },
    
    formatVatRate(rate) {
      return rate.toString().replace('.', ',')
    },
    
    formatMonth(monthString) {
      const [year, month] = monthString.split('-')
      const date = new Date(year, month - 1)
      return date.toLocaleDateString('fi-FI', { year: 'numeric', month: 'long' })
    },
    
    exportToPDF() {
      window.print()
    },
    
    printReport() {
      window.print()
    }
  },
  
  mounted() {
    this.loadALVLaskenta()
  }
}
</script>

<style scoped>
.card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  margin: 0;
  color: #333 !important;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.period-selector, .month-input, .year-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  color: #333;
}

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

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30px;
  padding: 20px;
  border: 2px solid #333;
  background: white;
}

.company-info h3, .period-info h4 {
  margin: 0 0 5px 0;
  color: #333;
}

.company-info p, .period-info p {
  margin: 0;
  color: #666;
}

.alv-container {
  background: white;
}

.alv-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 30px;
  background: white;
  border: 1px solid #ddd;
}

.alv-table th {
  background: #f8f9fa;
  padding: 12px 8px;
  text-align: left;
  border-bottom: 2px solid #333;
  font-weight: 600;
  color: #333;
}

.alv-table td {
  padding: 10px 8px;
  border-bottom: 1px solid #eee;
  color: #333;
}

.vat-rate {
  font-weight: 600;
  text-align: center;
  background: #e9ecef;
}

.amount {
  text-align: right;
  font-family: 'Courier New', monospace;
}

.net-vat {
  font-weight: 600;
  background: #fff3cd;
}

.total-row {
  background: #e9ecef;
  font-weight: 700;
}

.total-row td {
  border-top: 2px solid #333;
  border-bottom: 2px solid #333;
}

.total {
  font-weight: 700;
}

.net-total {
  background: #d1ecf1;
  color: #0c5460;
}

.summary-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.summary-card {
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.summary-card.payable {
  background-color: #f8d7da;
  border-left: 4px solid #dc3545;
}

.summary-card.deductible {
  background-color: #d4edda;
  border-left: 4px solid #28a745;
}

.summary-card.net {
  background-color: #d1ecf1;
  border-left: 4px solid #17a2b8;
}

.summary-card.turnover {
  background-color: #fff3cd;
  border-left: 4px solid #ffc107;
}

.summary-card h3 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 1rem;
}

.summary-card .amount {
  font-size: 1.5rem;
  font-weight: 700;
  margin: 0 0 5px 0;
  color: #333;
}

.summary-card .description {
  margin: 0;
  font-size: 0.9rem;
  color: #666;
}

.detailed-breakdown {
  margin-top: 30px;
}

.detailed-breakdown h3 {
  margin: 0 0 20px 0;
  color: #333;
  border-bottom: 2px solid #333;
  padding-bottom: 10px;
}

.breakdown-section {
  margin-bottom: 30px;
}

.breakdown-section h4 {
  margin: 0 0 15px 0;
  color: #333;
}

.breakdown-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
  background: white;
  border: 1px solid #ddd;
}

.breakdown-table th {
  background: #f8f9fa;
  padding: 10px 8px;
  text-align: left;
  border-bottom: 1px solid #ddd;
  font-weight: 600;
  color: #333;
}

.breakdown-table td {
  padding: 8px;
  border-bottom: 1px solid #eee;
  color: #333;
}

@media print {
  .header-actions {
    display: none;
  }
  
  .alv-table {
    font-size: 10pt;
  }
  
  .summary-cards {
    display: none;
  }
}

.monthly-summary {
  margin: 20px 0;
}

.monthly-summary h3 {
  margin: 0 0 15px 0;
  color: #333;
  border-bottom: 2px solid #333;
  padding-bottom: 10px;
}

.monthly-summary-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
  background: white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.monthly-summary-table th,
.monthly-summary-table td {
  padding: 12px;
  text-align: right;
  border: 1px solid #ddd;
}

.monthly-summary-table th:first-child,
.monthly-summary-table td:first-child {
  text-align: left;
  font-weight: 500;
  color: #333 !important;
}

.monthly-summary-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #333;
}

.monthly-summary-table .total-row {
  background-color: #f8f9fa;
  font-weight: 600;
  border-top: 2px solid #333;
}

.monthly-summary-table .total-row td {
  font-weight: 600;
}

.summary-card.payable {
  color: #d32f2f;
  font-weight: 500;
}

.summary-card.deductible {
  color: #2e7d32;
  font-weight: 500;
}

.summary-card.net {
  color: #1976d2;
  font-weight: 500;
}

.summary-card.turnover {
  color: #6a1b9a;
  font-weight: 500;
}

@media print {
  .monthly-summary-table {
    font-size: 10pt;
  }
}
</style>
