<?php
require_once 'config.php';

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

$action = $_REQUEST['action'] ?? '';

switch ($action) {
    case 'complete_habit':
        completeHabit();
        break;
    case 'complete_bounty':
        completeBounty();
        break;
    case 'get_item':
        getItem();
        break;
    case 'get_day_details':
        getDayDetails();
        break;
    default:
        echo json_encode(['success' => false, 'message' => 'Unknown action']);
}

function completeHabit() {
    $habitId = intval($_POST['habit_id'] ?? 0);
    if (!$habitId) {
        echo json_encode(['success' => false, 'message' => 'Invalid habit ID']);
        return;
    }
    
    $db = getDB();
    
    // Get champion for today
    $dayOfWeek = date('w');
    $stmt = $db->prepare("SELECT id FROM champions WHERE day_index = ?");
    $stmt->execute([$dayOfWeek]);
    $champion = $stmt->fetch();
    
    if (!$champion) {
        echo json_encode(['success' => false, 'message' => 'Champion not found']);
        return;
    }
    
    // Record completion
    $stmt = $db->prepare("INSERT INTO completions (habit_id, completed_date, champion_day) VALUES (?, CURDATE(), ?)");
    $stmt->execute([$habitId, $dayOfWeek]);
    
    // Get habit XP
    $stmt = $db->prepare("SELECT xp_reward FROM habits WHERE id = ?");
    $stmt->execute([$habitId]);
    $habit = $stmt->fetch();
    
    // Update champion XP
    $stmt = $db->prepare("UPDATE champion_progress SET xp = xp + ? WHERE champion_id = ?");
    $stmt->execute([$habit['xp_reward'], $champion['id']]);
    
    // Check for level up
    $stmt = $db->prepare("SELECT xp, level FROM champion_progress WHERE champion_id = ?");
    $stmt->execute([$champion['id']]);
    $progress = $stmt->fetch();
    
    $maxXP = $progress['level'] * 100;
    $leveledUp = false;
    
    if ($progress['xp'] >= $maxXP) {
        $newLevel = $progress['level'] + 1;
        $newXP = $progress['xp'] - $maxXP;
        $stmt = $db->prepare("UPDATE champion_progress SET level = ?, xp = ? WHERE champion_id = ?");
        $stmt->execute([$newLevel, $newXP, $champion['id']]);
        $leveledUp = true;
    }
    
    echo json_encode(['success' => true, 'leveled_up' => $leveledUp]);
}

function completeBounty() {
    $bountyId = intval($_POST['bounty_id'] ?? 0);
    if (!$bountyId) {
        echo json_encode(['success' => false, 'message' => 'Invalid bounty ID']);
        return;
    }
    
    $db = getDB();
    
    // Get champion for today
    $dayOfWeek = date('w');
    $stmt = $db->prepare("SELECT id FROM champions WHERE day_index = ?");
    $stmt->execute([$dayOfWeek]);
    $champion = $stmt->fetch();
    
    // Get bounty XP
    $stmt = $db->prepare("SELECT xp_reward FROM bounties WHERE id = ?");
    $stmt->execute([$bountyId]);
    $bounty = $stmt->fetch();
    
    // Update bounty
    $stmt = $db->prepare("UPDATE bounties SET completed = TRUE, completed_date = CURDATE() WHERE id = ?");
    $stmt->execute([$bountyId]);
    
    // Update champion XP
    $stmt = $db->prepare("UPDATE champion_progress SET xp = xp + ? WHERE champion_id = ?");
    $stmt->execute([$bounty['xp_reward'], $champion['id']]);
    
    echo json_encode(['success' => true]);
}

function getItem() {
    $itemId = intval($_GET['item_id'] ?? 0);
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM items WHERE id = ?");
    $stmt->execute([$itemId]);
    $item = $stmt->fetch();
    
    if ($item) {
        echo json_encode(['success' => true, 'data' => $item]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Item not found']);
    }
}

function getDayDetails() {
    $date = $_GET['date'] ?? '';
    $db = getDB();
    
    // Get champion for that day
    $dayOfWeek = date('w', strtotime($date));
    $stmt = $db->prepare("SELECT * FROM champions WHERE day_index = ?");
    $stmt->execute([$dayOfWeek]);
    $champion = $stmt->fetch();
    
    // Get completions for that date
    $stmt = $db->prepare("
        SELECT h.name, h.image_path 
        FROM completions c 
        JOIN habits h ON c.habit_id = h.id 
        WHERE c.completed_date = ?
    ");
    $stmt->execute([$date]);
    $completions = $stmt->fetchAll();
    
    echo json_encode([
        'success' => true,
        'champion' => $champion,
        'completions' => $completions
    ]);
}
?>


