<?php

namespace App\Http\Controllers;

use App\Helpers\ApiResponse;
use App\Models\News;
use App\Models\User;      
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;

class NewsController extends Controller
{
    // ─────────────────────────────────
    // GET ALL PUBLISHED NEWS (Public)
    // GET /api/news
    // ─────────────────────────────────
    public function getPublishedNews()
    {
        $news = News::where('status', 'PUBLISHED')
                    ->latest('published_at')
                    ->get();

        $data = $news->map(function ($n) {
            return [
                'id'           => (string) $n->id,
                'title'        => $n->title,
                'content'      => $n->content,
                'image'        => $n->image
                    ? asset('storage/' . $n->image)
                    : null,
                'status'       => $n->status,
                'published_at' => $n->published_at
                    ? $n->published_at->format('d M Y h:i A')
                    : null,
                'created_at'   => (string) $n->created_at,
            ];
        });

        return ApiResponse::success(
            $data,
            'News fetched successfully'
        );
    }

    // ─────────────────────────────────
    // GET SINGLE NEWS DETAIL (Public)
    // POST /api/news/detail
    // ─────────────────────────────────
    public function getNewsDetail(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:news,id'
        ]);

        $news = News::find($request->id);

        if ($news->status !== 'PUBLISHED') {
            return ApiResponse::error(
                'News not found.',
                404
            );
        }

        return ApiResponse::success(
            [
                'id'           => (string) $news->id,
                'title'        => $news->title,
                'content'      => $news->content,
                'image'        => $news->image
                    ? asset('storage/' . $news->image)
                    : null,
                'status'       => $news->status,
                'published_at' => $news->published_at
                    ? $news->published_at->format('d M Y h:i A')
                    : null,
                'created_at'   => (string) $news->created_at,
            ],
            'News detail fetched successfully'
        );
    }

    // ─────────────────────────────────
    // GET ALL NEWS (Super Admin)
    // GET /api/admin/news
    // ─────────────────────────────────
    public function getAllNews()
    {
        $news = News::with('createdBy')
                    ->latest()
                    ->get();

        $data = $news->map(function ($n) {
            return [
                'id'           => (string) $n->id,
                'title'        => $n->title,
                'content'      => $n->content,
                'image'        => $n->image
                    ? asset('storage/' . $n->image)
                    : null,
                'status'       => $n->status,
                'created_by'   => $n->createdBy->name,
                'published_at' => $n->published_at
                    ? $n->published_at->format('d M Y h:i A')
                    : null,
                'created_at'   => (string) $n->created_at,
            ];
        });

        return ApiResponse::success(
            $data,
            'News fetched successfully'
        );
    }

    // ─────────────────────────────────
    // CREATE NEWS (Super Admin)
    // POST /api/admin/news
    // ─────────────────────────────────
    public function createNews(Request $request)
    {
        $request->validate([
            'title'   => 'required|string',
            'content' => 'required|string',
            'status'  => 'required|in:DRAFT,PUBLISHED',
            'image'   => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
        ]);

        // Handle image upload
        $imagePath = null;
        if ($request->hasFile('image')) {
            $image     = $request->file('image');
            $fileName  = 'news_' . time() . '_'
                         . $image->getClientOriginalName();
            $imagePath = $image->storeAs(
                'news_images', $fileName, 'public'
            );
        }

        $news = News::create([
            'created_by'   => auth()->id(),
            'title'   => $request->input('title'),
            'content' => $request->input('content'),
            'image'        => $imagePath,
            'status'  => $request->input('status'),
            'published_at' => $request->status === 'PUBLISHED'
                ? Carbon::now()
                : null,
        ]);

        return ApiResponse::success(
            [
                'id'           => (string) $news->id,
                'title'        => $news->title,
                'content'      => $news->content,
                'image'        => $news->image
                    ? asset('storage/' . $news->image)
                    : null,
                'status'       => $news->status,
                'published_at' => $news->published_at
                    ? $news->published_at->format('d M Y h:i A')
                    : null,
            ],
            'News created successfully',
            201
        );
    }

    // ─────────────────────────────────
    // UPDATE NEWS (Super Admin)
    // POST /api/admin/news/update
    // ─────────────────────────────────
    public function updateNews(Request $request)
    {
        $request->validate([
            'id'      => 'required|exists:news,id',
            'title'   => 'sometimes|string',
            'content' => 'sometimes|string',
            'image'   => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
        ]);

        $news = News::find($request->id);

        // Handle new image upload
        if ($request->hasFile('image')) {
            // Delete old image first
            if ($news->image) {
                Storage::disk('public')->delete($news->image);
            }
            $image       = $request->file('image');
            $fileName    = 'news_' . time() . '_'
                           . $image->getClientOriginalName();
            $news->image = $image->storeAs(
                'news_images', $fileName, 'public'
            );
        }

        if ($request->filled('title')) {
    $news->title = $request->input('title');
}

if ($request->filled('content')) {
    $news->content = $request->input('content');
}


        $news->save();

        return ApiResponse::success(
            [
                'id'      => (string) $news->id,
                'title'   => $news->title,
                'content' => $news->content,
                'image'   => $news->image
                    ? asset('storage/' . $news->image)
                    : null,
                'status'  => $news->status,
            ],
            'News updated successfully'
        );
    }

    // ─────────────────────────────────
    // TOGGLE STATUS (Super Admin)
    // PUT /api/admin/news/toggle-status
    // DRAFT → PUBLISHED / PUBLISHED → DRAFT
    // ─────────────────────────────────
    public function toggleStatus(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:news,id'
        ]);

        $news = News::find($request->id);

        if ($news->status === 'DRAFT') {
            $news->status       = 'PUBLISHED';
            $news->published_at = Carbon::now();
        } else {
            $news->status       = 'DRAFT';
            $news->published_at = null;
        }

        $news->save();

        $action = $news->status === 'PUBLISHED'
            ? 'published'
            : 'unpublished';

        return ApiResponse::success(
            [
                'id'           => (string) $news->id,
                'title'        => $news->title,
                'status'       => $news->status,
                'published_at' => $news->published_at
                    ? $news->published_at->format('d M Y h:i A')
                    : null,
            ],
            'News ' . $action . ' successfully'
        );
    }

    // ─────────────────────────────────
    // DELETE NEWS (Super Admin)
    // DELETE /api/admin/news
    // ─────────────────────────────────
    public function deleteNews(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:news,id'
        ]);

        $news = News::find($request->id);

        // Delete image if exists
        if ($news->image) {
            Storage::disk('public')->delete($news->image);
        }

        $news->delete();

        return ApiResponse::success(
            null,
            'News deleted successfully'
        );
    }
}