اريد اضافة التالى الى هذا الكود 1- اضافة قاعدة بيانات monogdb بدل من الملف وقم باستخدام mongoose 2- اضافة next-auth ليكون هناك حسابين حساب للمستقبل وحساب للمدير 3- اضافة sockt.io لاضافة صوت عند وصول طلب الزيارة 4- قم بتغير لون الخلفية في visitingList على حسب حالة الطلب بالاوان احمر - اخضر - اصفر


// app/page.js
export default function Home() {
  return (
    <div className="container mx-auto p-4">
      <h1 className="text-2xl font-bold mb-4">مرحبًا بك في نظام إدارة الزيارات</h1>
      <p className="mb-4">يرجى اختيار الصفحة التي ترغب في الوصول إليها:</p>
      <div className="space-x-4">
        <a href="/receptionist" className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">صفحة الاستقبال</a>
        <a href="/manager" className="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600">صفحة المدير</a>
      </div>
    </div>
  )
}
// app/layout.js
import './globals.css'
import { Providers } from './providers'

export default function RootLayout({ children }) {
  return (
    <html lang="ar" dir="rtl">
      <body className="bg-gray-100">
        <Providers>
          <nav className="bg-blue-600 text-white p-4">
            <div className="container mx-auto flex justify-between items-center">
              <h1 className="text-2xl font-bold">نظام إدارة الزيارات</h1>
              <div>
                <a href="/receptionist" className="mr-4 hover:underline">الاستقبال</a>
                <a href="/manager" className="hover:underline">المدير</a>
              </div>
            </div>
          </nav>
          <main className="container mx-auto mt-8">
            {children}
          </main>
        </Providers>
      </body>
    </html>
  )
}
// app/providers.js
'use client'

import { Provider } from 'react-redux'
import { store } from '@/lib/redux/store'

export function Providers({ children }) {
  return (
    <Provider store={store}>
      {children}
    </Provider>
  )
}
// app/receptionist/page.js
'use client';

import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { addVisitAsync, fetchVisits } from '@/lib/redux/visitSlice';
import VisitForm from '@/components/VisitForm';
import VisitList from '@/components/VisitList';

export default function ReceptionistPage() {
  const dispatch = useDispatch();
  const visits = useSelector(state => state.visits.visits);
  const status = useSelector(state => state.visits.status);
  const error = useSelector(state => state.visits.error);

  useEffect(() => {
    if (status === 'idle') {
      dispatch(fetchVisits());
    }
  }, [status, dispatch]);

  const handleAddVisit = (visitData) => {
    dispatch(addVisitAsync(visitData));
  };

  return (
    <div className="container mx-auto p-4">
      <h1 className="text-2xl font-bold mb-4">صفحة الاستقبال</h1>
      <VisitForm onSubmit={handleAddVisit} />
      {status === 'loading' && <p>جارٍ تحميل الزيارات...</p>}
      {error && <p className="text-red-500">خطأ: {error}</p>}
      <VisitList visits={visits} />
    </div>
  );
}
// app/manager/page.js
'use client';

import { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { updateVisitStatusAsync, fetchVisits } from '@/lib/redux/visitSlice';
import VisitList from '@/components/VisitList';

export default function ManagerPage() {
  const dispatch = useDispatch();
  const visits = useSelector(state => state.visits.visits);
  const status = useSelector(state => state.visits.status);

  useEffect(() => {
    if (status === 'idle') {
      dispatch(fetchVisits());
    }
  }, [status, dispatch]);

  const handleStatusUpdate = (id, newStatus) => {
    dispatch(updateVisitStatusAsync({ id, status: newStatus }));
  };

  return (
    <div className="container mx-auto p-4">
      <h1 className="text-2xl font-bold mb-4">صفحة المدير</h1>
      <VisitList 
        visits={visits} 
        showActions={true} 
        onStatusUpdate={handleStatusUpdate} 
      />
    </div>
  );
}
// app/api/visits/data.js
let visits = [];

export function getVisits() {
  return visits;
}

export function addVisit(visit) {
  visits.push(visit);
}

export function updateVisit(id, status) {
  const visitIndex = visits.findIndex(v => v.id === parseInt(id));
  if (visitIndex !== -1) {
    visits[visitIndex].status = status;
    return visits[visitIndex];
  }
  return null;
}
// app/api/visits/route.js
import { NextResponse } from 'next/server';
import { getVisits, addVisit } from './data';

export async function GET() {
  const visits = getVisits();
  return NextResponse.json(visits);
}

export async function POST(request) {
  const visit = await request.json();
  visit.id = Date.now();
  visit.status = 'pending';
  addVisit(visit);
  return NextResponse.json(visit);
}
// app/api/visits/[id]/route.js
import { NextResponse } from 'next/server';
import { updateVisit } from '../data';

export async function PATCH(request, { params }) {
  const { id } = params;
  const { status } = await request.json();

  const updatedVisit = updateVisit(id, status);
  if (updatedVisit) {
    return NextResponse.json(updatedVisit);
  }

  return NextResponse.json({ error: 'Visit not found' }, { status: 404 });
}
// app/components/VisitForm.js
'use client';

import { useState } from 'react';

export default function VisitForm({ onSubmit }) {
  const [visitorName, setVisitorName] = useState('');
  const [visitorPhone, setVisitorPhone] = useState('');
  const [visitPurpose, setVisitPurpose] = useState('');
  const [error, setError] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!visitorName || !visitorPhone || !visitPurpose) {
      setError('جميع الحقول مطلوبة.');
      return;
    }
    onSubmit({ visitorName, visitorPhone, visitPurpose });
    setVisitorName('');
    setVisitorPhone('');
    setVisitPurpose('');
    setError('');
  };

  return (
    <form onSubmit={handleSubmit} className="mb-4">
      {error && <p className="text-red-500 mb-2">{error}</p>}
      <input
        type="text"
        value={visitorName}
        onChange={(e) => setVisitorName(e.target.value)}
        placeholder="اسم الزائر"
        className="mb-2 p-2 border rounded w-full"
        required
      />
      <input
        type="tel"
        value={visitorPhone}
        onChange={(e) => setVisitorPhone(e.target.value)}
        placeholder="رقم الهاتف"
        className="mb-2 p-2 border rounded w-full"
        required
      />
      <input
        type="text"
        value={visitPurpose}
        onChange={(e) => setVisitPurpose(e.target.value)}
        placeholder="سبب الزيارة"
        className="mb-2 p-2 border rounded w-full"
        required
      />
      <button type="submit" className="bg-blue-500 text-white p-2 rounded w-full">
        تسجيل الزيارة
      </button>
    </form>
  );
}
// app/components/VisitList.js
'use client';
import PropTypes from 'prop-types';

