<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Channel;
use App\Models\Tour;
use App\Models\ChannelCommission;
use App\Models\TourExceptionCommission;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ChannelCommissionController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $channels = Channel::where('status', 1)->get();
        $tours = Tour::where('status', 1)->get();
        $channelCommissions = ChannelCommission::with('tourExceptions')->get();
        return view('admin.channel_commission.index', compact('channels', 'tours', 'channelCommissions'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'channels' => 'required|array',
            'commissions' => 'required|array',
            'channels.*' => 'exists:channels,id',
            'commissions.*' => 'numeric|min:0',
            'tours' => 'nullable|array',
            'tour_commissions' => 'nullable|array',
            'tours.*' => 'array',
            'tours.*.*' => 'exists:tours,id',
            'tour_commissions.*' => 'array',
            'tour_commissions.*.*' => 'numeric|min:0',
        ]);

        DB::transaction(function () use ($request) {
            foreach ($request->channels as $index => $channelId) {
                $channelCommission = ChannelCommission::updateOrCreate(
                    ['channel_id' => $channelId],
                    ['commission' => $request->commissions[$index]]
                );
                if (!empty($request->tours[$index]) && is_array($request->tours[$index])) {
                    foreach ($request->tours[$index] as $tourIndex => $tourId) {
                        $tourCommission = $request->tour_commissions[$index][$tourIndex] ?? 0;

                        TourExceptionCommission::updateOrCreate(
                            [
                                'channel_commission_id' => $channelCommission->id,
                                'tour_id' => $tourId,
                            ],
                            ['commission' => $tourCommission]
                        );
                    }
                }
            }
            if ($request->filled('deleted_commissions')) {
                $deletedIds = explode(',', $request->deleted_commissions);
                TourExceptionCommission::whereIn('channel_commission_id', $deletedIds)->delete();
                ChannelCommission::whereIn('id', $deletedIds)->whereExists(function ($query) {
                    $query->select(DB::raw(1))->from('channel_commissions')->whereColumn('id', 'channel_commissions.id');
                })->delete();
            }
            if ($request->filled('deleted_tour_exceptions')) {
                $deletedIds = explode(',', $request->deleted_tour_exceptions);
                TourExceptionCommission::whereIn('id', $deletedIds)->whereExists(function ($query) {
                    $query->select(DB::raw(1))->from('tour_exception_commissions')->whereColumn('id', 'tour_exception_commissions.id');
                })->delete();
            }
        });
        return redirect()->back()->with('success', 'Commissions saved successfully!');
    }


    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
