<?php
  
namespace App\Http\Controllers\Admin;
  
use App\Http\Requests\Admin\StoreBannerRequest;
use App\Http\Requests\Admin\StorePageRequest;
use App\Http\Requests\Admin\UpdateBannerRequest;
use App\Http\Requests\Admin\UpdatePageRequest;
use App\Http\Controllers\Controller;
use App\Models\Attachment;
use App\Models\BannerImage;
use App\Models\PageDetail;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Str;
use Illuminate\View\View;
use Session;

  
class PageController extends Controller
{ 
    private function guestRedirect(): RedirectResponse
    {
        return redirect()->route('admin.logindata')
            ->with('message', 'Please login to continue.');
    }

    private function pageSlug(string $pageName): string
    {
        return Str::slug($pageName);
    }

    private function resolveAttachmentUrl(?int $attachmentId, string $fallbackUrl): string
    {
        if ((int) $attachmentId <= 0) {
            return $fallbackUrl;
        }

        $attachment = Attachment::query()->find($attachmentId);

        return $attachment ? ASSETURL.'files/'.$attachment->att_url : $fallbackUrl;
    }

    public function addpage(): View|RedirectResponse
    {
        if (!Auth::check()) { 
            return $this->guestRedirect();
          }           

        return view('admin.pages.addpage');
    } 


    public function savepage(StorePageRequest $request): RedirectResponse
    {
        $validated = $request->validated();

        PageDetail::query()->create([
            'pagename' => $validated['pagename'],
            'pageslug' => $this->pageSlug($validated['pagename']),
            'pagecontent' => $validated['DSC'] ?? null,
            'pageimg' => $validated['photoid'] ?? null,
            'pageorder' => $validated['pageorder'] ?? null,
            'createdby' => Auth::id(),
            'createdtime' => now(),
        ]);

        Session::flash('sucmessage', "Successful,  Institute / School Pages has Added"); 
		 
		return Redirect::back(); 
    } 


    public function pagemanagement(): View|RedirectResponse
    {
        if (!Auth::check()) { 
            return $this->guestRedirect();
          }      
          
          $pagedetails = PageDetail::query()
              ->where('createdby', Auth::id())
              ->orderByDesc('id')
              ->get()
              ->map(function (PageDetail $page) {
                  $page->image_url = $this->resolveAttachmentUrl(
                      (int) $page->pageimg,
                      ASSETURL.'public/frontend/images/logo.png'
                  );

                  return $page;
              });

        return view('admin.pages.pagemanagement')->with('pagedetails',$pagedetails);
    } 
         
    public function editpage($id): View|RedirectResponse {

        if (!Auth::check()) { 
            return $this->guestRedirect();
          }    
          
        $pagedetails = PageDetail::query()
            ->where('id', $id)
            ->where('createdby', Auth::id())
            ->firstOrFail();

        $pagedetails->image_url = $this->resolveAttachmentUrl(
            (int) $pagedetails->pageimg,
            ASSETURL.'public/frontend/images/logo.png'
        );

        return view('admin.pages.editpage')->with('pagedetails',$pagedetails);
    } 

    public function updatepage(UpdatePageRequest $request): RedirectResponse
    {
        $validated = $request->validated();

        $page = PageDetail::query()
            ->where('id', $validated['editid'])
            ->where('createdby', Auth::id())
            ->firstOrFail();

        $page->update([
            'pagename' => $validated['pagename'],
            'pageslug' => $this->pageSlug($validated['pagename']),
            'pagecontent' => $validated['DSC'] ?? null,
            'pageimg' => $validated['photoid'] ?? null,
            'pageorder' => $validated['pageorder'] ?? null,
        ]);

       
       Session::flash('sucmessage', "Successful,  Institute / School Pages has Updated"); 
        
       return redirect('admin/pagemanagement');

    } 

    public function deletepage($id): RedirectResponse {

        if (!Auth::check()) { 
            return $this->guestRedirect();
          }    
          
           PageDetail::query()
               ->where('id', $id)
               ->where('createdby', Auth::id())
               ->delete();  
          
        Session::flash('sucmessage', "Successful,  Institute / School Pages has Deleted"); 
		 
		 return Redirect::back(); 
       
        
    } 

    /////////////////
    // Banner Management
    /////////////
    

    public function bannermanagement(): View|RedirectResponse
    {
        if (!Auth::check()) { 
            return $this->guestRedirect();
          }      
          
          $bannerimages = BannerImage::query()
              ->orderByDesc('id')
              ->get()
              ->map(function (BannerImage $banner) {
                  $banner->image_url = $this->resolveAttachmentUrl(
                      (int) $banner->bannerimg,
                      asset('public/frontend/images/logo.png')
                  );

                  return $banner;
              });

        return view('admin.banner.bannermanagement')->with('bannerimages',$bannerimages);
    } 
    

    public function addbanner(): View|RedirectResponse
    {
        if (!Auth::check()) { 
            return $this->guestRedirect();
          }           

        return view('admin.banner.addbanner');
    } 

    public function savebanner(StoreBannerRequest $request): RedirectResponse
    {
        $validated = $request->validated();

        BannerImage::query()->create([
            'bannrename' => $validated['pagename'],
            'bannerimg' => $validated['photoid'] ?? null,
            'createdby' => Auth::id(),
            'createdtime' => now(),
        ]);

        Session::flash('sucmessage', "Successful,  Banner has Added"); 
		 
		return Redirect::back(); 
    } 


    
    public function editbanner($id): View|RedirectResponse {

        if (!Auth::check()) { 
            return $this->guestRedirect();
          }    
          
          $bannerimages = BannerImage::query()->findOrFail($id);
          $bannerimages->image_url = $this->resolveAttachmentUrl(
              (int) $bannerimages->bannerimg,
              asset('public/frontend/images/logo.png')
          );          

        return view('admin.banner.editbanner')->with('bannerimages',$bannerimages);
    } 
    

    public function updatebanner(UpdateBannerRequest $request): RedirectResponse
    {
        $validated = $request->validated();

        $banner = BannerImage::query()->findOrFail($validated['editid']);

        $banner->update([
            'bannrename' => $validated['pagename'],
            'bannerimg' => $validated['photoid'] ?? null,
        ]);

       
       Session::flash('sucmessage', "Successful,  Institute / School Banner has Updated"); 
        
       return redirect('admin/bannermanagement');

    } 


    public function deletebanner($id): RedirectResponse {

        if (!Auth::check()) { 
            return $this->guestRedirect();
          }    
          
           BannerImage::query()->where('id', $id)->delete();  
          
        Session::flash('sucmessage', "Successful,   Banner has Deleted"); 
		 
		 return Redirect::back(); 
       
        
    } 
    

}

