<?php
// Strict types for better type safety (PHP 7+)
declare(strict_types=1);

// Database credentials (আপনার সঠিক তথ্য দিন)
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'digitalb_beaccurate');
define('DB_PASSWORD', 'Saiful.1633');
define('DB_NAME', 'digitalb_beaccurate');

// --- Helper function to send JSON response and exit ---
function send_json_response(array $data, int $statusCode = 200): void {
    http_response_code($statusCode);
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode($data);
    exit;
}

// --- Database Connection ---
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);

if ($link === false) {
    error_log("Database Connection Error: " . mysqli_connect_error());
    send_json_response([
        'success' => false,
        'message' => 'ডাটাবেস সংযোগে সমস্যা। অনুগ্রহ করে পরে আবার চেষ্টা করুন।',
        'results' => [], 'voted' => false, 'total_votes' => 0,
        'daily_summary' => [], 'monthly_summary' => []
    ], 503);
}
if (!mysqli_set_charset($link, "utf8mb4")) {
    error_log("Error loading character set utf8mb4: " . mysqli_error($link));
}

// Initialize response array
$response = [
    'success' => false, 'message' => 'অবৈধ অনুরোধ।',
    'results' => [], 'voted' => false, 'total_votes' => 0,
    'daily_summary' => [], 'monthly_summary' => []
];

// --- Function to get vote results (মোট ফলাফল) ---
function get_vote_results(mysqli $dbLink): array {
    // এই ফাংশনটি আগের মতোই থাকবে
    $results_data = [];
    $total_votes = 0;
    $sql = "SELECT option_name, vote_count FROM votes";
    $query_result = mysqli_query($dbLink, $sql);

    if ($query_result) {
        while ($row = mysqli_fetch_assoc($query_result)) {
            $results_data[] = $row;
            $total_votes += (int)$row['vote_count'];
        }
        mysqli_free_result($query_result);
        foreach ($results_data as &$item) {
            $item['percentage'] = $total_votes > 0 ? round(((int)$item['vote_count'] / $total_votes) * 100, 2) : 0;
        }
        unset($item);
        return ['data' => $results_data, 'total' => $total_votes, 'error' => null];
    } else {
        error_log("Error fetching results: " . mysqli_error($dbLink));
        return ['data' => [], 'total' => 0, 'error' => 'ফলাফল আনতে সমস্যা হয়েছে: ' . mysqli_error($dbLink)];
    }
}

// --- Function to get daily vote summary for the current month ---
function get_daily_vote_summary_for_month(mysqli $dbLink, int $year, int $month): array {
    // এই ফাংশনটি আগের মতোই থাকবে
    $daily_summary = [];
    $num_days = (int)date('t', mktime(0, 0, 0, $month, 1, $year));

    for ($day = 1; $day <= $num_days; $day++) {
        $date_str = sprintf("%04d-%02d-%02d", $year, $month, $day);
        $daily_summary[$date_str] = ['সংস্কার' => 0, 'নির্বাচন' => 0];
    }
    $start_date = sprintf("%04d-%02d-01", $year, $month);
    $end_date = sprintf("%04d-%02d-%02d", $year, $month, $num_days);

    $sql = "SELECT vote_date, option_name, vote_count FROM vote_log WHERE vote_date BETWEEN ? AND ?";
    if ($stmt = mysqli_prepare($dbLink, $sql)) {
        mysqli_stmt_bind_param($stmt, "ss", $start_date, $end_date);
        if (mysqli_stmt_execute($stmt)) {
            $result = mysqli_stmt_get_result($stmt);
            while ($row = mysqli_fetch_assoc($result)) {
                $vote_date_obj = new DateTime($row['vote_date']);
                $date_key = $vote_date_obj->format('Y-m-d');
                if (isset($daily_summary[$date_key]) && ($row['option_name'] === 'সংস্কার' || $row['option_name'] === 'নির্বাচন')) {
                    $daily_summary[$date_key][$row['option_name']] = (int)$row['vote_count'];
                }
            }
            mysqli_free_result($result);
        } else { error_log("Error executing get_daily_vote_summary query: " . mysqli_stmt_error($stmt));}
        mysqli_stmt_close($stmt);
    } else { error_log("Error preparing get_daily_vote_summary statement: " . mysqli_error($dbLink));}
    return $daily_summary;
}

