<?php
define('BASEPATH', dirname(__FILE__));
session_start();

if (!isset($_SESSION['id_admin'])) {
    http_response_code(401);
    header('Content-Type: application/json');
    echo json_encode(array(
        'status' => false,
        'message' => 'Unauthorized'
    ));
    exit;
}

include('../include/connection.php');

$now = date('Y');
$next = date('Y') + 1;
$periode = $now.'/'.$next;

$query = $con->prepare("SELECT id_kandidat, nama_calon, suara FROM t_kandidat WHERE periode = ? ORDER BY id_kandidat ASC");
if (!$query) {
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode(array(
        'status' => false,
        'message' => 'Query gagal disiapkan'
    ));
    exit;
}
$query->bind_param('s', $periode);
$query->execute();
$query->store_result();

$labels = array();
$votes = array();
$percentages = array();
$rows = array();
$totalVotes = 0;

if ($query->num_rows() > 0) {
    for ($i = 0; $i < $query->num_rows(); $i++) {
        $query->bind_result($id, $nama, $suara);
        $query->fetch();
        $totalVotes += (int) $suara;
        $rows[] = array(
            'id' => (int) $id,
            'nama' => $nama,
            'suara' => (int) $suara
        );
    }
}

for ($i = 0; $i < count($rows); $i++) {
    $labels[] = $rows[$i]['nama'];
    $votes[] = $rows[$i]['suara'];
    $percentage = $totalVotes > 0 ? round(($rows[$i]['suara'] / $totalVotes) * 100, 2) : 0;
    $percentages[] = $percentage;
}

header('Content-Type: application/json');
echo json_encode(array(
    'status' => true,
    'periode' => $periode,
    'total_suara' => $totalVotes,
    'labels' => $labels,
    'votes' => $votes,
    'percentages' => $percentages,
    'updated_at' => date('Y-m-d H:i:s')
));

