<?php
if(!defined('BASEPATH')) {
   die('Direct access to the script is not allowed');
}
if( $admin["access"]["admin_access"] != 1  ){

    header("Location:".site_url("admin"));

    exit();
}
  
  $clients = $conn->prepare("SELECT * FROM clients ORDER BY client_id DESC LIMIT 500");
  $clients->execute(array());
  $clients = $clients->fetchAll(PDO::FETCH_ASSOC);







  // Fail Order Count (Existing)
  $failCount = $conn->prepare("SELECT * FROM orders WHERE orders.dripfeed='1' && orders.subscriptions_type='1' && order_error!=:error ");
  $failCount->execute(array("error"=>"-"));
  $failCount = $failCount->rowCount();

  // Today Orders Count (Existing)
  $todayCount = $conn->prepare("SELECT * FROM orders WHERE last_check=:error ");
  $todayCount->execute(array("error"=> date("Y-m-d") ));
  $todayCount = $todayCount->rowCount();

  // --- NEW DASHBOARD DATA (CHART.JS) ---
  $currentYear = date("Y");
  
  // 1. Monthly Revenue (Payments)
  $monthlyRevenue = array_fill(1, 12, 0); // Initialize array with 12 months = 0
  $stmt = $conn->prepare("
      SELECT MONTH(payment_create_date) as month, SUM(payment_amount) as total 
      FROM payments 
      WHERE payment_status = 3 AND YEAR(payment_create_date) = :year 
      GROUP BY MONTH(payment_create_date)
  ");
  $stmt->execute(['year' => $currentYear]);
  while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      $monthlyRevenue[$row['month']] = (float)$row['total'];
  }
  $chartRevenueData = json_encode(array_values($monthlyRevenue));

  // 2. Monthly Orders
  $monthlyOrders = array_fill(1, 12, 0);
  $stmt = $conn->prepare("
      SELECT MONTH(order_create) as month, COUNT(*) as total 
      FROM orders 
      WHERE YEAR(order_create) = :year 
      GROUP BY MONTH(order_create)
  ");
  $stmt->execute(['year' => $currentYear]);
  while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      $monthlyOrders[$row['month']] = (int)$row['total'];
  }
  $chartOrdersData = json_encode(array_values($monthlyOrders));

  // 3. Order Status Distribution (All time or current year)
  $statusDistribution = [
      'Completed' => 0,
      'Processing' => 0,
      'Pending' => 0,
      'In progress' => 0,
      'Partial' => 0,
      'Canceled' => 0,
      'Fail' => 0
  ];
  $stmt = $conn->prepare("
      SELECT order_status, COUNT(*) as total 
      FROM orders 
      GROUP BY order_status
  ");
  $stmt->execute();
  while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      if (array_key_exists($row['order_status'], $statusDistribution)) {
          $statusDistribution[$row['order_status']] = (int)$row['total'];
      }
  }
  $chartStatusData = json_encode(array_values($statusDistribution));
  $chartStatusLabels = json_encode(array_keys($statusDistribution));

  // 4. Recent Activity (Latest 5 Orders)
  $recentOrders = $conn->prepare("
      SELECT orders.*, clients.username 
      FROM orders 
      LEFT JOIN clients ON orders.client_id = clients.client_id 
      ORDER BY orders.order_id DESC 
      LIMIT 6
  ");
  $recentOrders->execute();
  $recentOrders = $recentOrders->fetchAll(PDO::FETCH_ASSOC);

  require admin_view('index');