import React, { useState, useEffect } from 'react'; import { useMediaQuery, Box, Typography, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, Button, Chip, Menu, MenuItem, Dialog, DialogTitle, DialogContent, DialogActions, } from '@mui/material'; import TuneIcon from '@mui/icons-material/Tune'; import AddEmployModal from './AddEmployModal'; import authService from '../../../../services/authService'; import IOSSwitch from './IOSSwitch'; import { useTheme } from '@mui/material/styles'; import DeleteForeverIcon from '@mui/icons-material/DeleteForever'; import EmployeeDetailsModal from './EmployeeDetailsModal'; const Accountant = ({ restaurantId }) => { const theme = useTheme(); const isMobile = useMediaQuery(theme.breakpoints.down('sm')); const [modalOpen, setModalOpen] = useState(false); const [showAll, setShowAll] = useState(false); const [switchStates, setSwitchStates] = useState({}); const [shiftFilter, setShiftFilter] = useState('all'); const [filterAnchorEl, setFilterAnchorEl] = useState(null); const [Accountants, setAccountants] = useState([]); const [loading, setLoading] = useState(true); const [detailsModalOpen, setDetailsModalOpen] = useState(false); const [AccountantDetails, setAccountantDetails] = useState(null); // حالات الحذف const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false); const [selectedAccountant, setSelectedAccountant] = useState(null); const [isDeleting, setIsDeleting] = useState(false); useEffect(() => { const fetchAccountants = async () => { setLoading(true); try { const response = await authService.getAllAccountants(restaurantId); if (response.accountants) { setAccountants(response.accountants); // تهيئة switchStates حسب قيمة active const initialStates = {}; response.accountants.forEach(accountants => { initialStates[accountants.id] = accountants.active === 1; // أو Boolean(waiter.active) }); setSwitchStates(initialStates); } else { setAccountants([]); } } catch (error) { console.error("Failed to fetch waiters:", error); setAccountants([]); } finally { setLoading(false); } }; fetchAccountants(); }, [restaurantId]); const handleSwitchChange = async (id, email) => { try { const response = await authService.toggleAccountStatus(email, "Accountant"); if (response.success) { setSwitchStates((prev) => ({ ...prev, [id]: response.data, })); // alert(response.message); } else { alert("Failed: " + response.message); } } catch (error) { alert("Error: " + error.message); } }; const handleOpenModal = () => setModalOpen(true); const handleCloseModal = () => setModalOpen(false); const handleConfirm = async (formData) => { try { const AccountantData = { ...formData, restaurant_id: restaurantId, }; const response = await authService.registerAccountant(AccountantData); if (response.success) { alert('Accountant registered successfully!'); setModalOpen(false); // تحديث الحالة مباشرة بدل إعادة جلب كل البيانات const newAccountant = response.Accountant || AccountantData; // تأكد أن الـ API يعيد الـ Accountant المضاف، أو استخدم البيانات المحلية setAccountants((prev) => [newAccountant, ...prev]); } else { if (response.errors) { const errorsList = Object.entries(response.errors) .map(([field, msgs]) => { if (Array.isArray(msgs)) { return `${field}: ${msgs.join(', ')}`; } else { return `${field}: ${msgs}`; } }) .join('\n'); alert(`Failed to register Accountant due to validation errors:\n${errorsList}`); } else { alert('Failed to register Accountant: ' + response.message); } } } catch (error) { alert('An error occurred: ' + error.message); } }; const getShiftChipProps = (shiftType) => { switch (shiftType?.toLowerCase()) { case 'morning': return { label: 'Morning', sx: { backgroundColor: '#E7F4EE', color: '#0D894F', fontWeight: 600, fontSize: '14px', minWidth: 80, textTransform: 'capitalize', }, }; case 'evening': return { label: 'Evening', sx: { backgroundColor: '#FDF1E8', color: '#E46A11', fontWeight: 600, fontSize: '14px', minWidth: 80, textTransform: 'capitalize', }, }; default: return { label: shiftType, sx: { backgroundColor: '#E0E0E0', color: '#424242', fontWeight: 600, fontSize: '14px', minWidth: 80, textTransform: 'capitalize', }, }; } }; const filteredAccountants = shiftFilter === 'all' ? Accountants : Accountants.filter((w) => w.shift_type.toLowerCase() === shiftFilter); const displayedAccountants = showAll ? filteredAccountants : filteredAccountants.slice(0, 3); const handleFilterClick = (event) => { setFilterAnchorEl(event.currentTarget); }; const handleFilterClose = () => { setFilterAnchorEl(null); }; const handleFilterSelect = (value) => { setShiftFilter(value); setFilterAnchorEl(null); }; // فتح مودال الحذف const handleDeleteClick = (Accountant) => { setSelectedAccountant(Accountant); setConfirmDeleteOpen(true); }; // تأكيد الحذف const handleDeleteConfirm = async () => { if (!selectedAccountant) return; setIsDeleting(true); try { const response = await authService.deleteAccountant(selectedAccountant.id); // هنا تحقق من وجود message بدل success if (response.message && response.message.toLowerCase().includes("successfully")) { // alert(response.message); setAccountants((prev) => prev.filter((w) => w.id !== selectedAccountant.id)); } else { alert("Failed to delete Accountant: " + (response.message || "Unknown error")); } } catch (error) { alert("An error occurred: " + error.message); } finally { setIsDeleting(false); setConfirmDeleteOpen(false); setSelectedAccountant(null); } }; const handleOpenDetails = async (id) => { try { const response = await authService.getAccountantById(id); if (response.accountant) { setAccountantDetails(response.accountant); setDetailsModalOpen(true); } else { alert("Failed to fetch Accountant details"); } } catch (error) { alert("Error: " + error.message); } }; return ( Accountant {Accountants.length > 3 && ( )} Name Email Shift Type Actions {loading ? ( Loading... ) : displayedAccountants.length === 0 ? ( No activities found. ) : ( displayedAccountants.map((Accountant) => ( handleOpenDetails(Accountant.id)} > {Accountant.name} {Accountant.email} handleSwitchChange(Accountant.id, Accountant.email)} inputProps={{ 'aria-label': 'accountant switch' }} /> handleDeleteClick(Accountant)} /> )) )}
{['all', 'morning', 'evening'].map((shift) => ( handleFilterSelect(shift)} sx={{ color: shiftFilter === shift ? '#FF914D' : '#4F5867', backgroundColor: shiftFilter === shift ? '#fffcf9d5' : 'transparent', '&:hover': { backgroundColor: '#f0f0f0ff', transition: 'background-color 150ms ease-in-out', }, }} > {shift.charAt(0).toUpperCase() + shift.slice(1)} ))} {/* مودال تأكيد الحذف */} setConfirmDeleteOpen(false)}> Confirm Delete Are you sure you want to delete "{selectedAccountant?.name}"? This action cannot be undone. setDetailsModalOpen(false)} employee={AccountantDetails} type="Accountant" />
); }; export default Accountant;