<?php
require __DIR__ . '/bootstrap.php';

use App\Core\Auth;
use App\Core\Database;
use App\Core\Response;

$user = Auth::requireUser();
if (($user['role_name'] ?? '') !== 'member') {
    Response::error('Member access only.', 403);
}

$pdo = Database::connection();
$input = request_input();
$action = (string)($input['action'] ?? 'home');
$userId = (int)$user['id'];

function pyrk_mobile_profile(PDO $pdo, int $userId): array
{
    $stmt = $pdo->prepare('SELECT u.id, u.full_name, u.email, u.mobile, u.profile_photo_path, u.can_edit_own_profile, u.qr_token, u.status, u.created_at, u.updated_at,
        mp.date_of_birth, mp.gender, mp.emergency_contact_name, mp.emergency_contact_mobile, mp.medical_conditions, mp.photo_consent,
        COALESCE(mp.total_walks,0) AS total_walks, COALESCE(mp.total_kilometers,0) AS total_kilometers, COALESCE(mp.loyalty_points,0) AS loyalty_points,
        TIMESTAMPDIFF(YEAR, mp.date_of_birth, CURDATE()) AS age
        FROM users u LEFT JOIN member_profiles mp ON mp.user_id = u.id WHERE u.id = ? LIMIT 1');
    $stmt->execute([$userId]);
    return $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
}

function pyrk_mobile_unread_count(PDO $pdo, int $userId): int
{
    try {
        $stmt = $pdo->prepare('SELECT COUNT(*) FROM notifications WHERE user_id = ? AND channel = "in_app" AND read_at IS NULL');
        $stmt->execute([$userId]);
        return (int)$stmt->fetchColumn();
    } catch (Throwable) {
        return 0;
    }
}

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    Response::error('Unsupported request method.', 405);
}

if ($action === 'unread_count') {
    Response::ok(['unread_count' => pyrk_mobile_unread_count($pdo, $userId)]);
}

if ($action === 'home') {
    $profile = pyrk_mobile_profile($pdo, $userId);
    if (!$profile) Response::error('Member profile not found.', 404);

    $next = $pdo->prepare('SELECT w.id, w.title, w.walk_date, w.start_time, w.expected_finish_time, w.status, w.access_type,
        r.route_name, r.total_km, wr.registration_status,
        a.status AS attendance_status, a.check_in_time, a.finish_time
        FROM walk_registrations wr
        JOIN walks w ON w.id = wr.walk_id
        LEFT JOIN routes r ON r.id = w.route_id
        LEFT JOIN attendance a ON a.walk_id = w.id AND a.user_id = wr.user_id
        WHERE wr.user_id = ? AND wr.registration_status IN ("registered","approved")
          AND w.walk_date >= CURDATE()
          AND LOWER(TRIM(COALESCE(w.status,""))) NOT IN ("closed","completed","archived")
        ORDER BY w.walk_date ASC, w.start_time ASC LIMIT 1');
    $next->execute([$userId]);

    $badges = $pdo->prepare('SELECT COUNT(*) FROM user_badges WHERE user_id = ?');
    $badges->execute([$userId]);

    Response::ok([
        'profile' => $profile,
        'next_walk' => $next->fetch(PDO::FETCH_ASSOC) ?: null,
        'badges_count' => (int)$badges->fetchColumn(),
        'unread_count' => pyrk_mobile_unread_count($pdo, $userId),
    ]);
}

if ($action === 'profile') {
    $profile = pyrk_mobile_profile($pdo, $userId);
    if (!$profile) Response::error('Member profile not found.', 404);

    $groups = $pdo->prepare('SELECT g.id, g.group_name, g.description FROM member_group_members mgm JOIN member_groups g ON g.id = mgm.group_id WHERE mgm.user_id = ? AND g.status = "active" ORDER BY g.group_name');
    $groups->execute([$userId]);

    $waivers = $pdo->prepare('SELECT ws.id, ws.signed_at, w.id AS walk_id, w.title AS walk_title, w.walk_date, wt.title AS waiver_title, wt.version AS waiver_version
        FROM waiver_signatures ws JOIN walks w ON w.id = ws.walk_id LEFT JOIN waiver_templates wt ON wt.id = ws.waiver_template_id
        WHERE ws.user_id = ? AND ws.accepted_terms = 1 ORDER BY ws.signed_at DESC, ws.id DESC LIMIT 40');
    $waivers->execute([$userId]);

    $photos = $pdo->prepare('SELECT wp.id, wp.walk_id, wp.title, wp.caption, wp.file_path, wp.thumbnail_path, wp.status, wp.votes_count, wp.uploaded_at,
        w.title AS walk_title, w.walk_date
        FROM walk_photos wp JOIN walks w ON w.id = wp.walk_id
        WHERE wp.user_id = ? ORDER BY wp.uploaded_at DESC, wp.id DESC LIMIT 60');
    $photos->execute([$userId]);

    $badges = $pdo->prepare('SELECT b.badge_name, b.description, b.badge_icon, ub.earned_at FROM user_badges ub JOIN badges b ON b.id = ub.badge_id WHERE ub.user_id = ? ORDER BY ub.earned_at DESC');
    $badges->execute([$userId]);

    Response::ok([
        'profile' => $profile,
        'groups' => $groups->fetchAll(PDO::FETCH_ASSOC),
        'waivers' => $waivers->fetchAll(PDO::FETCH_ASSOC),
        'photos' => $photos->fetchAll(PDO::FETCH_ASSOC),
        'badges' => $badges->fetchAll(PDO::FETCH_ASSOC),
        'unread_count' => pyrk_mobile_unread_count($pdo, $userId),
    ]);
}

if ($action === 'history') {
    $history = $pdo->prepare('SELECT w.id AS walk_id, w.title, w.walk_date, w.start_time, r.route_name,
        a.status, a.verified_km, a.check_in_time, a.finish_time
        FROM attendance a JOIN walks w ON w.id = a.walk_id LEFT JOIN routes r ON r.id = w.route_id
        WHERE a.user_id = ? ORDER BY w.walk_date DESC, COALESCE(a.finish_time,a.check_in_time) DESC LIMIT 120');
    $history->execute([$userId]);

    Response::ok([
        'history' => $history->fetchAll(PDO::FETCH_ASSOC),
        'unread_count' => pyrk_mobile_unread_count($pdo, $userId),
    ]);
}

if ($action === 'activity') {
    $profile = pyrk_mobile_profile($pdo, $userId);
    if (!$profile) Response::error('Member profile not found.', 404);

    $transactions = $pdo->prepare('SELECT lt.id, lt.points, lt.transaction_type, lt.description, lt.created_at, lt.walk_id, w.title AS walk_title
        FROM loyalty_transactions lt LEFT JOIN walks w ON w.id = lt.walk_id
        WHERE lt.user_id = ? ORDER BY lt.created_at DESC, lt.id DESC LIMIT 200');
    $transactions->execute([$userId]);
    $rows = $transactions->fetchAll(PDO::FETCH_ASSOC);

    $gained = 0;
    $used = 0;
    foreach ($rows as $row) {
        $points = (int)($row['points'] ?? 0);
        if ($points >= 0) $gained += $points;
        else $used += abs($points);
    }

    Response::ok([
        'current_points' => (int)($profile['loyalty_points'] ?? 0),
        'gained_points' => $gained,
        'used_points' => $used,
        'transactions' => $rows,
        'unread_count' => pyrk_mobile_unread_count($pdo, $userId),
    ]);
}

Response::error('Unsupported mobile member action.', 404);
