<?php

namespace App\Http\Controllers;

use App\Models\NoticeBoard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;

class NoticeBoardController extends Controller
{
    /**
     * Get all NoticeBoard records.
     */
    public function index()
    {
        $noticeBoards = NoticeBoard::with(['noticeCategory', 'society', 'user'])->get();

        // Convert STDate and EdDate to Indian date format (dd/mm/YYYY H:i:s)
        $noticeBoards->each(function ($noticeBoard) {
            $noticeBoard->STDate = $noticeBoard->STDate ? Carbon::parse($noticeBoard->STDate)->format('d/m/Y H:i:s') : null;
            $noticeBoard->EdDate = $noticeBoard->EdDate ? Carbon::parse($noticeBoard->EdDate)->format('d/m/Y H:i:s') : null;
        });

        return response()->json($noticeBoards);
    }

    /**
     * Get a specific NoticeBoard record by Ntc_Id.
     */
    public function show($id)
    {
        $noticeBoard = NoticeBoard::with(['noticeCategory', 'society', 'user'])->find($id);

        if (!$noticeBoard) {
            return response()->json(['message' => 'Record not found'], 404);
        }

        // Convert STDate and EdDate to Indian date format (dd/mm/Y H:i:s)
        $noticeBoard->STDate = $noticeBoard->STDate ? Carbon::parse($noticeBoard->STDate)->format('d/m/Y H:i:s') : null;
        $noticeBoard->EdDate = $noticeBoard->EdDate ? Carbon::parse($noticeBoard->EdDate)->format('d/m/Y H:i:s') : null;

        return response()->json($noticeBoard);
    }

    /**
     * Store a new NoticeBoard record.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'Nc_Id'       => 'required|integer|exists:notice_category,Nc_Id',
            'Title'       => 'required|string|max:25',
            'Description' => 'required|string|max:250',
            'SocId'       => 'required|integer|exists:society_master,SocId',
            'Severity'    => 'nullable|string|max:1',
            'Status'      => 'required|string|max:1',
            'STDate'      => 'required|date_format:d/m/Y H:i:s',
            'EdDate'      => 'required|date_format:d/m/Y H:i:s',
            'Added_by'    => 'nullable|integer|exists:users_master,U_Id',
            'Notice_type' => 'nullable|string|max:1|in:N,E',
            'Press_by'    => 'nullable|string|max:1|in:G,M,A',
        ]);

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

        try {
            // Convert from Indian format (dd/mm/yyyy H:i:s) to MySQL format (Y-m-d H:i:s)
            $startDate = Carbon::createFromFormat('d/m/Y H:i:s', $request->input('STDate'))->format('Y-m-d H:i:s');
            $endDate = Carbon::createFromFormat('d/m/Y H:i:s', $request->input('EdDate'))->format('Y-m-d H:i:s');
        } catch (\Exception $e) {
            return response()->json(['error' => 'Invalid date format. Use dd/mm/yyyy H:i:s'], 422);
        }

        $noticeBoard = NoticeBoard::create([
            'Nc_Id'       => $request->input('Nc_Id'),
            'Title'       => $request->input('Title'),
            'Description' => $request->input('Description'),
            'SocId'       => $request->input('SocId'),
            'Severity'    => $request->input('Severity'),
            'Status'      => $request->input('Status'),
            'STDate'      => $startDate,
            'EdDate'      => $endDate,
            'Added_by'    => $request->input('Added_by'),
            'Notice_type' => $request->input('Notice_type', 'N'), // Default to 'N' if not provided
            'Press_by'    => $request->input('Press_by'),
        ]);

        return response()->json($noticeBoard, 201);
    }

    /**
     * Update a NoticeBoard record by Ntc_Id.
     */
    public function update(Request $request, $id)
    {
        $noticeBoard = NoticeBoard::find($id);

        if (!$noticeBoard) {
            return response()->json(['message' => 'Record not found'], 404);
        }

        $validator = Validator::make($request->all(), [
            'Nc_Id'       => 'required|integer|exists:notice_category,Nc_Id',
            'Title'       => 'required|string|max:25',
            'Description' => 'required|string|max:250',
            'SocId'       => 'required|integer|exists:society_master,SocId',
            'Severity'    => 'nullable|string|max:1',
            'Status'      => 'required|string|max:1',
            'STDate'      => 'required|date_format:d/m/Y H:i:s',
            'EdDate'      => 'required|date_format:d/m/Y H:i:s',
             'Added_by'    => 'nullable|integer|exists:users_master,U_Id',
            'Notice_type' => 'nullable|string|max:1|in:N,E',
            'Press_by'    => 'nullable|string|max:1|in:G,M,A',
        ]);

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

        try {
            // Convert date from Indian format to MySQL format
            $startDate = Carbon::createFromFormat('d/m/Y H:i:s', $request->input('STDate'))->format('Y-m-d H:i:s');
            $endDate = Carbon::createFromFormat('d/m/Y H:i:s', $request->input('EdDate'))->format('Y-m-d H:i:s');
        } catch (\Exception $e) {
            return response()->json(['error' => 'Invalid date format. Use dd/mm/yyyy H:i:s'], 422);
        }

        $noticeBoard->update([
            'Nc_Id'       => $request->input('Nc_Id'),
            'Title'       => $request->input('Title'),
            'Description' => $request->input('Description'),
            'SocId'       => $request->input('SocId'),
            'Severity'    => $request->input('Severity'),
            'Status'      => $request->input('Status'),
            'STDate'      => $startDate,
            'EdDate'      => $endDate,
            'Added_by'    => $request->input('Added_by'),
            'Notice_type' => $request->input('Notice_type', 'N'), // Default to 'N' if not provided
            'Press_by'    => $request->input('Press_by'),
        ]);

        return response()->json($noticeBoard);
    }

    /**
     * Delete a NoticeBoard record by Ntc_Id.
     */
    public function destroy($id)
    {
        $noticeBoard = NoticeBoard::find($id);

        if (!$noticeBoard) {
            return response()->json(['message' => 'Record not found'], 404);
        }

        $noticeBoard->delete();
        return response()->json(['message' => 'Deleted successfully']);
    }
}
