{% extends "base.html" %}
{% block title %}Profit Report{% endblock %}

{% block content %}
<style>
  :root {
    --primary-color: #8b5cf6;
    --primary-light: #c4b5fd;
    --primary-dark: #6d28d9;
    --success-color: #10b981;
    --danger-color: #ef4444;
    --warning-color: #f59e0b;
    --bg-light: #faf5ff;
    --bg-card: #ffffff;
    --border-color: #e9d5ff;
    --text-dark: #1e293b;
    --text-light: #64748b;
    --shadow-sm: 0 1px 3px rgba(139, 92, 246, 0.12);
    --shadow-md: 0 4px 6px rgba(139, 92, 246, 0.15);
    --shadow-lg: 0 10px 15px rgba(139, 92, 246, 0.2);
  }

  body {
    background: var(--bg-light);
  }

  /* Container */
  .report-container {
    background: var(--bg-card);
    border-radius: 16px;
    padding: 2rem;
    margin-bottom: 2rem;
    box-shadow: var(--shadow-md);
    border: 1px solid var(--border-color);
  }

  /* Section Headers */
  .section-header {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 1.5rem;
    padding-bottom: 1rem;
    border-bottom: 3px solid var(--primary-color);
  }

  .section-header h2 {
    margin: 0;
    font-size: 1.75rem;
    font-weight: 700;
    color: var(--text-dark);
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }

  .section-icon {
    font-size: 2rem;
    filter: drop-shadow(2px 2px 4px rgba(0,0,0,0.1));
  }

  /* Form Styling */
  .form-control {
    border: 2px solid var(--border-color);
    border-radius: 10px;
    padding: 0.75rem 1rem;
    transition: all 0.3s ease;
    font-size: 0.95rem;
  }

  .form-control:focus {
    border-color: var(--primary-color);
    box-shadow: 0 0 0 4px rgba(139, 92, 246, 0.1);
    outline: none;
  }

  .form-label {
    font-weight: 700;
    color: var(--text-dark);
    margin-bottom: 0.5rem;
    font-size: 0.85rem;
    text-transform: uppercase;
    letter-spacing: 0.03em;
  }

  .btn-primary {
    background: linear-gradient(135deg, #8b5cf6 0%, #6d28d9 100%);
    border: none;
    padding: 0.85rem 2rem;
    border-radius: 10px;
    font-weight: 700;
    font-size: 1rem;
    transition: all 0.3s ease;
    text-transform: uppercase;
    letter-spacing: 0.05em;
  }

  .btn-primary:hover {
    background: linear-gradient(135deg, #7c3aed 0%, #5b21b6 100%);
    transform: translateY(-2px);
    box-shadow: var(--shadow-lg);
  }

  /* Stats Cards */
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 1.5rem;
    margin-bottom: 2rem;
  }

  .stat-card {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    box-shadow: var(--shadow-md);
    border: 2px solid var(--border-color);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
  }

  .stat-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, var(--card-color) 0%, var(--card-color-light) 100%);
  }

  .stat-card:hover {
    transform: translateY(-5px);
    box-shadow: var(--shadow-lg);
  }

  .stat-card-header {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    margin-bottom: 1rem;
  }

  .stat-icon {
    font-size: 2rem;
    width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 12px;
    background: linear-gradient(135deg, var(--card-color) 0%, var(--card-color-light) 100%);
  }

  .stat-label {
    font-size: 0.85rem;
    font-weight: 600;
    color: var(--text-light);
    text-transform: uppercase;
    letter-spacing: 0.05em;
  }

  .stat-value {
    font-size: 1.75rem;
    font-weight: 800;
    color: var(--text-dark);
    margin-top: 0.5rem;
  }

  /* Color variants for stat cards */
  .stat-card.revenue {
    --card-color: #3b82f6;
    --card-color-light: #60a5fa;
  }

  .stat-card.cost {
    --card-color: #f59e0b;
    --card-color-light: #fbbf24;
  }

  .stat-card.profit {
    --card-color: #10b981;
    --card-color-light: #34d399;
  }

  .stat-card.expense {
    --card-color: #ef4444;
    --card-color-light: #f87171;
  }

  .stat-card.final {
    --card-color: #8b5cf6;
    --card-color-light: #a78bfa;
  }

  /* Date Range Display */
  .date-range {
    background: linear-gradient(135deg, #e9d5ff 0%, #ddd6fe 100%);
    border: 2px solid #c4b5fd;
    border-radius: 12px;
    padding: 1.25rem 1.5rem;
    margin-bottom: 2rem;
    display: flex;
    align-items: center;
    gap: 1rem;
  }

  .date-range-icon {
    font-size: 1.75rem;
  }

  .date-range-text {
    font-size: 1.1rem;
    font-weight: 700;
    color: var(--text-dark);
  }

  /* Charts Container */
  .charts-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
    gap: 2rem;
    margin-top: 2rem;
  }

  .chart-container {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    box-shadow: var(--shadow-md);
    border: 2px solid var(--border-color);
  }

  .chart-title {
    font-size: 1.25rem;
    font-weight: 700;
    color: var(--text-dark);
    margin-bottom: 1.5rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }

  canvas {
    max-height: 300px;
  }

  /* Mobile Responsive */
  @media (max-width: 768px) {
    .report-container {
      padding: 1.5rem;
      border-radius: 12px;
    }

    .section-header h2 {
      font-size: 1.4rem;
    }

    .stats-grid {
      grid-template-columns: 1fr;
    }

    .charts-grid {
      grid-template-columns: 1fr;
    }

    .stat-value {
      font-size: 1.5rem;
    }

    .btn-mobile-full {
      width: 100%;
    }
  }

  /* Empty State */
  .empty-state {
    text-align: center;
    padding: 4rem 2rem;
    color: var(--text-light);
  }

  .empty-state-icon {
    font-size: 4rem;
    margin-bottom: 1rem;
    opacity: 0.5;
  }

  .empty-state-text {
    font-size: 1.1rem;
    font-weight: 600;
  }
