<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Cities;
use App\Models\Company;
use App\Models\Country;
use App\Models\Faq;
use App\Models\User;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Http\JsonResponse;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
class FaqController extends Controller
{
    public function index()
    {
        $faq = Faq::orderBy('id', 'desc')->get();
        
        return view('admin.faq.index', compact('faq'));

    }
    public function create(){
        $today = date("Y-m-d");
        $faq = "";
        $title       = "";
        return view('admin.faq.create', compact('today', 'faq'));

    }

    public function store(Request $request)
    {
        $rules = [
            'question' => 'required|string|max:255',
            'answer' => 'required|string',
            'status' => 'required|in:0,1',
        ];
    
        $validator = Validator::make($request->all(), $rules);
    
        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'errors' => $validator->errors(),
            ], 422);
        }
    
        if ($request->id) {
            $faq = Faq::find($request->id);
    
            if (!$faq) {
                return response()->json(['status' => 'error', 'message' => 'Faq not found'], 404);
            }
    
            $existingfaq = Faq::where('question', $request->question)
                ->where('id', '!=', $request->id)
                ->first();
    
            if ($existingfaq) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The question already exists.']
                    ]
                ], 422);
            }
    
            $faq->question = $request->question;
            $faq->answer = $request->answer;
            $faq->status = $request->status;
            $faq->save();
    
            return response()->json(['status' => 'success', 'message' => 'Question updated successfully']);
        } else {
            $existingfaq = Faq::where('question', $request->question)->first();
    
            if ($existingfaq) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The question already exists.']
                    ]
                ], 422);
            }
    
            $faq = Faq::create([
                'question' => $request->question,
                'answer' => $request->answer,
                'status' => $request->status,
            ]);
    
            return response()->json(['status' => 'success', 'message' => 'Question added successfully', 'faq' => $faq]);
        }
    }
    


  
    public function edit($id) {
        $faq = Faq::findOrFail($id);
        return view('admin.faq.create', compact('faq'));
    }

    public function destroy($id): JsonResponse
    {
        try {
            $faq = Faq::findOrFail($id);           
            $faq->delete();
            return response()->json([
                'status' => 'success',
                'message' => 'Faq deleted successfully.'
            ], 200);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Faq not found.'
            ], 404);
        } catch (Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while deleting the company.'
            ], 500);
        }
    }

    public function statusChange(Request $request, $id) {
        $faq = Faq::find($id);

        if (!$faq) {
            return response()->json([
                'status' => 'error',
                'message' => 'Faq not found.'
            ], 404);
        }
    
        $faq->status = $request->status;
        $faq->save();
    
        return response()->json([
            'status' => 'success',
            'message' => 'Faq status updated successfully.'
        ]);
    }

    public function export()
    {
        $faqs = Faq::all();

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle('FAQs');

        $sheet->setCellValue('A1', 'No');
        $sheet->setCellValue('B1', 'Question');
        $sheet->setCellValue('C1', 'Answer');
        $sheet->setCellValue('D1', 'Status');
        $sheet->setCellValue('E1', 'Created At');

        $row = 2; 
        foreach ($faqs as $index => $faq) {
            $sheet->setCellValue('A' . $row, $index + 1); 
            $sheet->setCellValue('B' . $row, $faq->question); 
            $sheet->setCellValue('C' . $row, $faq->answer); 
            $sheet->setCellValue('D' . $row, $faq->status ? 'Active' : 'Inactive'); 
            $sheet->setCellValue('E' . $row, $faq->created_at->format('d M, Y - h:i A')); 
            $row++;
        }

    
        $sheet->getStyle('A1:E1')->getFont()->setBold(true);
        $sheet->getStyle('A1:E1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle('A1:E1')->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);

        
        $writer = new Xlsx($spreadsheet);
        $fileName = "FAQs_Export_" . date('Y_m_d_H_i_s') . ".xlsx";

        header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $writer->save('php://output');
        exit();
    }
}
