<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use App\Models\License;
use App\Models\User;
use Illuminate\Http\Request;

class MegaToolController extends Controller
{
    private function ownerOnly()
    {
        if (!auth()->user()->isOwner()) {
            abort(403, 'Owner access required');
        }
    }

    public function deleteAllKeys()
    {
        $this->ownerOnly();
        $count = License::count();
        License::truncate();
        AuditLog::record('MEGA_DELETE_ALL_KEYS', "Deleted all {$count} keys");
        return response()->json(['success' => true, 'message' => "Deleted {$count} keys"]);
    }

    public function blockAllKeys()
    {
        $this->ownerOnly();
        $count = License::where('is_blocked', false)->count();
        License::query()->update(['is_blocked' => true]);
        AuditLog::record('MEGA_BLOCK_ALL_KEYS', "Blocked all {$count} keys");
        return response()->json(['success' => true, 'message' => "Blocked {$count} keys"]);
    }

    public function unblockAllKeys()
    {
        $this->ownerOnly();
        $count = License::where('is_blocked', true)->count();
        License::query()->update(['is_blocked' => false]);
        AuditLog::record('MEGA_UNBLOCK_ALL_KEYS', "Unblocked all {$count} keys");
        return response()->json(['success' => true, 'message' => "Unblocked {$count} keys"]);
    }

    public function extendAllKeys(Request $request)
    {
        $this->ownerOnly();
        $request->validate(['hours' => 'required|integer|min:1|max:8760']);
        $hours = $request->hours;
        $count = License::count();
        License::query()->update(['expires_at' => \DB::raw("DATE_ADD(expires_at, INTERVAL {$hours} HOUR)")]);
        AuditLog::record('MEGA_EXTEND_ALL_KEYS', "Extended all {$count} keys by {$hours} hour(s)");
        return response()->json(['success' => true, 'message' => "Extended {$count} keys by {$hours} hour(s)"]);
    }

    public function deleteAllUsersExceptSelf()
    {
        $this->ownerOnly();
        $ownerId = auth()->id();
        
        // Exclude the main owner account 'arkadmin' from bulk deletion
        $query = User::where('id', '!=', $ownerId)->where('username', '!=', 'arkadmin');
        
        $count = $query->count();
        $userIds = $query->pluck('id');
        
        License::whereIn('created_by', $userIds)->delete();
        User::whereIn('id', $userIds)->delete();
        
        AuditLog::record('MEGA_DELETE_ALL_USERS', "Deleted {$count} users and their keys");
        return response()->json(['success' => true, 'message' => "Deleted {$count} users and all their keys"]);
    }

    public function selfTopup(Request $request)
    {
        $this->ownerOnly();
        $request->validate(['amount' => 'required|numeric|min:1']);
        
        $user = auth()->user();
        $user->increment('balance', $request->amount);
        
        AuditLog::record('MEGA_SELF_TOPUP', "Owner self-topped up ₹{$request->amount}");
        return response()->json(['success' => true, 'message' => "Self topped up ₹{$request->amount} successfully"]);
    }

    public function deleteUserKeys(Request $request)
    {
        $this->ownerOnly();
        $request->validate(['username' => 'required|string']);
        
        $targetUser = User::where('username', $request->username)->first();
        if (!$targetUser) {
            return response()->json(['success' => false, 'message' => 'User not found'], 404);
        }

        $count = License::where('created_by', $targetUser->id)->count();
        License::where('created_by', $targetUser->id)->delete();

        AuditLog::record('MEGA_DELETE_USER_KEYS', "Deleted all {$count} keys of user {$targetUser->username}");
        return response()->json(['success' => true, 'message' => "Deleted {$count} keys belonging to {$targetUser->username}"]);
    }

    public function deleteUnusedKeys()
    {
        $this->ownerOnly();
        $count = License::where('device_count', 0)->count();
        License::where('device_count', 0)->delete();

        AuditLog::record('MEGA_DELETE_UNUSED_KEYS', "Deleted all {$count} unused keys");
        return response()->json(['success' => true, 'message' => "Deleted {$count} unused keys successfully"]);
    }
}