export default function VisitList({ visits, showActions = false, onStatusUpdate }) {
  if (visits.length === 0) {
    return <p>لا توجد زيارات مسجلة.</p>;
  }

  return (
    <div className="mt-4">
      <h2 className="text-xl font-semibold mb-2">قائمة الزيارات</h2>
      <ul className="space-y-2">
        {visits.map((visit) => (
          <li key={visit.id} className="border p-4 rounded shadow">
            <p><strong>الاسم:</strong> {visit.visitorName}</p>
            <p><strong>الهاتف:</strong> {visit.visitorPhone}</p>
            <p><strong>السبب:</strong> {visit.visitPurpose}</p>
            <p><strong>الحالة:</strong> {visit.status}</p>
            {showActions && (
              <div className="mt-2 flex space-x-2">
                <button 
                  onClick={() => onStatusUpdate(visit.id, 'accepted')}
                  className="bg-green-500 text-white px-3 py-1 rounded"
                >
                  قبول
                </button>
                <button 
                  onClick={() => onStatusUpdate(visit.id, 'rejected')}
                  className="bg-red-500 text-white px-3 py-1 rounded"
                >
                  رفض
                </button>
                <button 
                  onClick={() => onStatusUpdate(visit.id, 'waiting')}
                  className="bg-yellow-500 text-white px-3 py-1 rounded"
                >
                  انتظار
                </button>
              </div>
            )}
          </li>
        ))}
      </ul>
    </div>
  );
}

VisitList.propTypes = {
  visits: PropTypes.array.isRequired,
  showActions: PropTypes.bool,
  onStatusUpdate: PropTypes.func,
};
// lib/redux/store.js
import { configureStore } from '@reduxjs/toolkit';
import visitReducer from './visitSlice';

export const store = configureStore({
  reducer: {
    visits: visitReducer,
  },
});
// lib/redux/visitSlice.js
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

export const fetchVisits = createAsyncThunk(
  'visits/fetchVisits',
  async () => {
    const response = await fetch('/api/visits');
    return response.json();
  }
);

export const addVisitAsync = createAsyncThunk(
  'visits/addVisit',
  async (visitData) => {
    const response = await fetch('/api/visits', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(visitData),
    });
    return response.json();
  }
);

export const updateVisitStatusAsync = createAsyncThunk(
  'visits/updateVisitStatus',
  async ({ id, status }) => {
    const response = await fetch(`/api/visits/${id}`, {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ status }),
    });
    return response.json();
  }
);

const initialState = {
  visits: [],
  status: 'idle',
  error: null,
};

const visitSlice = createSlice({
  name: 'visits',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      // حالات fetchVisits
      .addCase(fetchVisits.pending, (state) => {
        state.status = 'loading';
      })
      .addCase(fetchVisits.fulfilled, (state, action) => {
        state.status = 'succeeded';
        state.visits = action.payload;
      })
      .addCase(fetchVisits.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.error.message;
      })
      // حالات addVisitAsync
      .addCase(addVisitAsync.pending, (state) => {
        state.status = 'loading';
      })
      .addCase(addVisitAsync.fulfilled, (state, action) => {
        state.status = 'succeeded';
        state.visits.push(action.payload);
      })
      .addCase(addVisitAsync.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.error.message;
      })
      // حالات updateVisitStatusAsync
      .addCase(updateVisitStatusAsync.pending, (state) => {
        state.status = 'loading';
      })
      .addCase(updateVisitStatusAsync.fulfilled, (state, action) => {
        state.status = 'succeeded';
        const index = state.visits.findIndex(v => v.id === action.payload.id);
        if (index !== -1) {
          state.visits[index] = action.payload;
        }
      })
      .addCase(updateVisitStatusAsync.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.error.message;
      });
  },
});

export default visitSlice.reducer;