<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use App\Models\Guide;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class GuideController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $guides = Guide::orderBy('type')->orderBy('created_at', 'desc')->get();
        return view('dashboard.guides.index', compact('guides'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        // Redirect to index - we handle everything there
        return redirect()->route('guides.index');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'type' => 'required|in:prayer_guide,more_zikar,hajj_umrah',
            'title' => 'required|string|max:255',
            'pdf_file' => 'required|mimes:pdf|max:10240', // PDF file, max 10MB
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        try {
            // Create directory if it doesn't exist
            $publicPath = public_path();
            $guidesDir = $publicPath.'/uploads/guides';
            
            if (!file_exists($guidesDir)) {
                mkdir($guidesDir, 0755, true);
            }
            
            // Upload PDF file
            $pdf = $request->file('pdf_file');
            $pdfName = time().'_'.Str::slug(pathinfo($pdf->getClientOriginalName(), PATHINFO_FILENAME)).'.pdf';
            $pdf->move($guidesDir, $pdfName);
            $pdfPath = '/uploads/guides/'.$pdfName;

            Guide::create([
                'type' => $request->type,
                'title' => $request->title,
                'pdf_file' => $pdfPath,
            ]);

            return redirect()
                ->route('guides.index')
                ->with('success', 'Guide created successfully!');

        } catch (\Exception $e) {
            return redirect()
                ->back()
                ->withInput()
                ->with('error', 'Error creating guide: '.$e->getMessage());
        }
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        // Redirect to index - we handle everything there
        return redirect()->route('guides.index');
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'type' => 'required|in:prayer_guide,more_zikar,hajj_umrah',
            'title' => 'required|string|max:255',
            'pdf_file' => 'nullable|mimes:pdf|max:10240', // Optional PDF file, max 10MB
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        try {
            $guide = Guide::findOrFail($id);
            $data = $request->only(['type', 'title']);
            
            // Update PDF file if provided
            if ($request->hasFile('pdf_file')) {
                $publicPath = public_path();
                $guidesDir = $publicPath.'/uploads/guides';
                
                if (!file_exists($guidesDir)) {
                    mkdir($guidesDir, 0755, true);
                }
                
                // Delete old PDF if exists
                if ($guide->pdf_file && file_exists(public_path($guide->pdf_file))) {
                    unlink(public_path($guide->pdf_file));
                }
                
                // Upload new PDF
                $pdf = $request->file('pdf_file');
                $pdfName = time().'_'.Str::slug(pathinfo($pdf->getClientOriginalName(), PATHINFO_FILENAME)).'.pdf';
                $pdf->move($guidesDir, $pdfName);
                $data['pdf_file'] = '/uploads/guides/'.$pdfName;
            }

            $guide->update($data);

            return redirect()
                ->route('guides.index')
                ->with('success', 'Guide updated successfully!');

        } catch (\Exception $e) {
            return redirect()
                ->back()
                ->withInput()
                ->with('error', 'Error updating guide: '.$e->getMessage());
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        try {
            $guide = Guide::findOrFail($id);
            
            // Delete PDF file if exists
            if ($guide->pdf_file && file_exists(public_path($guide->pdf_file))) {
                unlink(public_path($guide->pdf_file));
            }
            
            $guide->delete();

            return redirect()
                ->route('guides.index')
                ->with('success', 'Guide deleted successfully!');

        } catch (\Exception $e) {
            return redirect()
                ->route('guides.index')
                ->with('error', 'Error deleting guide: '.$e->getMessage());
        }
    }
}
