<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\PageContent;
use Illuminate\Http\Request;

class CmsController extends Controller
{
    public function index()
    {
        try {
            // Get all PHP files in the Frontend directory
            $rootPath = base_path('../Frontend');
            $files = glob($rootPath . '/*.php');
        
            $pages = [];
            $exclude = ['cookie.txt', 'test.php']; // Add any files to exclude
            
            foreach ($files as $file) {
                $name = basename($file);
                if (!in_array($name, $exclude)) {
                    $exists = PageContent::where('page_name', $name)->exists();

                    $pages[] = (object)[
                        'page_name' => $name,
                        'is_configured' => $exists
                    ];
                }
            }

            return view('admin.cms.index', compact('pages'));
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('CMS Index Error: ' . $e->getMessage());
            return back()->with('error', 'CMS Error: ' . $e->getMessage());
        }
    }

    public function editPage($pageName)
    {
        $contents = PageContent::where('page_name', $pageName)->get();
        return view('admin.cms.edit', compact('pageName', 'contents'));
    }

    public function updateContent(Request $request)
    {
        $request->validate([
            'contents' => 'required|array',
            'contents.*.id' => 'required',
            'contents.*.content_value' => 'required|string',
        ]);

        foreach ($request->contents as $content) {
            PageContent::where('id', $content['id'])->update([
                'content_value' => $content['content_value']
            ]);
        }

        return back()->with('success', 'Page content updated successfully.');
    }
}