// --- Function to get monthly vote summary for a given year ---
function get_monthly_vote_summary(mysqli $dbLink, int $year): array {
    $monthly_summary = [];
    for ($m = 1; $m <= 12; $m++) {
        $monthly_summary[$m] = ['সংস্কার' => 0, 'নির্বাচন' => 0];
    }

    $sql = "SELECT MONTH(vote_date) as vote_month, option_name, SUM(vote_count) as total_monthly_votes
            FROM vote_log
            WHERE YEAR(vote_date) = ?
            GROUP BY vote_month, option_name";

    if ($stmt = mysqli_prepare($dbLink, $sql)) {
        mysqli_stmt_bind_param($stmt, "i", $year);
        if (mysqli_stmt_execute($stmt)) {
            $result = mysqli_stmt_get_result($stmt);
            while ($row = mysqli_fetch_assoc($result)) {
                $month_num = (int)$row['vote_month'];
                if (isset($monthly_summary[$month_num]) && ($row['option_name'] === 'সংস্কার' || $row['option_name'] === 'নির্বাচন')) {
                    $monthly_summary[$month_num][$row['option_name']] = (int)$row['total_monthly_votes'];
                }
            }
            mysqli_free_result($result);
        } else { error_log("Error executing get_monthly_vote_summary query: " . mysqli_stmt_error($stmt)); }
        mysqli_stmt_close($stmt);
    } else { error_log("Error preparing get_monthly_vote_summary statement: " . mysqli_error($dbLink)); }
    return $monthly_summary;
}

// --- Function to check if user has voted ---
function has_user_voted(mysqli $dbLink, string $fingerprint): array {
    // এই ফাংশনটি আগের মতোই থাকবে
    if (empty($fingerprint)) return ['voted' => false, 'message' => 'ফিঙ্গারপ্রিন্ট পাওয়া যায়নি।', 'error' => true];
    $sql = "SELECT id FROM voted_users WHERE fingerprint = ?";
    if ($stmt = mysqli_prepare($dbLink, $sql)) {
        mysqli_stmt_bind_param($stmt, "s", $fingerprint);
        if (mysqli_stmt_execute($stmt)) {
            mysqli_stmt_store_result($stmt);
            $hasVoted = mysqli_stmt_num_rows($stmt) > 0;
            mysqli_stmt_close($stmt);
            return ['voted' => $hasVoted, 'message' => $hasVoted ? 'আপনি ইতিমধ্যেই ভোট দিয়েছেন।' : 'ভোট দেওয়ার জন্য প্রস্তুত।', 'error' => false];
        } else {
            error_log("Error executing check voted statement: " . mysqli_stmt_error($stmt));
            mysqli_stmt_close($stmt);
            return ['voted' => false, 'message' => 'ভোটের স্ট্যাটাস যাচাই করতে সমস্যা হয়েছে।', 'error' => true];
        }
    } else {
        error_log("Error preparing check voted statement: " . mysqli_error($dbLink));
        return ['voted' => false, 'message' => 'ভোটের স্ট্যাটাস যাচাইয়ের প্রস্তুতিতে সমস্যা হয়েছে।', 'error' => true];
    }
}

// --- Main Request Handling ---
if ($_SERVER["REQUEST_METHOD"] !== "POST") send_json_response($response, 405);

$current_results_info = get_vote_results($link);
if ($current_results_info['error'] === null) {
    $response['results'] = $current_results_info['data'];
    $response['total_votes'] = $current_results_info['total'];
    $response['success'] = true;
    $response['message'] = 'ফলাফল সফলভাবে লোড হয়েছে।';
} else { $response['message'] = $current_results_info['error']; }

$action = $_POST['action'] ?? '';
$fingerprint = $_POST['fingerprint'] ?? '';

// Fetch daily and monthly summaries
$current_year = (int)date('Y');
$current_month_num = (int)date('m');
$response['daily_summary'] = get_daily_vote_summary_for_month($link, $current_year, $current_month_num);
$response['monthly_summary'] = get_monthly_vote_summary($link, $current_year);

if (!empty($fingerprint)) {
    // ... (has_user_voted কল এবং রেসপন্স সেট করা আগের মতো)
    $voted_status_info = has_user_voted($link, $fingerprint);
    if ($voted_status_info['error']) {
        $response['success'] = false;
        $response['message'] = $voted_status_info['message'];
    } else {
        $response['voted'] = $voted_status_info['voted'];
        if ($voted_status_info['voted']) {
            $response['message'] = $voted_status_info['message'];
        } else if (empty($action)){
            $response['message'] = $voted_status_info['message']; // 'ভোট দেওয়ার জন্য প্রস্তুত।'
        }
    }
} else { if ($action === 'vote') { $response['success'] = false; $response['message'] = 'ভোট দেওয়ার জন্য ডিভাইস ফিঙ্গারপ্রিন্ট আবশ্যক।';}}

