<?php
include 'database/shikanisha.kts.php';

if (isset($_GET['year'])) {
  $selectedYear = $_GET['year'];

  // Check connection
  if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
  }

  // Retrieve data for each month of the selected year
  $sql = "SELECT MONTHNAME(cs.seller_date) AS month, 
           SUM(cs.total) AS total_sales,
    SUM(cs.amount_received) AS total_received,
    SUM(cs.total) - SUM(cs.amount_received) AS total_debt,
    SUM(CASE WHEN t.payment_method = 'cash' THEN t.amount ELSE 0 END) AS cash_total,
    SUM(CASE WHEN t.payment_method = 'merchant' THEN t.amount ELSE 0 END) AS merchant_total,
    SUM(CASE WHEN t.payment_method = 'Captains Order' THEN t.amount ELSE 0 END) AS captain_total,
    SUM(CASE WHEN t.payment_method = 'till' THEN t.amount ELSE 0 END) AS till_total
    FROM transaction_receipts cs
    LEFT JOIN payments t ON cs.trans_id = t.trans_id
    WHERE YEAR(cs.seller_date) = $selectedYear
    GROUP BY MONTH(cs.seller_date)
    ORDER BY MONTH(cs.seller_date)";

  $result = $conn->query($sql);

  if ($result->num_rows > 0) {
    // Prepare data for the chart
    $labels = array();
    $cash_data = array();
    $till_data = array();
    $merchant_data = array();
    $captain_data = array();
    $debt = array();
    
    while ($row = $result->fetch_assoc()) {
      array_push($labels, $row["month"]);
      array_push($cash_data, $row["cash_total"]);
      array_push($merchant_data, $row["merchant_total"]);
      array_push($till_data, $row["till_total"]);
      array_push($captain_data, $row["captain_total"]);
      array_push($debt, $row["total_debt"]);
    }

    // Create an array with month names from January to December
    $months = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');

    // Loop through the months and check if data is available for each month
    for ($i = 0; $i < 12; $i++) {
      $month = $months[$i];
      if (!in_array($month, $labels)) {
        // If data is not available for the month, add 0 values
       
        array_push($labels, $row["month"]);
        array_push($cash_data, $row["cash_total"]);
        array_push($merchant_data, $row["merchant_total"]);
        array_push($captain_data, $row["captain_total"]);
        array_push($till_data, $row["till_total"]);
        array_push($debt, $row["total_debt"]);
      }
    }

    $response = array(
     'labels' => $labels,
    'cash_data' => $cash_data,
    'till_data' => $till_data,
    'merchant_data' => $merchant_data,
    'captain_data' => $captain_data,
    'debt' => $debt
    );

    echo json_encode($response);
  } else {
    echo "0 results";
  }

  $conn->close();
} else {
  echo "Invalid request";
}
?>
