<?php
require_once '../config.php';
require_once '../middleware.php';

// DEBUG VERSION - No authentication required for testing
header('Content-Type: application/json');

$method = $_SERVER['REQUEST_METHOD'];

if ($method !== 'POST') {
    sendResponse(405, 'Method not allowed');
}

// Get the encrypted payload
$encrypted_payload = file_get_contents('php://input');
if (empty($encrypted_payload)) {
    sendResponse(400, 'Empty request body');
}

// Decrypt the payload
$data = decryptRequestPayload($encrypted_payload);
if (!$data) {
    sendResponse(400, 'Invalid request body');
}

$user_id = $data['user_id'] ?? 0;

if ($user_id <= 0) {
    sendResponse(400, 'Invalid user_id');
}

// Skip authentication for debug
// authenticateSession($user_id, $device_id, $session_token);
// rateLimit($user_id);
// $new_session_token = generateNewSessionToken($user_id, $device_id);

$conn = getDbConnection();

// Get daily checkin coins from app settings
$coins_reward = 50; // Default value
try {
    // First check if the column exists
    $stmt = $conn->prepare("SHOW COLUMNS FROM app_settings LIKE 'daily_checkin_coins'");
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        // Column exists, get the value
        $stmt = $conn->prepare("SELECT daily_checkin_coins FROM app_settings WHERE id = 1");
        $stmt->execute();
        $result = $stmt->get_result();
        $settings = $result->fetch_assoc();
        $stmt->close();
        
        if ($settings && isset($settings['daily_checkin_coins'])) {
            $coins_reward = $settings['daily_checkin_coins'];
        }
    } else {
        // Column doesn't exist, use default value
        $coins_reward = 50;
    }
} catch (Exception $e) {
    // If there's any error, use default value
    $coins_reward = 50;
}

// Check if daily_checkins table exists
$table_exists = false;
try {
    $stmt = $conn->prepare("SHOW TABLES LIKE 'daily_checkins'");
    $stmt->execute();
    $result = $stmt->get_result();
    $table_exists = $result->num_rows > 0;
} catch (Exception $e) {
    $table_exists = false;
}

if (!$table_exists) {
    // Table doesn't exist, return default values
    sendResponse(200, 'Checkin status fetched (DEBUG - No daily_checkins table)', [
        'can_claim' => true,
        'coins_reward' => $coins_reward,
        'last_claimed' => null,
        'next_available' => null,
        'streak_days' => 0,
        'debug_info' => [
            'table_exists' => false,
            'user_id' => $user_id,
            'coins_reward' => $coins_reward
        ]
    ]);
}

// Check if user has already claimed today
$today = date('Y-m-d');
$can_claim = true;
$last_claimed = null;
$next_available = null;
$streak_days = 0;

try {
    $stmt = $conn->prepare("SELECT claimed_at FROM daily_checkins WHERE user_id = ? AND DATE(claimed_at) = ? ORDER BY claimed_at DESC LIMIT 1");
    $stmt->bind_param("is", $user_id, $today);
    $stmt->execute();
    $result = $stmt->get_result();
    $today_checkin = $result->fetch_assoc();
    $stmt->close();

    $can_claim = $result->num_rows === 0;

    // Get last claimed date
    $stmt = $conn->prepare("SELECT claimed_at FROM daily_checkins WHERE user_id = ? ORDER BY claimed_at DESC LIMIT 1");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $last_checkin = $result->fetch_assoc();
    $stmt->close();

    $last_claimed = $last_checkin ? $last_checkin['claimed_at'] : null;

    // Calculate next available time
    if ($last_claimed) {
        $next_available = date('Y-m-d H:i:s', strtotime($last_claimed . ' +1 day'));
    }

    // Calculate streak days (consecutive days) - Simplified version for older MySQL
    $stmt = $conn->prepare("
        SELECT COUNT(*) as streak_days
        FROM (
            SELECT claimed_at, DATE(claimed_at) as claim_date
            FROM daily_checkins 
            WHERE user_id = ?
            ORDER BY claimed_at DESC
        ) t1
        WHERE claim_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
        AND claim_date <= CURDATE()
        AND claim_date = DATE_SUB(CURDATE(), INTERVAL (
            SELECT COUNT(*) 
            FROM daily_checkins dc2 
            WHERE dc2.user_id = ? 
            AND dc2.claimed_at > t1.claimed_at
        ) DAY)
    ");
    $stmt->bind_param("ii", $user_id, $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $streak_data = $result->fetch_assoc();
    $stmt->close();

    $streak_days = $streak_data ? $streak_data['streak_days'] : 0;

} catch (Exception $e) {
    // If there's any database error, return default values
    $can_claim = true;
    $last_claimed = null;
    $next_available = null;
    $streak_days = 0;
}

$conn->close();

sendResponse(200, 'Checkin status fetched (DEBUG)', [
    'can_claim' => $can_claim,
    'coins_reward' => $coins_reward,
    'last_claimed' => $last_claimed,
    'next_available' => $next_available,
    'streak_days' => $streak_days,
    'debug_info' => [
        'table_exists' => $table_exists,
        'user_id' => $user_id,
        'today' => $today,
        'coins_reward' => $coins_reward
    ]
]);
?> 