<?php
require_once __DIR__ . '/../config.php';



$db = contracts_db();
mysqli_set_charset($db, 'utf8mb4');             // <-- juda muhim
$db->query("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci");
$db->query("SET time_zone = '+05:00'");


$u=current_user(); if(!$u || $u['role']!=='operator'){ http_response_code(403); exit("Operator kerak"); }
$op=(int)$u['operator_id']; $ym=$_GET['ym'] ?? date('Y-m'); $db=db();

$ymq = $db->real_escape_string($ym);
$out = ['status_counts'=>['approved'=>0,'pending'=>0,'rejected'=>0],
        'per_item'=>[], 'per_day'=>[]];

// Status counts
$r=$db->query("SELECT status, COUNT(*) c FROM kpi_submissions WHERE operator_id=$op AND ym='$ymq' GROUP BY status");
while($x=$r->fetch_assoc()){ $out['status_counts'][$x['status']] = (int)$x['c']; }

// Per item (title)
$r=$db->query("SELECT i.title,
                      SUM(s.status='approved') AS approved,
                      SUM(s.status='pending')  AS pending,
                      SUM(s.status='rejected') AS rejected
               FROM kpi_submissions s
               JOIN kpi_items i ON i.id=s.item_id
               WHERE s.operator_id=$op AND s.ym='$ymq'
               GROUP BY i.title
               ORDER BY i.title");
while($x=$r->fetch_assoc()){ $out['per_item'][]=['title'=>$x['title'], 'approved'=>(int)$x['approved'], 'pending'=>(int)$x['pending'], 'rejected'=>(int)$x['rejected']]; }

// Per day (created_at mavjud bo‘lsa)
$r=$db->query("SELECT DATE(created_at) d, COUNT(*) c FROM kpi_submissions WHERE operator_id=$op AND ym='$ymq' GROUP BY DATE(created_at) ORDER BY d");
while($x=$r->fetch_assoc()){ $out['per_day'][]=['day'=>$x['d'], 'count'=>(int)$x['c']]; }

json_out($out);
