<?php

/*
    Created by Mohamed.
*/


namespace App\Http\Controllers\API\Dashboard;

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

class ContactController extends Controller
{

    public function index(Request $request)
    {
        $perPage = $request->query('per_page', 10);
        $contacts = Contact::paginate($perPage);

        return response()->json([
            'success' => true,
            'data' => $contacts->items(),
            'pagination' => [
                'current_page' => $contacts->currentPage(),
                'total_pages' => $contacts->lastPage(),
                'per_page' => $contacts->perPage(),
                'total' => $contacts->total(),
            ]
        ]);
    }


    public function respond(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'response' => 'required|string',
            'status' => 'required|in:pending,resolved,rejected'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 422);
        }

        $contact = Contact::find($id);

        if (!$contact) {
            return response()->json([
                'success' => false,
                'message' => 'Contact message not found'
            ], 404);
        }

        $contact->update([
            'response' => $request->response,
            'status' => $request->status
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Response updated successfully',
            'data' => $contact
        ]);
    }
    public function destroy($id)
    {
        $contact = Contact::find($id);

        if (!$contact) {
            return response()->json([
                'message' => 'السجل غير موجود',
            ], 404);
        }
        $contact->delete();

        return response()->json([
            'message' => 'تم حذف السجل بنجاح',
        ], 200);
    }
}