</style>

<div class="report-container">
  <div class="section-header">
    <span class="section-icon">📈</span>
    <h2>Net Profit Calculator</h2>
  </div>

  <form method="POST" class="row g-3">
    <div class="col-md-4">
      <label for="start_date" class="form-label">📅 From Date</label>
      <input type="date" class="form-control" name="start_date" id="start_date" required>
    </div>
    <div class="col-md-4">
      <label for="end_date" class="form-label">📅 To Date</label>
      <input type="date" class="form-control" name="end_date" id="end_date" required>
    </div>
    <div class="col-md-4 d-flex align-items-end">
      <button type="submit" class="btn btn-primary btn-mobile-full">🔍 Calculate Report</button>
    </div>
  </form>
</div>

{% if result %}
<div class="report-container">
  <div class="date-range">
    <span class="date-range-icon">📅</span>
    <span class="date-range-text">Report Period: {{ result.start_date }} to {{ result.end_date }}</span>
  </div>

  <!-- Statistics Cards -->
  <div class="stats-grid">
    <div class="stat-card revenue">
      <div class="stat-card-header">
        <div class="stat-icon">💰</div>
        <div class="stat-label">Total Cash Received</div>
      </div>
      <div class="stat-value">{{ result.cash_received }}</div>
    </div>

    <div class="stat-card cost">
      <div class="stat-card-header">
        <div class="stat-icon">🛒</div>
        <div class="stat-label">Total Cost</div>
      </div>
      <div class="stat-value">{{ result.total_cost }}</div>
    </div>

    <div class="stat-card profit">
      <div class="stat-card-header">
        <div class="stat-icon">📘</div>
        <div class="stat-label">Monthly Profit</div>
      </div>
      <div class="stat-value">{{ result.monthly_profit }}</div>
    </div>

    <div class="stat-card expense">
      <div class="stat-card-header">
        <div class="stat-icon">🧾</div>
        <div class="stat-label">Total Expenses</div>
      </div>
      <div class="stat-value">{{ result.expenses }}</div>
    </div>

    <div class="stat-card final">
      <div class="stat-card-header">
        <div class="stat-icon">{% if result.is_profit %}📈{% else %}🔻{% endif %}</div>
        <div class="stat-label">{% if result.is_profit %}Final Profit{% else %}Final Loss{% endif %}</div>
      </div>
      <div class="stat-value" style="color: {% if result.is_profit %}#10b981{% else %}#ef4444{% endif %}">
        {{ result.final_profit }}
      </div>
    </div>
  </div>

  <!-- Charts -->
  <div class="charts-grid">
    <div class="chart-container">
      <div class="chart-title">💹 Revenue vs Expenses</div>
      <canvas id="revenueExpenseChart"></canvas>
    </div>

    <div class="chart-container">
      <div class="chart-title">📊 Profit Breakdown</div>
      <canvas id="profitBreakdownChart"></canvas>
    </div>

    <div class="chart-container">
      <div class="chart-title">🥧 Cost Distribution</div>
      <canvas id="costDistributionChart"></canvas>
    </div>

    <div class="chart-container">
      <div class="chart-title">📈 Profitability Analysis</div>
      <canvas id="profitabilityChart"></canvas>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
  // Parse result data
  const parseAmount = (str) => parseFloat(str.replace(/[Rs.,\s]/g, '')) || 0;
  
  const cashReceived = parseAmount('{{ result.cash_received }}');
  const totalCost = parseAmount('{{ result.total_cost }}');
  const monthlyProfit = parseAmount('{{ result.monthly_profit }}');
  const expenses = parseAmount('{{ result.expenses }}');
  const finalProfit = parseAmount('{{ result.final_profit }}');
  const isProfit = {{ 'true' if result.is_profit else 'false' }};

  // Chart configuration
  const chartConfig = {
    responsive: true,
    maintainAspectRatio: true,
    plugins: {
      legend: {
        display: true,
        position: 'bottom',
        labels: {
          padding: 15,
          font: {
            size: 12,
            weight: '600'
          }
        }
      }
    }
  };

  // 1. Revenue vs Expenses Bar Chart
  new Chart(document.getElementById('revenueExpenseChart'), {
    type: 'bar',
    data: {
      labels: ['Cash Received', 'Total Cost', 'Expenses'],
      datasets: [{
        label: 'Amount (Rs.)',
        data: [cashReceived, totalCost, expenses],
        backgroundColor: [
          'rgba(59, 130, 246, 0.8)',
          'rgba(245, 158, 11, 0.8)',
          'rgba(239, 68, 68, 0.8)'
        ],
        borderColor: [
          'rgb(59, 130, 246)',
          'rgb(245, 158, 11)',
          'rgb(239, 68, 68)'
        ],
        borderWidth: 2,
        borderRadius: 8
      }]
    },
    options: {
      ...chartConfig,
      scales: {
        y: {
          beginAtZero: true,
          ticks: {
            callback: function(value) {
              return 'Rs. ' + value.toLocaleString();
            }
          }
        }
      }
    }
  });

  // 2. Profit Breakdown Doughnut Chart
  new Chart(document.getElementById('profitBreakdownChart'), {
    type: 'doughnut',
    data: {
      labels: ['Monthly Profit', 'Expenses', isProfit ? 'Final Profit' : 'Final Loss'],
      datasets: [{
        data: [monthlyProfit, expenses, Math.abs(finalProfit)],
        backgroundColor: [
          'rgba(16, 185, 129, 0.8)',
          'rgba(239, 68, 68, 0.8)',
          isProfit ? 'rgba(139, 92, 246, 0.8)' : 'rgba(220, 38, 38, 0.8)'
        ],
        borderColor: [
          'rgb(16, 185, 129)',
          'rgb(239, 68, 68)',
          isProfit ? 'rgb(139, 92, 246)' : 'rgb(220, 38, 38)'
        ],
        borderWidth: 2
      }]
    },
    options: {
      ...chartConfig,
      plugins: {
        ...chartConfig.plugins,
        tooltip: {
          callbacks: {
            label: function(context) {
              return context.label + ': Rs. ' + context.parsed.toLocaleString();
            }
          }
        }
      }
    }
  });

  // 3. Cost Distribution Pie Chart
  new Chart(document.getElementById('costDistributionChart'), {
    type: 'pie',
    data: {
      labels: ['Product Cost', 'Operating Expenses'],
      datasets: [{
        data: [totalCost, expenses],
        backgroundColor: [
          'rgba(245, 158, 11, 0.8)',
          'rgba(239, 68, 68, 0.8)'
        ],
        borderColor: [
          'rgb(245, 158, 11)',
          'rgb(239, 68, 68)'
        ],
        borderWidth: 2
      }]
    },
    options: {
      ...chartConfig,
      plugins: {
        ...chartConfig.plugins,
        tooltip: {
          callbacks: {
            label: function(context) {
              const total = context.dataset.data.reduce((a, b) => a + b, 0);
              const percentage = ((context.parsed / total) * 100).toFixed(1);
              return context.label + ': Rs. ' + context.parsed.toLocaleString() + ' (' + percentage + '%)';
            }
          }
        }
      }
    }
  });

  // 4. Profitability Analysis Line Chart
  new Chart(document.getElementById('profitabilityChart'), {
    type: 'line',
    data: {
      labels: ['Revenue', 'After Costs', 'After Expenses'],
      datasets: [{
        label: 'Profit Flow',
        data: [cashReceived, monthlyProfit, finalProfit],
        borderColor: isProfit ? 'rgb(16, 185, 129)' : 'rgb(239, 68, 68)',
        backgroundColor: isProfit ? 'rgba(16, 185, 129, 0.1)' : 'rgba(239, 68, 68, 0.1)',
        borderWidth: 3,
        fill: true,
        tension: 0.4,
        pointRadius: 6,
        pointBackgroundColor: isProfit ? 'rgb(16, 185, 129)' : 'rgb(239, 68, 68)',
        pointBorderColor: '#fff',
        pointBorderWidth: 2,
        pointHoverRadius: 8
      }]
    },
    options: {
      ...chartConfig,
      scales: {
        y: {
          ticks: {
            callback: function(value) {
              return 'Rs. ' + value.toLocaleString();
            }
          }
        }
      },
      plugins: {
        ...chartConfig.plugins,
        tooltip: {
          callbacks: {
            label: function(context) {
              return 'Amount: Rs. ' + context.parsed.y.toLocaleString();
            }
          }
        }
      }
    }
  });
</script>
{% else %}
<div class="report-container">
  <div class="empty-state">
    <div class="empty-state-icon">📊</div>
    <div class="empty-state-text">Select a date range to generate profit report</div>
  </div>
</div>
{% endif %}

{% endblock %}