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

date_default_timezone_set('Asia/Kolkata');

### API Blueprint: /user/checkin_status
# POST /user/checkin_status
# Description: Checks daily checkin status for the user.
# Headers:
#   - Device-ID: <device_id> (required)
#   - Session-Token: <session_token> (required)
# Request Body:
#   - user_id: integer (required)
# Response:
#   - 200: Success
#     {
#       "status": 200,
#       "message": "Checkin status fetched",
#       "data": {
#         "can_claim": true,
#         "coins_reward": 50,
#         "last_claimed": "2025-01-15 10:30:00",
#         "next_available": "2025-01-16 10:30:00",
#         "streak_days": 3
#       },
#       "new_session_token": "new_strong_session_token_64_chars"
#     }
#   - 400: Invalid user_id
#   - 401: Unauthorized
#   - 429: Too many requests
#   - 500: Database connection failed

header('Content-Type: application/json');

$device_id = $_SERVER['HTTP_DEVICE_ID'] ?? '';
$session_token = $_SERVER['HTTP_SESSION_TOKEN'] ?? '';

$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');
}

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', [
        'can_claim' => true,
        'coins_reward' => $coins_reward,
        'last_claimed' => null,
        'next_available' => null,
        'streak_days' => 0
    ], $new_session_token);
}

// 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 00:00:00', strtotime($today . ' +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', [
    'can_claim' => $can_claim,
    'coins_reward' => $coins_reward,
    'last_claimed' => $last_claimed,
    'next_available' => $next_available,
    'streak_days' => $streak_days
], $new_session_token);
?> 