<?php
require_once 'includes/auth.php';
require_once 'includes/header.php';
$userId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
?>

<div x-data="userDetail(<?= $userId ?>)" class="space-y-6">

    <!-- Header / Actions -->
    <div class="flex items-center justify-between">
        <div class="flex items-center gap-4">
            <a href="users.php" class="text-gray-400 hover:text-white"><i class="fas fa-arrow-left"></i></a>
            <h3 class="text-3xl font-medium text-gray-100">User Profile</h3>
        </div>
        <div class="flex gap-3">
            <button @click="banUser()" class="bg-red-500/10 hover:bg-red-500 text-red-500 hover:text-white px-4 py-2 rounded-lg border border-red-500/30 transition-colors">
                <i class="fas fa-ban mr-2"></i> Ban User
            </button>
            <button class="bg-primary hover:bg-indigo-600 text-white px-4 py-2 rounded-lg shadow-lg shadow-primary/30 transition-colors">
                <i class="fas fa-envelope mr-2"></i> Message
            </button>
        </div>
    </div>

    <div x-show="loading" class="text-center py-12">
        <i class="fas fa-circle-notch fa-spin fa-2x text-gray-500"></i>
    </div>

    <div x-show="!loading && user" class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        
        <!-- Main Profile Card -->
        <div class="lg:col-span-1 space-y-6">
            <div class="bg-surface rounded-xl p-6 border border-gray-700 text-center relative overflow-hidden">
                <div class="absolute top-0 left-0 w-full h-24 bg-gradient-to-r from-primary/20 to-secondary/20"></div>
                
                <div class="relative mt-8 mb-4">
                    <img :src="user.avatar_url || 'https://ui-avatars.com/api/?name='+user.username" class="w-24 h-24 rounded-full border-4 border-surface mx-auto object-cover shadow-lg">
                    <div x-show="user.status === 'online'" class="absolute bottom-1 right-[35%] w-4 h-4 bg-green-500 rounded-full border-2 border-surface"></div>
                </div>
                
                <h2 class="text-2xl font-bold text-white" x-text="user.display_name"></h2>
                <div class="text-gray-400 mb-4" x-text="'@'+user.username"></div>
                
                <div class="flex justify-center gap-2 mb-6">
                    <span x-show="user.is_plus_subscriber == 1" class="px-3 py-1 rounded-full bg-indigo-500/20 text-indigo-400 text-xs font-bold border border-indigo-500/30">PLUS</span>
                    <span x-show="isBoosted(user)" class="px-3 py-1 rounded-full bg-pink-500/20 text-pink-500 text-xs font-bold border border-pink-500/30">DIAMOND VIP</span>
                    <span x-show="user.is_seed == 1" class="px-3 py-1 rounded-full bg-secondary/20 text-secondary text-xs font-bold border border-secondary/30">BOT</span>
                    <span x-show="user.is_verified == 1" class="px-3 py-1 rounded-full bg-blue-500/20 text-blue-500 text-xs font-bold border border-blue-500/30">VERIFIED</span>
                </div>

                <div class="grid grid-cols-2 gap-4 border-t border-gray-700 pt-6">
                    <div class="text-center">
                        <div class="text-xs text-gray-500 uppercase">Joined</div>
                        <div class="text-sm text-gray-300 font-mono" x-text="formatDate(user.created_at)"></div>
                    </div>
                    <div class="text-center">
                        <div class="text-xs text-gray-500 uppercase">Last Seen</div>
                        <div class="text-sm text-gray-300 font-mono" x-text="formatDate(user.last_login_at)"></div>
                    </div>
                </div>
            </div>

            <!-- Device Info -->
            <div class="bg-surface rounded-xl p-6 border border-gray-700">
                <h4 class="text-sm font-bold text-gray-400 uppercase mb-4">System Info</h4>
                <div class="space-y-3 text-sm">
                    <div class="flex justify-between">
                        <span class="text-gray-500">Reg. IP</span>
                        <span class="text-gray-300 font-mono" x-text="user.registration_ip || '-'"></span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-500">Last IP</span>
                        <span class="text-gray-300 font-mono" x-text="user.last_ip || '-'"></span>
                    </div>
                    <div class="border-t border-gray-700 my-2 pt-2">
                        <div class="text-gray-500 mb-1 font-bold">Device Details</div>
                        <template x-if="user.device_info">
                            <div class="space-y-1 text-xs text-gray-400 font-mono">
                                <div x-show="user.device_info.platform">Platform: <span class="text-gray-300" x-text="user.device_info.platform.toUpperCase()"></span></div>
                                <div x-show="user.device_info.model">Model: <span class="text-gray-300" x-text="user.device_info.model"></span></div>
                                <div x-show="user.device_info.version">OS: <span class="text-gray-300" x-text="user.device_info.version"></span></div>
                                <div x-show="user.device_info.manufacturer">Maker: <span class="text-gray-300" x-text="user.device_info.manufacturer"></span></div>
                            </div>
                        </template>
                        <template x-if="!user.device_info">
                            <div class="text-xs text-gray-600 italic">No device data captured</div>
                        </template>
                    </div>
                </div>
            </div>
        </div>

        <!-- Right Column -->
        <div class="lg:col-span-2 space-y-6">
            
            <!-- Stats Grid -->
            <div class="grid grid-cols-3 gap-4">
                <div class="bg-surface p-4 rounded-xl border border-gray-700">
                    <div class="text-gray-500 text-xs uppercase mb-1">Conversations</div>
                    <div class="text-2xl font-bold text-white" x-text="user.stats?.conversations || 0"></div>
                </div>
                <div class="bg-surface p-4 rounded-xl border border-gray-700">
                    <div class="text-gray-500 text-xs uppercase mb-1">Messages</div>
                    <div class="text-2xl font-bold text-white" x-text="user.stats?.messages_sent || 0"></div>
                </div>
                <div class="bg-surface p-4 rounded-xl border border-gray-700">
                    <div class="text-gray-500 text-xs uppercase mb-1">Reports</div>
                    <div class="text-2xl font-bold text-red-400" x-text="user.stats?.reports_received || 0"></div>
                </div>
            </div>

            <!-- PLUS Membership -->
            <div class="bg-surface rounded-xl p-6 border border-gray-700">
                <h4 class="text-sm font-bold text-gray-400 uppercase mb-4">PLUS Membership</h4>
                <div class="space-y-4">
                    <div class="flex items-center justify-between">
                        <label class="text-sm text-gray-300">Active PLUS Subscriber</label>
                        <input type="checkbox" x-model="user.is_plus_subscriber" :true-value="1" :false-value="0" class="w-5 h-5 accent-indigo-500">
                    </div>
                    <div>
                        <label class="text-xs text-gray-500 uppercase block mb-1">PLUS Expiration</label>
                        <input type="datetime-local" x-model="user.plus_expires_at_formatted" class="w-full bg-dark border border-gray-600 rounded px-3 py-2 text-sm text-gray-300">
                    </div>
                    <div>
                        <label class="text-xs text-gray-500 uppercase block mb-1">Active Frame</label>
                        <select x-model="user.active_frame" class="w-full bg-dark border border-gray-600 rounded px-3 py-2 text-sm text-gray-300">
                            <option value="">None</option>
                            <option value="silver">Silver</option>
                            <option value="holiday">Holiday</option>
                            <option value="love">Love</option>
                            <option value="diamond">Diamond</option>
                            <option value="angel_wings">Angel Wings</option>
                            <option value="cactus">Cactus</option>
                            <option value="kings_crown">King's Crown</option>
                            <option value="queens_crown">Queen's Crown</option>
                        </select>
                    </div>
                    <button @click="updateSubscription()" class="w-full bg-primary hover:bg-indigo-600 text-white font-bold py-2 px-4 rounded transition-colors shadow-lg shadow-primary/20 mt-2">
                        Update Subscription
                    </button>
                </div>
            </div>

            <!-- Öne Çıkart (Diamond VIP) -->
            <div class="bg-surface rounded-xl p-6 border border-gray-700">
                <h4 class="text-sm font-bold text-gray-400 uppercase mb-4">Öne Çıkart (Diamond VIP)</h4>
                <div class="grid grid-cols-3 gap-2">
                    <button @click="addBoost(15)" class="bg-dark hover:bg-pink-500/20 border border-gray-600 rounded py-2 text-xs font-bold transition-colors">15m</button>
                    <button @click="addBoost(30)" class="bg-dark hover:bg-pink-500/20 border border-gray-600 rounded py-2 text-xs font-bold transition-colors">30m</button>
                    <button @click="addBoost(45)" class="bg-dark hover:bg-pink-500/20 border border-gray-600 rounded py-2 text-xs font-bold transition-colors">45m</button>
                    <button @click="addBoost(60)" class="bg-dark hover:bg-pink-500/20 border border-gray-600 rounded py-2 text-xs font-bold transition-colors">1h</button>
                    <button @click="addBoost(120)" class="bg-dark hover:bg-pink-500/20 border border-gray-600 rounded py-2 text-xs font-bold transition-colors">2h</button>
                    <button @click="addBoost(180)" class="bg-dark hover:bg-pink-500/20 border border-gray-600 rounded py-2 text-xs font-bold transition-colors">3h</button>
                </div>
                <div x-show="user.boosted_until" class="mt-4 p-3 bg-pink-500/10 rounded border border-pink-500/20 text-center">
                    <div class="text-[10px] text-pink-500 font-bold uppercase">Diamond VIP Active Until</div>
                    <div class="text-sm font-mono text-white" x-text="formatDate(user.boosted_until, true)"></div>
                </div>
            </div>

            <!-- Chat History -->
            <div class="bg-surface rounded-xl border border-gray-700 overflow-hidden">
                <div class="p-4 border-b border-gray-700 flex justify-between items-center">
                    <h4 class="font-bold text-gray-300">Chat History</h4>
                    <div class="text-xs text-gray-500" x-text="(conversations?.length || 0) + ' conversations'"></div>
                </div>
                <div class="divide-y divide-gray-700">
                    <template x-if="conversationsLoading">
                        <div class="p-6 text-gray-400 flex items-center gap-3">
                            <i class="fas fa-circle-notch fa-spin"></i>
                            Loading chat history...
                        </div>
                    </template>

                    <template x-if="!conversationsLoading && conversations.length === 0">
                        <div class="p-6 text-gray-500">
                            No conversations found.
                        </div>
                    </template>

                    <template x-for="c in conversations" :key="c.id">
                        <a class="p-4 flex items-center gap-4 hover:bg-dark/50 transition-colors"
                           :href="'chat_detail.php?id=' + c.id">
                            <img :src="c.partner_avatar_url || 'https://ui-avatars.com/api/?name=' + c.partner_real_name"
                                 class="w-10 h-10 rounded-full border border-gray-700">
                            <div class="flex-1 overflow-hidden">
                                <div class="flex items-center justify-between gap-3">
                                    <div class="text-sm text-white font-medium truncate" x-text="c.partner_real_name"></div>
                                    <div class="text-[10px] px-2 py-1 rounded-full border"
                                         :class="c.is_anonymous ? 'bg-primary/10 text-primary border-primary/30' : 'bg-emerald-500/10 text-emerald-400 border-emerald-500/30'">
                                        <span class="font-bold uppercase tracking-wide" x-text="c.is_anonymous ? 'Anon' : 'Real'"></span>
                                    </div>
                                </div>
                                <div class="text-xs text-gray-400 truncate">
                                    <span x-show="c.last_msg_is_anon" class="text-primary font-bold mr-1" x-text="(c.last_msg_alias || 'Anon') + ':'"></span>
                                    <span x-text="c.last_message_text || 'No messages yet'"></span>
                                </div>
                                <div class="text-[10px] text-gray-500 mt-1 flex items-center gap-2">
                                    <span class="font-mono" x-text="'Chat #' + c.id"></span>
                                    <span x-show="c.is_anonymous && c.display_alias" x-text="'Alias: ' + c.display_alias"></span>
                                </div>
                            </div>
                            <div class="text-xs text-gray-500" x-text="formatDate(c.last_message_at)"></div>
                        </a>
                    </template>
                </div>
            </div>

        </div>

    </div>

