<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\TargetCampaign;
use Illuminate\Http\Request;

class TargetCampaignAdminController extends Controller
{
    public function index()
    {
        $items = TargetCampaign::orderByDesc('id')->get();
        return view('admin.targets.index', compact('items'));
    }

    public function create()
    {
        return view('admin.targets.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'title'          => 'required|string|max:120',
            'project_type'   => 'required|in:referral,jobpost,drive_offer,product',
            'is_active'      => 'required|boolean',
            'required_count' => 'required|integer|min:1',
            'referral_level' => 'nullable|integer|min:1|max:10',
            'start_at'       => 'required|date',
            'end_at'         => 'required|date|after:start_at',
            'bonus_amount'   => 'required|numeric|min:0.01',
            'bonus_wallet'   => 'required|in:cash,voucher',
            'description'    => 'nullable|string',
        ]);

        if ($data['project_type'] !== 'referral') {
            $data['referral_level'] = null;
        }

        TargetCampaign::create($data);

        return redirect()->route('admin.targets.index')->with('success','✅ Target Campaign created.');
    }

    public function edit(TargetCampaign $target)
    {
        return view('admin.targets.edit', compact('target'));
    }

    public function update(Request $request, TargetCampaign $target)
    {
        $data = $request->validate([
            'title'          => 'required|string|max:120',
            'project_type'   => 'required|in:referral,jobpost,drive_offer,product',
            'is_active'      => 'required|boolean',
            'required_count' => 'required|integer|min:1',
            'referral_level' => 'nullable|integer|min:1|max:10',
            'start_at'       => 'required|date',
            'end_at'         => 'required|date|after:start_at',
            'bonus_amount'   => 'required|numeric|min:0.01',
            'bonus_wallet'   => 'required|in:cash,voucher',
            'description'    => 'nullable|string',
        ]);

        if ($data['project_type'] !== 'referral') {
            $data['referral_level'] = null;
        }

        $target->update($data);

        return redirect()->route('admin.targets.index')->with('success','✅ Updated.');
    }

    public function toggle(TargetCampaign $target)
    {
        $target->update(['is_active' => ! $target->is_active]);
        return back()->with('success','✅ Status toggled.');
    }

    public function destroy(TargetCampaign $target)
    {
        $target->delete();
        return back()->with('success','🗑️ Deleted.');
    }
}