<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use App\Http\Requests\Manage\ManageArtworkEditRequest;
use App\Http\Requests\Manage\ManageArtworkUpdateRequest;
use App\Http\Requests\Manage\ManageArtworkDestroyRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;

class ManageController extends Controller
{
    public function index(Request $request)
    {
        $userId = $request->user()->id;
        $perPage = 50;

        $categorySub = DB::table('artwork_category as ac')
            ->join('categories as c', 'ac.category_id', '=', 'c.id')
            ->select('ac.artwork_id', DB::raw('MIN(c.name) as category_name'))
            ->groupBy('ac.artwork_id');

        $query = DB::table('artworks as a')
            ->leftJoinSub($categorySub, 'cat', function ($join) {
                $join->on('a.id', '=', 'cat.artwork_id');
            })
            ->leftJoin('artwork_stats as s', 'a.id', '=', 's.artwork_id')
            ->where('a.user_id', $userId)
            ->select(
                'a.*',
                DB::raw('cat.category_name as category_name'),
                DB::raw('COALESCE(s.rating_count, 0) as rating_num'),
                DB::raw('COALESCE(s.rating_avg, 0) as rating'),
                DB::raw('COALESCE(s.downloads, 0) as dls'),
                DB::raw('COALESCE(s.favorites, 0) as zoom'),
                DB::raw('COALESCE(s.views, 0) as views')
            )
            ->orderByDesc('a.published_at')
            ->orderByDesc('a.id');

        $artworks = $query->paginate($perPage);

        return view('manage.index', [
            'artworks' => $artworks,
            'page_title' => 'Artwork Manager',
        ]);
    }

    public function edit(ManageArtworkEditRequest $request, $id)
    {
        $artwork = $request->artwork();

        $selectedCategory = DB::table('artwork_category')->where('artwork_id', (int)$id)->value('category_id');
        $artwork->category = $selectedCategory;

        $categories = DB::table('categories')
            ->where('content_type_id', 0)
            ->orderBy('id')
            ->select(DB::raw('id as category_id'), DB::raw('name as category_name'))
            ->get();

        return view('manage.edit', [
            'artwork' => $artwork,
            'categories' => $categories,
            'page_title' => 'Edit Artwork: ' . ($artwork->title ?? ''),
        ]);
    }

    public function update(ManageArtworkUpdateRequest $request, $id)
    {
        $existing = $request->artwork();
        $data = $request->validated();
        $update = [
            'title' => $data['title'],
            'description' => $data['description'] ?? $existing->description,
            'updated' => now(),
        ];

        if ($request->hasFile('artwork')) {
            $file = $request->file('artwork');
            $path = $file->store('public/uploads/artworks');
            $filename = basename($path);
            $update['picture'] = $filename;
        }

        if ($request->hasFile('attachment')) {
            $att = $request->file('attachment');
            $attPath = $att->store('public/uploads/attachments');
            $update['fname'] = basename($attPath);
        }

        DB::table('artworks')->where('id', (int)$id)->update($update);

        if (isset($data['section'])) {
            DB::table('artwork_category')->where('artwork_id', (int)$id)->delete();
            DB::table('artwork_category')->insert([
                'artwork_id' => (int)$id,
                'category_id' => (int)$data['section'],
            ]);
        }

        return redirect()->route('manage')->with('status', 'Artwork was successfully updated.');
    }

    public function destroy(ManageArtworkDestroyRequest $request, $id)
    {
        $artwork = $request->artwork();

        if (!empty($artwork->fname)) {
            Storage::delete('public/uploads/attachments/' . $artwork->fname);
        }
        if (!empty($artwork->picture)) {
            Storage::delete('public/uploads/artworks/' . $artwork->picture);
        }

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

        return redirect()->route('manage')->with('status', 'Artwork deleted.');
    }
}
