<?php

namespace App\Http\Controllers;

use App\Contact;
use App\SiteSetting;
use Illuminate\Http\Request;

class ContactController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth')->only(['index', 'view', 'destroy']);
        $this->middleware('admin')->only(['index', 'view', 'destroy']);
    }

    public function show()
    {
        return view('contact');
    }

    public function send(Request $request)
    {
        $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|email|max:255',
            'subject' => 'required|max:255',
            'message' => 'required',
        ]);

        // reCAPTCHA verification
        if (SiteSetting::get('recaptcha_enabled', '0') == '1' && SiteSetting::get('recaptcha_secret_key', '')) {
            $recaptcha = $request->input('g-recaptcha-response');
            if (!$recaptcha) {
                return back()->withInput()->withErrors(['g-recaptcha-response' => 'يرجى تأكيد أنك لست برنامج روبوت']);
            }
            $response = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . SiteSetting::get('recaptcha_secret_key') . '&response=' . $recaptcha);
            $result = json_decode($response);
            if (!$result || !$result->success) {
                return back()->withInput()->withErrors(['g-recaptcha-response' => 'فشل التحقق من reCAPTCHA، يرجى المحاولة مرة أخرى']);
            }
        }

        Contact::create([
            'name' => $request->name,
            'email' => $request->email,
            'subject' => $request->subject,
            'message' => $request->message,
        ]);

        flash('تم إرسال رسالتك بنجاح! سنقوم بالرد عليك قريباً.')->success();
        return redirect('/contact');
    }

    // Admin: view messages
    public function index()
    {
        $messages = Contact::orderBy('created_at', 'desc')->get();
        return view('admin.contacts.index', compact('messages'));
    }

    public function view($id)
    {
        $contact = Contact::findOrFail($id);
        $contact->is_read = 1;
        $contact->save();
        return view('admin.contacts.view', compact('contact'));
    }

    public function destroy($id)
    {
        Contact::findOrFail($id)->delete();
        flash('تم حذف الرسالة بنجاح')->error();
        return redirect('/admin/contacts');
    }
}
