<?php
session_start();
include '../koneksi.php';
$is_input_pengeluaran = (isset($_SESSION['status']) && $_SESSION['status'] === 'input_pengeluaran_logedin');

// Parameter DataTables
$draw = isset($_POST['draw']) ? (int)$_POST['draw'] : 1;
$start = isset($_POST['start']) ? (int)$_POST['start'] : 0;
$length = isset($_POST['length']) ? (int)$_POST['length'] : 25;
if ($length < 1) $length = 999999; // "Semua"
$searchValue = isset($_POST['search']['value']) ? mysqli_real_escape_string($koneksi, $_POST['search']['value']) : '';
$orderCol = isset($_POST['order'][0]['column']) ? (int)$_POST['order'][0]['column'] : 1;
$orderDir = isset($_POST['order'][0]['dir']) ? mysqli_real_escape_string($koneksi, $_POST['order'][0]['dir']) : 'desc';

// Filter (tanggal bisa dd/mm/yyyy dari datepicker)
$tanggal_dari = trim($_POST['tanggal_dari'] ?? '');
$tanggal_sampai = trim($_POST['tanggal_sampai'] ?? '');
$filter_shift = mysqli_real_escape_string($koneksi, $_POST['shift'] ?? '');

if (preg_match('#^(\d{1,2})/(\d{1,2})/(\d{4})$#', $tanggal_dari, $m)) {
  $tanggal_dari = $m[3] . '-' . str_pad($m[2], 2, '0', STR_PAD_LEFT) . '-' . str_pad($m[1], 2, '0', STR_PAD_LEFT);
}
if (preg_match('#^(\d{1,2})/(\d{1,2})/(\d{4})$#', $tanggal_sampai, $m)) {
  $tanggal_sampai = $m[3] . '-' . str_pad($m[2], 2, '0', STR_PAD_LEFT) . '-' . str_pad($m[1], 2, '0', STR_PAD_LEFT);
}

$where = "1=1";
if ($tanggal_dari !== '') $where .= " AND tanggal >= '$tanggal_dari'";
if ($tanggal_sampai !== '') $where .= " AND tanggal <= '$tanggal_sampai'";
if ($filter_shift !== '') $where .= " AND shift = '$filter_shift'";

if ($searchValue !== '') {
  $where .= " AND (tanggal LIKE '%$searchValue%' OR shift LIKE '%$searchValue%' OR nominal LIKE '%$searchValue%' OR keterangan LIKE '%$searchValue%')";
}

$columns = array(0 => 'id', 1 => 'tanggal', 2 => 'shift', 3 => 'nominal', 4 => 'keterangan', 5 => 'id');
$orderBy = isset($columns[$orderCol]) ? $columns[$orderCol] : 'tanggal';
if ($orderBy === 'id') $orderBy = 'tanggal';
$orderDir = strtoupper($orderDir) === 'ASC' ? 'ASC' : 'DESC';

// Total tanpa filter
$resTotal = mysqli_query($koneksi, "SELECT COUNT(*) as total FROM laporan_kasir");
$totalRecords = (int)mysqli_fetch_assoc($resTotal)['total'];

// WHERE untuk filter saja (tanpa search) - dipakai untuk total nominal & chart
$whereBase = "1=1";
if ($tanggal_dari !== '') $whereBase .= " AND tanggal >= '$tanggal_dari'";
if ($tanggal_sampai !== '') $whereBase .= " AND tanggal <= '$tanggal_sampai'";
if ($filter_shift !== '') $whereBase .= " AND shift = '$filter_shift'";

// Jumlah baris yang match filter + search (untuk recordsFiltered DataTables)
$resFiltered = mysqli_query($koneksi, "SELECT COUNT(*) as total FROM laporan_kasir WHERE $where");
$filteredRecords = (int)mysqli_fetch_assoc($resFiltered)['total'];

// Data dengan pagination
$query = "SELECT * FROM laporan_kasir WHERE $where ORDER BY $orderBy $orderDir, FIELD(shift,'Pagi','Siang','Malam') LIMIT $start, $length";
$result = mysqli_query($koneksi, $query);

$data = array();
$no = $start + 1;
while ($row = mysqli_fetch_assoc($result)) {
  $opsi = '';
  if (!$is_input_pengeluaran) {
    $opsi .= '<button type="button" class="btn btn-warning btn-sm btn-edit-tunai" data-id="' . $row['id'] . '" data-toggle="modal" data-target="#modalEdit" title="Edit"><i class="fa fa-edit"></i></button>';
    $opsi .= ' <button type="button" class="btn btn-danger btn-sm btn-hapus-tunai" data-id="' . $row['id'] . '" title="Hapus"><i class="fa fa-trash"></i></button>';
  } else {
    $opsi = '<span class="text-muted">-</span>';
  }
  $data[] = array(
    $no++,
    date('d/m/Y', strtotime($row['tanggal'])),
    $row['shift'],
    'Rp. ' . number_format($row['nominal'], 0, ',', '.') . ' ,-',
    ($row['keterangan'] !== null && $row['keterangan'] !== '') ? htmlspecialchars($row['keterangan']) : '-',
    $opsi
  );
}

// Total nominal (filter)
$resSum = mysqli_query($koneksi, "SELECT COALESCE(SUM(nominal),0) as total FROM laporan_kasir WHERE $whereBase");
$totalNominal = (float)mysqli_fetch_assoc($resSum)['total'];

// Chart (group by tanggal, filter yang sama)
$chartQuery = "SELECT tanggal, SUM(nominal) as total FROM laporan_kasir WHERE $whereBase GROUP BY tanggal ORDER BY tanggal ASC";
$chartRes = mysqli_query($koneksi, $chartQuery);
$chart_labels = array();
$chart_data = array();
while ($r = mysqli_fetch_assoc($chartRes)) {
  $chart_labels[] = date('d/m', strtotime($r['tanggal']));
  $chart_data[] = (float)$r['total'];
}

header('Content-Type: application/json');
echo json_encode(array(
  'draw' => $draw,
  'recordsTotal' => $totalRecords,
  'recordsFiltered' => $filteredRecords,
  'data' => $data,
  'total_nominal' => $totalNominal,
  'chart_labels' => $chart_labels,
  'chart_data' => $chart_data
));
