<?php
/**
 * mission_api.php
 * action=list  → সব Mission, User-এর Real-Progress-সহ দেয়
 * action=claim → নির্দিষ্ট Mission Claim করে, Balance-এ Bonus যোগ করে
 */
error_reporting(E_ALL);
ini_set('display_errors', 0);
header('Content-Type: application/json; charset=utf-8');
set_error_handler(function($errno, $errstr, $errfile, $errline) {
    echo json_encode(['code' => 1, 'msg' => "PHP-Error: $errstr (Line: $errline)"]);
    exit;
});
register_shutdown_function(function() {
    $error = error_get_last();
    if ($error !== null && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        echo json_encode(['code' => 1, 'msg' => "Fatal-Error: " . $error['message']]);
    }
});

include __DIR__ . "/deepanshu/conn.php";
include __DIR__ . "/deepanshu/functions2.php";

// ✅ নতুন যোগ — Bengali Text সঠিকভাবে আসার জন্য, Connection-এর
// Charset Explicitly utf8mb4 করা হচ্ছে (আগে "?" দেখাচ্ছিল)
if (isset($conn)) { $conn->set_charset("utf8mb4"); }

$bearer = explode(" ", $_SERVER['HTTP_AUTHORIZATION'] ?? '');
$author = $bearer[1] ?? '';
$is_jwt_valid = is_jwt_valid($author);
$data_auth = json_decode($is_jwt_valid, true);

if (($data_auth['status'] ?? '') !== 'Success') {
    echo json_encode(['code' => 1, 'msg' => 'Login করা নেই']);
    exit;
}

$userId = $data_auth['payload']['id'];
$action = $_GET['action'] ?? '';

$tableCheck = $conn->query("SHOW TABLES LIKE 'mission_definitions'");
if (!$tableCheck || $tableCheck->num_rows === 0) {
    echo json_encode(['code' => 1, 'msg' => 'Database-এ Mission-Table পাওয়া যায়নি — mission_schema.sql Run করতে হবে']);
    exit;
}

// ✅ আজকের Date আর এই সপ্তাহের Week-Key বের করা
$todayKey = date('Y-m-d');
$weekKey = date('Y-W');

function getPeriodKey($category, $todayKey, $weekKey) {
    return $category === 'weekly' ? $weekKey : $todayKey;
}

function getPeriodStart($category) {
    if ($category === 'weekly') {
        $monday = new DateTime();
        $monday->modify('monday this week');
        return $monday->format('Y-m-d 00:00:00');
    }
    return date('Y-m-d 00:00:00');
}

// ✅ Real Progress Calculate করা — Mission-Type অনুযায়ী
function getProgress($conn, $userId, $missionType, $periodStart) {
    switch ($missionType) {
        case 'deposit':
            $stmt = $conn->prepare("SELECT SUM(motta) as total FROM thevani WHERE balakedara = ? AND sthiti = 1 AND dinankavannuracisi >= ?");
            $stmt->bind_param("ss", $userId, $periodStart);
            $stmt->execute();
            return (float)($stmt->get_result()->fetch_assoc()['total'] ?? 0);

        case 'betting':
            $stmt = $conn->prepare("SELECT SUM(bet_amount) as total FROM game_bet_logs WHERE user_id = ? AND created_at >= ?");
            $stmt->bind_param("ss", $userId, $periodStart);
            $stmt->execute();
            return (float)($stmt->get_result()->fetch_assoc()['total'] ?? 0);

        case 'game_count':
            $stmt = $conn->prepare("SELECT COUNT(DISTINCT game_code) as total FROM game_bet_logs WHERE user_id = ? AND created_at >= ?");
            $stmt->bind_param("ss", $userId, $periodStart);
            $stmt->execute();
            return (float)($stmt->get_result()->fetch_assoc()['total'] ?? 0);

        case 'login':
            // ✅ Login মানেই এই Mission-Page Access করা = আজ Login করেছে
            return 1;

        default:
            return 0;
    }
}

