<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Circle Chart with D3JS</title>
  <style>
    .header {
      background-color: #29384D;
      height: 40px;
      color: #fff;
      line-height: 40px;
      border-top-left-radius: 5px;
      border-top-right-radius: 5px;
      font-weight: 400;
      font-size: 1.5em;
      text-transform: uppercase;
      text-shadow: 1px 1px #06060d;
    }

    .chart-container {
      padding: 25px;
    }

    .shadow {
      -webkit-filter: drop-shadow(0px 3px 3px rgba(0, 0, 0, 0.5));
      filter: drop-shadow(0px 3px 3px rgba(0, 0, 0, 0.5));
    }
  </style>
</head>
<body style="background-color:#1a1d20">
  <div class="widget">
    <div class="header"><a style="margin-left:20px">လစဉ်ရောင်းရစာရင်း</a></div>
    <div id="chart" class="chart-container"></div>
  </div>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js'></script>

  <?php
    include "database/database.php";
    include "database/data.php";
    include "cal_expense.php";

    $month = date("m");

    // Retrieve total sales by currency for the given month
    $queries = [
      'kyat' => "SELECT SUM(s.total) AS total_kyat FROM ".$sell_data." s JOIN ".$banking." b ON s.banking = b.type WHERE Month(s.date) = '$month' AND b.currency = 'kyat'",
      'baht' => "SELECT SUM(s.total) AS total_baht FROM ".$sell_data." s JOIN ".$banking." b ON s.banking = b.type WHERE Month(s.date) = '$month' AND b.currency = 'baht'",
      'yuan' => "SELECT SUM(s.total) AS total_yuan FROM ".$sell_data." s JOIN ".$banking." b ON s.banking = b.type WHERE Month(s.date) = '$month' AND b.currency = 'yuan'",
      'dollar' => "SELECT SUM(s.total) AS total_dollar FROM ".$sell_data." s JOIN ".$banking." b ON s.banking = b.type WHERE Month(s.date) = '$month' AND b.currency = 'dollar'"
    ];

    $totals = [];
    foreach ($queries as $key => $query) {
      $result = mysqli_query($connection, $query);
      $row = mysqli_fetch_assoc($result);
      $totals[$key] = $row['total_' . $key] ?: 0;
    }

    $total = array_sum($totals);

    $data = [];
    foreach ($totals as $currency => $amount) {
      $data[] = [
        "name" => ucfirst($currency),
        "percent" => $total > 0 ? ($amount / $total) * 100 : 0
      ];
    }

    echo "<script>var dataset = " . json_encode($data) . ";</script>";
  ?>

  <script>
    var pie = d3.layout.pie()
      .value(function(d) { return d.percent; })
      .sort(null)
      .padAngle(.03);

    var w = 500, h = 380; // Increase height to make space for the vertical legend

    var outerRadius = 100; // Radius of the pie chart
    var innerRadius = 60;  // Inner radius for a donut chart

    var color = d3.scale.category10();

    var arc = d3.svg.arc()
      .outerRadius(outerRadius)
      .innerRadius(innerRadius);

    var svg = d3.select("#chart")
      .append("svg")
      .attr({
          width: w,
          height: h,
          class: 'shadow'
      }).append('g')
      .attr({
          transform: 'translate(' + (w / 2) + ',' + (outerRadius + 20) + ')' // Center the chart horizontally
      });

    var path = svg.selectAll('path')
      .data(pie(dataset))
      .enter()
      .append('path')
      .attr({
          d: arc,
          fill: function(d) {
              return color(d.data.name);
          }
      });

    path.transition()
      .duration(1000)
      .attrTween('d', function(d) {
          var interpolate = d3.interpolate({ startAngle: 0, endAngle: 0 }, d);
          return function(t) {
              return arc(interpolate(t));
          };
      });

    var restOfTheData = function() {
        svg.selectAll('text')
            .data(pie(dataset))
            .enter()
            .append("text")
            .transition()
            .duration(200)
            .attr("transform", function(d) {
                return "translate(" + arc.centroid(d) + ")";
            })
            .attr("dy", ".4em")
            .attr("text-anchor", "middle")
            .text(function(d) {
                return d.data.percent.toFixed(1) + "%";
            })
            .style({
                fill: '#fff',
                'font-size': '14px'
            });

        var legendRectSize = 20;
        var legendSpacing = 7;

        var legend = svg.selectAll('.legend')
            .data(dataset)
            .enter()
            .append('g')
            .attr({
                class: 'legend',
                transform: function(d, i) {
                    var legendX = -(outerRadius + 120); // Align to the left side of the chart
                    var legendY = outerRadius + 40 + (i * (legendRectSize + legendSpacing)); // Position each item vertically below the previous one
                    return 'translate(' + legendX + ',' + legendY + ')';
                }
            });

        legend.append('rect')
            .attr({
                width: legendRectSize,
                height: legendRectSize,
                fill: function(d) { return color(d.name); }
            });

        legend.append('text')
            .attr({
                x: legendRectSize + legendSpacing,
                y: legendRectSize - legendSpacing
            })
            .text(function(d) {
                return d.name;
            })
            .style({
                fill: '#fff',
                'font-size': '14px'
            });

        // Add logo inside the circle
        svg.append("svg:image")
            .attr({
                "xlink:href": "image/logo.png", // URL of the logo image
                x: -30, // Adjust x position
                y: -30, // Adjust y position
                width: 60, // Adjusted size
                height: 60 // Adjusted size
            });
    };

    setTimeout(restOfTheData, 1000);
  </script>
</body>
</html>