</div>

<script>
function userDetail(id) {
    return {
        userId: id,
        user: null,
        loading: true,
        conversations: [],
        conversationsLoading: true,

        init() {
            this.fetchUser();
            this.fetchConversations();
        },

        fetchUser() {
            fetch(`/backend-php/public/api/admin/users/${this.userId}`)
                .then(res => res.json())
                .then(data => {
                    // Format date for datetime-local input
                    if (data.plus_expires_at) {
                        data.plus_expires_at_formatted = new Date(data.plus_expires_at).toISOString().slice(0, 16);
                    } else {
                        data.plus_expires_at_formatted = '';
                    }
                    
                    // Parse device_info if it's a string (MySQL JSON sometimes returns as string in some PHP versions)
                    if (typeof data.device_info === 'string') {
                        try { data.device_info = JSON.parse(data.device_info); } catch(e) {}
                    }
                    
                    this.user = data;
                    this.loading = false;
                });
        },

        updateSubscription() {
            // Re-map the formatted date back
            const payload = {
                is_plus_subscriber: this.user.is_plus_subscriber,
                plus_expires_at: this.user.plus_expires_at_formatted,
                active_frame: this.user.active_frame
            };

            fetch(`/backend-php/public/api/admin/users/${this.userId}/subscription`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    showToast('Subscription updated successfully');
                    this.fetchUser();
                } else {
                    showToast(data.error || 'Update failed', 'error');
                }
            })
            .catch(err => {
                console.error(err);
                showToast('An error occurred', 'error');
            });
        },

        addBoost(minutes) {
            fetch(`/backend-php/public/api/admin/users/${this.userId}/boost`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ minutes: minutes })
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    showToast('Boost added: ' + minutes + 'm');
                    this.fetchUser();
                } else {
                    showToast(data.error || 'Boost failed', 'error');
                }
            })
            .catch(err => {
                console.error(err);
                showToast('An error occurred', 'error');
            });
        },

        fetchConversations() {
            fetch(`/backend-php/public/api/admin/users/${this.userId}/conversations?limit=100`)
                .then(res => res.json())
                .then(data => {
                    this.conversations = Array.isArray(data) ? data : [];
                    this.conversationsLoading = false;
                })
                .catch(() => {
                    this.conversations = [];
                    this.conversationsLoading = false;
                });
        },

        formatDate(dateStr, showTime = false) {
            if (!dateStr) return '-';
            const opt = { month: 'short', day: 'numeric', year: 'numeric' };
            if (showTime) {
                opt.hour = '2-digit';
                opt.minute = '2-digit';
            }
            return new Date(dateStr).toLocaleDateString(undefined, opt);
        },

        banUser() {
            if(!confirm('Ban this user?')) return;
            fetch(`/backend-php/public/api/admin/users/${this.userId}/ban`, { method: 'POST' })
                .then(() => {
                    showToast('User banned');
                    this.fetchUser();
                });
        }
    }
}
</script>

<?php require_once 'includes/footer.php'; ?>