if ($action === 'list') {
    $missionsResult = $conn->query("SELECT * FROM mission_definitions WHERE is_active = 1 ORDER BY category, sort_order");
    $missions = [];

    while ($m = $missionsResult->fetch_assoc()) {
        $periodKey = getPeriodKey($m['category'], $todayKey, $weekKey);
        $periodStart = getPeriodStart($m['category']);
        $progress = getProgress($conn, $userId, $m['mission_type'], $periodStart);

        // ✅ আগে Claim করা হয়েছে কিনা Check
        $claimCheckStmt = $conn->prepare("SELECT id FROM mission_claims WHERE user_id = ? AND mission_id = ? AND period_key = ?");
        $claimCheckStmt->bind_param("sis", $userId, $m['id'], $periodKey);
        $claimCheckStmt->execute();
        $alreadyClaimed = $claimCheckStmt->get_result()->num_rows > 0;

        $target = (float)$m['target_value'];
        $currentProgress = min($progress, $target);
        $isComplete = $progress >= $target;

        $missions[] = [
            'id' => $m['id'],
            'category' => $m['category'],
            'title' => $m['title'],
            'icon' => $m['icon'],
            'target' => $target,
            'progress' => round($currentProgress, 2),
            'reward' => (float)$m['reward_amount'],
            'is_complete' => $isComplete,
            'already_claimed' => $alreadyClaimed,
            'can_claim' => $isComplete && !$alreadyClaimed,
            'percent' => $target > 0 ? min(100, round(($currentProgress / $target) * 100)) : 0
        ];
    }

    echo json_encode(['code' => 0, 'missions' => $missions]);
    exit;
}

if ($action === 'claim') {
    $input = json_decode(file_get_contents('php://input'), true);
    $missionId = (int)($input['mission_id'] ?? 0);

    $missionStmt = $conn->prepare("SELECT * FROM mission_definitions WHERE id = ? AND is_active = 1");
    $missionStmt->bind_param("i", $missionId);
    $missionStmt->execute();
    $missionResult = $missionStmt->get_result();

    if ($missionResult->num_rows === 0) {
        echo json_encode(['code' => 1, 'msg' => 'এই Mission পাওয়া যায়নি']);
        exit;
    }

    $m = $missionResult->fetch_assoc();
    $periodKey = getPeriodKey($m['category'], $todayKey, $weekKey);
    $periodStart = getPeriodStart($m['category']);

    // ✅ Backend-Level Re-Verify — Progress সত্যিই পূরণ হয়েছে কিনা
    $progress = getProgress($conn, $userId, $m['mission_type'], $periodStart);
    if ($progress < (float)$m['target_value']) {
        echo json_encode(['code' => 1, 'msg' => 'এখনো এই Mission সম্পূর্ণ হয়নি']);
        exit;
    }

    // ✅ Duplicate-Claim Check
    $claimCheckStmt = $conn->prepare("SELECT id FROM mission_claims WHERE user_id = ? AND mission_id = ? AND period_key = ?");
    $claimCheckStmt->bind_param("sis", $userId, $missionId, $periodKey);
    $claimCheckStmt->execute();
    if ($claimCheckStmt->get_result()->num_rows > 0) {
        echo json_encode(['code' => 1, 'msg' => 'তুমি আগেই এই Mission-এর Reward নিয়ে নিয়েছো']);
        exit;
    }

    $conn->begin_transaction();
    try {
        $rewardAmount = (float)$m['reward_amount'];

        $updateStmt = $conn->prepare("UPDATE shonu_kaichila SET motta = motta + ? WHERE balakedara = ?");
        $updateStmt->bind_param("ds", $rewardAmount, $userId);
        $updateStmt->execute();

        $recordStmt = $conn->prepare("INSERT INTO mission_claims (user_id, mission_id, period_key, reward_amount) VALUES (?, ?, ?, ?)");
        $recordStmt->bind_param("sisd", $userId, $missionId, $periodKey, $rewardAmount);
        $recordStmt->execute();

        $conn->commit();
        echo json_encode(['code' => 0, 'msg' => "অভিনন্দন! ৳$rewardAmount তোমার Balance-এ যোগ হয়েছে", 'reward' => $rewardAmount]);
    } catch (Throwable $e) {
        $conn->rollback();
        echo json_encode(['code' => 1, 'msg' => 'একটা সমস্যা হয়েছে, আবার চেষ্টা করো']);
    }
    exit;
}

echo json_encode(['code' => 1, 'msg' => 'Invalid Action']);