// --- Handle 'vote' Action ---
if ($action === 'vote') {
    // ... (ভোট হ্যান্ডলিং লজিক আগের মতোই, শুধু শেষে daily_summary এবং monthly_summary রি-ফেচ করতে হবে)
    $option = $_POST['option'] ?? '';
    $allowed_options = ['সংস্কার', 'নির্বাচন'];

    if (empty($fingerprint)) { $response['success'] = false; }
    else if ($response['voted'] === true) { $response['success'] = false; }
    else if (empty($option) || !in_array($option, $allowed_options, true)) {
        $response['success'] = false; $response['message'] = 'অবৈধ অপশন অথবা অপশন নির্বাচন করা হয়নি।';
    } else {
        mysqli_begin_transaction($link);
        $vote_recorded_successfully = false;
        try {
            // 1. Update total vote count
            $sql_update_vote = "UPDATE votes SET vote_count = vote_count + 1 WHERE option_name = ?";
            $stmt_update = mysqli_prepare($link, $sql_update_vote);
            mysqli_stmt_bind_param($stmt_update, "s", $option);
            mysqli_stmt_execute($stmt_update);
            if (mysqli_stmt_affected_rows($stmt_update) === 0) { mysqli_stmt_close($stmt_update); throw new Exception('অবৈধ ভোটিং অপশন।');}
            mysqli_stmt_close($stmt_update);

            // 2. Insert fingerprint
            $sql_insert_fingerprint = "INSERT INTO voted_users (fingerprint) VALUES (?)";
            $stmt_insert = mysqli_prepare($link, $sql_insert_fingerprint);
            mysqli_stmt_bind_param($stmt_insert, "s", $fingerprint);
            if (!mysqli_stmt_execute($stmt_insert)) {
                if (mysqli_errno($link) === 1062) {
                    mysqli_stmt_close($stmt_insert); mysqli_rollback($link);
                    $response['voted'] = true; $response['success'] = false;
                    $response['message'] = 'আপনি ইতিমধ্যেই ভোট দিয়েছেন (সমসাময়িক অনুরোধ সনাক্ত)।';
                    // Re-fetch all data
                    $current_results_info = get_vote_results($link);
                    $response['results'] = $current_results_info['data']; $response['total_votes'] = $current_results_info['total'];
                    $response['daily_summary'] = get_daily_vote_summary_for_month($link, (int)date('Y'), (int)date('m'));
                    $response['monthly_summary'] = get_monthly_vote_summary($link, (int)date('Y'));
                    send_json_response($response, 200);
                }
                throw new Exception('ফিঙ্গারপ্রিন্ট সংরক্ষণ করতে সমস্যা: ' . mysqli_stmt_error($stmt_insert));
            }
            mysqli_stmt_close($stmt_insert);

            // 3. Update daily vote count
            $today = date("Y-m-d");
            $sql_update_daily_vote = "INSERT INTO vote_log (vote_date, option_name, vote_count) VALUES (?, ?, 1)
                                      ON DUPLICATE KEY UPDATE vote_count = vote_count + 1";
            $stmt_daily = mysqli_prepare($link, $sql_update_daily_vote);
            mysqli_stmt_bind_param($stmt_daily, "ss", $today, $option);
            mysqli_stmt_execute($stmt_daily);
            mysqli_stmt_close($stmt_daily);

            mysqli_commit($link);
            $vote_recorded_successfully = true;
        } catch (Exception $e) {
            mysqli_rollback($link); error_log("Vote processing error: " . $e->getMessage());
            $response['success'] = false; $response['message'] = $e->getMessage();
        }

        if ($vote_recorded_successfully) {
            $response['success'] = true; $response['message'] = 'ভোট সফলভাবে রেকর্ড করা হয়েছে!'; $response['voted'] = true;
            // Re-fetch all results including summaries
            $updated_results_info = get_vote_results($link);
            if ($updated_results_info['error'] === null) {
                $response['results'] = $updated_results_info['data'];
                $response['total_votes'] = $updated_results_info['total'];
            } else { $response['message'] .= ' তবে, আপডেটেড মোট ফলাফল আনতে সমস্যা হয়েছে।';}
            $response['daily_summary'] = get_daily_vote_summary_for_month($link, (int)date('Y'), (int)date('m'));
            $response['monthly_summary'] = get_monthly_vote_summary($link, (int)date('Y'));
        }
    }
} else if (empty($action) || $action === 'get_results') {
    // Initial load or get_results: data already fetched
} else {
    $response['success'] = false; $response['message'] = 'অজানা অ্যাকশন: ' . htmlspecialchars($action);
}

mysqli_close($link);
$final_status_code = 200; // Default
if (!$response['success'] && $action === 'vote' && (strpos($response['message'], 'অবৈধ অপশন') !== false || strpos($response['message'], 'ডিভাইস ফিঙ্গারপ্রিন্ট আবশ্যক') !== false) ){
    $final_status_code = 400;
}
send_json_response($response, $final_status_code);
?>