import React, { useState, useEffect } from 'react'; import Toast from '../Components/Toast'; import { ChevronLeft, Upload, X, Check, FileText } from 'lucide-react'; export default function InvestorEdit({ id }) { const isReceptionist = window.__APP_DATA__?.role === 'receptionist'; const basePath = isReceptionist ? '/receptionist/investors' : '/owner/investors'; const [loading, setLoading] = useState(true); const [saving, setSaving] = useState(false); const [branches, setBranches] = useState([]); const [toast, setToast] = useState(null); const [hasPayouts, setHasPayouts] = useState(false); const [formData, setFormData] = useState({ name: '', investment_date: '', investment_amount: '', applicable_to_all_branches: false, branch_ids: [], roi_type: 'Percentage', roi_value: '', roi_period: 'Monthly', security_proof_document: null, existing_document: null }); const [branchDropdownOpen, setBranchDropdownOpen] = useState(false); useEffect(() => { const fetchData = async () => { try { const bRes = await fetch('/api/branches?status=Active'); const bData = await bRes.json(); setBranches(bData); const iRes = await fetch(`/api/investors/${id}`); const iData = await iRes.json(); setFormData({ ...formData, ...iData, applicable_to_all_branches: !!iData.applicable_to_all_branches, branch_ids: iData.branches.map(b => b.id), existing_document: iData.security_proof_document, security_proof_document: null }); const pRes = await fetch(`/api/investors/${id}/payouts`); const pData = await pRes.json(); setHasPayouts(pData.length > 0); } catch (error) { console.error('Error fetching data:', error); } finally { setLoading(false); } }; fetchData(); }, [id]); const handleChange = (e) => { const { name, value, type, checked } = e.target; setFormData({ ...formData, [name]: type === 'checkbox' ? checked : value }); }; const handleFileChange = (e) => { setFormData({ ...formData, security_proof_document: e.target.files[0] }); }; const toggleBranch = (id) => { const newBranchIds = formData.branch_ids.includes(id) ? formData.branch_ids.filter(bid => bid !== id) : [...formData.branch_ids, id]; setFormData({ ...formData, branch_ids: newBranchIds }); }; const handleSave = async (e) => { e.preventDefault(); setSaving(true); const data = new FormData(); data.append('_method', 'PUT'); // For Laravel multipart PUT Object.keys(formData).forEach(key => { if (key === 'branch_ids') { formData.branch_ids.forEach(id => data.append('branch_ids[]', id)); } else if (key === 'security_proof_document' && formData[key]) { data.append('security_proof_document', formData[key]); } else if (key === 'applicable_to_all_branches') { data.append(key, formData[key] ? '1' : '0'); } else if (key !== 'existing_document' && key !== 'branches') { data.append(key, formData[key] || ''); } }); const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content'); try { const response = await fetch(`/api/investors/${id}`, { method: 'POST', // Multipart must be POST in PHP/Laravel with _method=PUT headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': csrfToken }, body: data }); if (response.ok) { setToast({ message: 'Investor updated successfully!', type: 'success' }); setTimeout(() => window.location.href = basePath, 1500); } else { const errorData = await response.json().catch(() => ({})); if (errorData.errors) { const message = Object.entries(errorData.errors) .map(([field, msgs]) => `${field.replace('_', ' ')}: ${msgs.join(', ')}`) .join('\n'); setToast({ message: 'Validation Error:\n' + message, type: 'error' }); } else { setToast({ message: 'Error updating investor: ' + (errorData.message || response.statusText), type: 'error' }); } } } catch (error) { console.error('API Error:', error); setToast({ message: 'Failed to update investor.', type: 'error' }); } finally { setSaving(false); } }; if (loading) return
Loading details...
; const selectedBranchNames = branches .filter(b => formData.branch_ids.includes(b.id)) .map(b => b.name) .join(', '); return ( <> {toast && setToast(null)} />}

Edit Investor

{hasPayouts && (

Financial Terms Locked

Core investment terms (Amount, Date, ROI) cannot be modified because payments have already been processed for this investor to maintain accounting integrity.

)}
{ if (e.target.value.length <= 30) handleChange(e); else setToast({ message: 'Maximum 30 characters allowed', type: 'error' }); }} className="w-full border border-gray-200 rounded-xl px-4 py-3.5 text-sm focus:ring-2 focus:ring-emerald-500 transition-all outline-none" />
Applicable to All Branches
{!formData.applicable_to_all_branches && !isReceptionist && (
{branchDropdownOpen && (
{branches.map(branch => (
toggleBranch(branch.id)} className="flex items-center justify-between p-3 hover:bg-gray-50 rounded-lg cursor-pointer transition-colors" > {branch.name} {formData.branch_ids.includes(branch.id) && }
))}
)}
)}
{formData.existing_document && !formData.security_proof_document && (

Current Document

Existing proof attached

)}

{formData.security_proof_document ? formData.security_proof_document.name : <>Upload new file or drag and drop}

PDF, PNG, JPG up to 10MB

); }