<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\File;
use App\Models\User;

class AuthorController extends Controller
{
    public function addAuthor()
    {
        $data = [
            'user' => Auth::user(),
            'departments' => [
                'Bachelor of Science in Criminology',
                'Bachelor of Science in Information Technology',
                'Bachelor of Science in Nursing',
                'Bachelor of Science in Hospitality Management',
                'Bachelor of Science in Radiologic Technology',
                'Diploma in Hotel and Restaurant Technology'
            ],
            'pageTitle' => 'Add new author'
        ];
        return view('back.pages.authors.add-author', $data); // create.blade.php
    }
    public function createAuthor(Request $request)
    {
        $request->validate([
            'author_name' => 'required|string|max:255',
            'author_username' => 'required|string',
            'author_email' => 'required|email',
            'author_password' => 'required|string|min:6',
            'department' => 'required|string',
            'author_profile_image' => 'nullable|image|mimes:jpg,jpeg,png|max:3072',
        ]);


        $profileImageName = null;

        if ($request->hasFile('author_profile_image') && $request->file('author_profile_image')->isValid()) {
            $path = 'images/users/';
            $file = $request->file('author_profile_image');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path($path), $filename);
            $profileImageName = $filename;
        }


        // Save as user with type "author"
        $user = new User();
        $user->name = $request->author_name;
        $user->username = $request->author_username;
        $user->email = $request->author_email;
        $user->password = Hash::make($request->author_password);
        $user->department = $request->department;
        $user->type = 'author';
        $user->picture = $profileImageName;
        $user->status = 'active';
        $saved = $user->save();

        return response()->json([
            'status' => $saved ? 1 : 0,
            'message' => $saved ? 'New Author has been successfully added.' : 'Something went wrong.'
        ]);
    }
    public function allAuthors(Request $request)
    {
        $data = [
            'pageTitle' => 'Authors'
        ];
        return view('back.pages.authors.authors', $data);
    }
    public function editAuthor(Request $request, $id = null)
    {
        $author = User::findOrFail($id);

        $data = [
            'user' => Auth::user(),
            'pageTitle' => 'Edit Author',
            'departments' => [
                'Bachelor of Science in Criminology',
                'Bachelor of Science in Information Technology',
                'Bachelor of Science in Nursing',
                'Bachelor of Science in Hospitality Management',
                'Bachelor of Science in Radiologic Technology',
                'Diploma in Hotel and Restaurant Technology'
            ],
            'author' => $author
        ];
        return view('back.pages.authors.edit-author', $data);
    }

    public function updateAuthor(Request $request)
    {
        $author = User::findOrFail($request->author_id);
        $author_image_name = $author->getAttributes()['picture'];
        if (filter_var($author_image_name, FILTER_VALIDATE_URL)) {
            $author_image_name = basename(parse_url($author_image_name, PHP_URL_PATH));
        }
        $request->validate([
            'author_name' => 'required|string|max:255',
            'author_username' => 'required|string',
            'author_email' => 'required|email',
            'department' => 'required|string',
            'author_profile_image' => 'nullable|image|mimes:jpg,jpeg,png|max:3072',
        ]);

        $path = '/images/users/';
        if ($request->hasFile('author_profile_image') && $request->file('author_profile_image')->isValid()) {
            $file = $request->file('author_profile_image');
            $filename = time() . '_' . $file->getClientOriginalName();

            $relativePath = $path . $author_image_name;
            if ($author_image_name && File::exists(public_path($relativePath))) {
                File::delete(public_path($relativePath));
            }

            $file->move(public_path($path), $filename);
            $author_image_name = $filename;
        }

        // Update fields
        $author->name = $request->author_name;
        $author->username = $request->author_username;
        $author->email = $request->author_email;
        $author->department = $request->department;
        $author->picture = $author_image_name;
        $author->status = $request->has('is_active') ? 'active' : 'inactive';

        $saved = $author->save();

        return response()->json([
            'status' => $saved ? 1 : 0,
            'message' => $saved ? 'Author has been successfully updated.' : 'Something went wrong.'
        ]);
    }
}
