<?php
// =====================================================
// GET /get-dashboard.php
// Response: { total_users, total_line_men, total_marketing, total_tickets,
//             tickets_not_closed, tickets_closed, row_data: [...] }
// =====================================================
require_once 'config.php';

$conn = getConnection();

// Count totals
$total_users     = $conn->query("SELECT COUNT(*) as c FROM users")->fetch_assoc()['c'];
$total_line_men  = $conn->query("SELECT COUNT(*) as c FROM line_man")->fetch_assoc()['c'];
$total_marketing = $conn->query("SELECT COUNT(*) as c FROM marketing")->fetch_assoc()['c'];
$total_tickets   = $conn->query("SELECT COUNT(*) as c FROM ticket")->fetch_assoc()['c'];
$tickets_closed  = $conn->query("SELECT COUNT(*) as c FROM ticket WHERE status = 'closed'")->fetch_assoc()['c'];
$tickets_not_closed = $total_tickets - $tickets_closed;

// Get all tickets for row_data
$result = $conn->query("SELECT id, problem, assign, location, created_at, status, end_time,
                                recharge_id, user_id, name, phone, priroty,
                                create_by, check_time, remark, check_count
                         FROM ticket ORDER BY id DESC");

$row_data = [];
while ($row = $result->fetch_assoc()) {
    $row_data[] = $row;
}

echo json_encode([
    "total_users"       => (int)$total_users,
    "total_line_men"    => (int)$total_line_men,
    "total_marketing"   => (int)$total_marketing,
    "total_tickets"     => (int)$total_tickets,
    "tickets_not_closed" => (int)$tickets_not_closed,
    "tickets_closed"    => (int)$tickets_closed,
    "row_data"          => $row_data
]);

$conn->close();
