<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\Task;
use App\Models\TaskRequest;
use App\Models\User;
use App\Models\UserLedger;
use Illuminate\Http\Request;

class TaskController extends Controller
{
    public $route = 'admin.task';

    // List all tasks
    public function index()
    {
        $tasks = Task::get();
        return view('admin.pages.task.index', compact('tasks'));
    }

    // Show create/edit form
    public function create($id = null)
    {
        $data = $id ? Task::find($id) : null;
        return view('admin.pages.task.insert', compact('data'));
    }

    // Insert or update task
    public function insert_or_update(Request $request)
    {
        $this->validate($request, [
            'level' => 'required|integer|min:1',
            'required_invites' => 'required|integer|min:1',
            'required_purchase' => 'required|numeric|min:1',
            'bonus' => 'required|numeric|min:0',
            'extra_profit' => 'required|numeric|min:0',
        ]);

        $model = $request->id ? Task::findOrFail($request->id) : new Task();

        $model->level = $request->level;
        $model->required_invites = $request->required_invites;
        $model->required_purchase = $request->required_purchase;
        $model->bonus = $request->bonus;
        $model->extra_profit = $request->extra_profit;
        $model->progress = $model->progress ?? 0;
        $model->status = $model->status ?? 'Not Eligible';

        $model->save();

        return redirect()->route($this->route.'.index')
                         ->with('success', $request->id ? 'Task Updated Successfully.' : 'Task Created Successfully.');
    }

    // Delete task and related requests
    public function delete($id)
    {
        $task = Task::findOrFail($id);
        TaskRequest::where('task_id', $id)->delete();
        $task->delete();

        return redirect()->route($this->route.'.index')->with('success', 'Task Deleted Successfully.');
    }

    // List task requests
    public function task_request()
    {
        $tasks = TaskRequest::orderByDesc('id')->get();
        return view('admin.pages.task_request', compact('tasks'));
    }

    // Approve or reject a task request
    public function task_request_status($taskReId, $status)
    {
        $taskRe = TaskRequest::findOrFail($taskReId);
        $task = Task::findOrFail($taskRe->task_id);
        $user = User::findOrFail($taskRe->user_id);

        if ($status == 'approved' && $taskRe->status == 'pending') {
            // Add task bonus to user balance
            $user->balance += $task->bonus;

            // Automatically promote VIP if applicable
            if ($user->vip_level < $task->level) {
                $user->vip_level = $task->level;
            }

            $user->save();

            $taskRe->status = 'approved';
            $taskRe->save();

        } elseif ($status == 'rejected') {
            if ($taskRe->status == 'approved') {
                // Remove bonus if previously approved
                $user->balance -= $task->bonus;
            }
            $taskRe->status = 'rejected';
            $taskRe->save();
            $user->save();
        }

        // Log to user ledger
        UserLedger::create([
            'user_id' => $user->id,
            'reason' => 'task_income',
            'perticulation' => 'Task Commission '.price($task->bonus).' '.$status,
            'amount' => $task->bonus,
            'debit' => $task->bonus,
            'status' => $status,
            'date' => now()->format('d-m-Y H:i')
        ]);

        return redirect('admin/secret/task/request')
               ->with('success', 'Request '.$taskRe->status);
    }

    // Optional: Function to check and update all users' task progress
    public function updateAllTaskProgress()
    {
        $users = User::get();

        foreach ($users as $user) {
            $tasks = Task::where('user_id', $user->id)->orderBy('level')->get();

            foreach ($tasks as $task) {
                $eligibleSubordinates = $user->subordinates()
                    ->where('grade', 'A')
                    ->whereHas('orders', function($q) use ($task) {
                        $q->where('total', '>=', $task->required_purchase);
                    })->count();

                $task->progress = $eligibleSubordinates;

                if ($eligibleSubordinates >= $task->required_invites) {
                    $task->status = 'Eligible';

                    // VIP promotion
                    if ($user->vip_level < $task->level) {
                        $user->vip_level = $task->level;
                        $user->save();
                    }
                } else {
                    $task->status = 'Not Eligible';
                }

                $task->save();
            }
        }

        return redirect()->back()->with('success', 'All task progress updated successfully.');
    }
}
