<?php

// ============================================
// CREATE: app/Http/Controllers/UserController.php
// ============================================

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{
    /**
     * Display user management page
     */
    public function index(Request $request)
    {
        $search = $request->get('search');
        $roleFilter = $request->get('role');
        $statusFilter = $request->get('status');

        $query = DB::table('users');

        // Search
        if ($search) {
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%");
            });
        }

        // Filter by role
        if ($roleFilter) {
            $query->where('role', $roleFilter);
        }

        // Filter by status
        if ($statusFilter !== null && $statusFilter !== '') {
            $query->where('is_active', $statusFilter);
        }

        $users = $query->orderBy('created_at', 'desc')->paginate(15);

        $totalUsers = DB::table('users')->count();
        $activeUsers = DB::table('users')->where('is_active', true)->count();
        $adminUsers = DB::table('users')->where('role', 'admin')->count();

        return view('account.users.index', compact(
            'users', 
            'search', 
            'roleFilter', 
            'statusFilter',
            'totalUsers',
            'activeUsers',
            'adminUsers'
        ));
    }

    /**
     * Store new user
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|string|min:8',
            'role' => 'required|in:admin,user,staff',
        ]);

        DB::table('users')->insert([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => Hash::make($validated['password']),
            'role' => $validated['role'],
            'is_active' => true,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return response()->json([
            'success' => true,
            'message' => 'User created successfully!'
        ]);
    }

    /**
     * Update user
     */
    public function update(Request $request, $id)
    {
        $user = DB::table('users')->where('id', $id)->first();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'User not found!'
            ], 404);
        }

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email,' . $id,
            'role' => 'required|in:admin,user,staff',
            'password' => 'nullable|string|min:8',
        ]);

        $data = [
            'name' => $validated['name'],
            'email' => $validated['email'],
            'role' => $validated['role'],
            'updated_at' => now(),
        ];

        // Update password if provided
        if ($request->filled('password')) {
            $data['password'] = Hash::make($validated['password']);
        }

        DB::table('users')->where('id', $id)->update($data);

        return response()->json([
            'success' => true,
            'message' => 'User updated successfully!'
        ]);
    }

    /**
     * Toggle user status
     */
    public function toggleStatus($id)
    {
        $user = DB::table('users')->where('id', $id)->first();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'User not found!'
            ], 404);
        }

        // Prevent self-deactivation
        if ($id == Auth::id()) {
            return response()->json([
                'success' => false,
                'message' => 'You cannot deactivate yourself!'
            ], 400);
        }

        $newStatus = !$user->is_active;

        DB::table('users')->where('id', $id)->update([
            'is_active' => $newStatus,
            'updated_at' => now()
        ]);

        return response()->json([
            'success' => true,
            'message' => 'User status updated!',
            'status' => $newStatus
        ]);
    }

    /**
     * Delete user
     */
    public function destroy($id)
    {
        $user = DB::table('users')->where('id', $id)->first();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'User not found!'
            ], 404);
        }

        // Prevent self-deletion
        if ($id == Auth::id()) {
            return response()->json([
                'success' => false,
                'message' => 'You cannot delete yourself!'
            ], 400);
        }

        DB::table('users')->where('id', $id)->delete();

        return response()->json([
            'success' => true,
            'message' => 'User deleted successfully!'
        ]);
    }

    /**
     * Get single user (for edit modal)
     */
    public function show($id)
    {
        $user = DB::table('users')->where('id', $id)->first();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'User not found!'
            ], 404);
        }

        // Remove password from response
        unset($user->password);

        return response()->json([
            'success' => true,
            'data' => $user
        ]);
    }
}