'Investments & Loans'] ]; $success = ''; $error = ''; $currentUser = getCurrentUser(); // Handle form submissions if ($_SERVER['REQUEST_METHOD'] === 'POST') { try { $action = $_POST['action'] ?? ''; switch ($action) { case 'add_investment': $type = sanitizeInput($_POST['type']); $title = sanitizeInput($_POST['title']); $amount = (float)$_POST['amount']; $interestRate = (float)($_POST['interest_rate'] ?? 0); $startDate = $_POST['start_date']; $endDate = $_POST['end_date'] ?? null; $segmentId = !empty($_POST['segment_id']) ? (int)$_POST['segment_id'] : null; $description = sanitizeInput($_POST['description'] ?? ''); $lender = sanitizeInput($_POST['lender'] ?? ''); $tenure = (int)($_POST['tenure'] ?? 0); // Validation if (empty($type) || empty($title) || $amount <= 0 || empty($startDate)) { throw new Exception('Type, title, amount, and start date are required.'); } if (!in_array($type, ['investment', 'loan'])) { throw new Exception('Invalid investment type.'); } if ($interestRate < 0 || $interestRate > 100) { throw new Exception('Interest rate must be between 0 and 100.'); } // Calculate EMI for loans $emi = 0; if ($type === 'loan' && $tenure > 0 && $interestRate > 0) { $emi = calculateEMI($amount, $interestRate, $tenure); } $investmentData = [ 'type' => $type, 'title' => $title, 'amount' => $amount, 'interest_rate' => $interestRate, 'start_date' => $startDate, 'end_date' => $endDate, 'segment_id' => $segmentId, 'description' => $description, 'lender' => $lender, 'tenure_months' => $tenure, 'emi_amount' => $emi, 'status' => 'active', 'created_by' => $currentUser['id'], 'created_at' => date('Y-m-d H:i:s') ]; $investmentId = insertData('investments', $investmentData); if ($investmentId) { logSystemActivity('Add ' . ucfirst($type), "Added {$type}: {$title} - " . formatIndianCurrency($amount)); $success = ucfirst($type) . ' recorded successfully!'; } else { throw new Exception('Failed to record ' . $type . '.'); } break; case 'update_investment': $investmentId = (int)$_POST['investment_id']; $type = sanitizeInput($_POST['type']); $title = sanitizeInput($_POST['title']); $amount = (float)$_POST['amount']; $interestRate = (float)($_POST['interest_rate'] ?? 0); $startDate = $_POST['start_date']; $endDate = $_POST['end_date'] ?? null; $segmentId = !empty($_POST['segment_id']) ? (int)$_POST['segment_id'] : null; $description = sanitizeInput($_POST['description'] ?? ''); $lender = sanitizeInput($_POST['lender'] ?? ''); $tenure = (int)($_POST['tenure'] ?? 0); $status = sanitizeInput($_POST['status']); // Validation if (empty($title) || $amount <= 0 || empty($startDate)) { throw new Exception('Title, amount, and start date are required.'); } if (!in_array($status, ['active', 'completed', 'cancelled'])) { throw new Exception('Invalid status.'); } // Check if user can edit this investment $existingInvestment = fetchRow("SELECT * FROM investments WHERE id = ?", [$investmentId]); if (!$existingInvestment) { throw new Exception('Investment/Loan not found.'); } if ($currentUser['role'] !== 'admin' && $existingInvestment['created_by'] != $currentUser['id']) { throw new Exception('You can only edit your own records.'); } // Recalculate EMI if loan parameters changed $emi = $existingInvestment['emi_amount']; if ($type === 'loan' && $tenure > 0 && $interestRate > 0) { if ($amount != $existingInvestment['amount'] || $interestRate != $existingInvestment['interest_rate'] || $tenure != $existingInvestment['tenure_months']) { $emi = calculateEMI($amount, $interestRate, $tenure); } } $updateData = [ 'title' => $title, 'amount' => $amount, 'interest_rate' => $interestRate, 'start_date' => $startDate, 'end_date' => $endDate, 'segment_id' => $segmentId, 'description' => $description, 'lender' => $lender, 'tenure_months' => $tenure, 'emi_amount' => $emi, 'status' => $status ]; updateData('investments', $updateData, 'id = ?', [$investmentId]); logSystemActivity('Update ' . ucfirst($type), "Updated {$type} ID: {$investmentId}"); $success = ucfirst($type) . ' updated successfully!'; break; case 'delete_investment': $investmentId = (int)$_POST['investment_id']; // Check if user can delete this investment $existingInvestment = fetchRow("SELECT * FROM investments WHERE id = ?", [$investmentId]); if (!$existingInvestment) { throw new Exception('Investment/Loan not found.'); } if ($currentUser['role'] !== 'admin' && $existingInvestment['created_by'] != $currentUser['id']) { throw new Exception('You can only delete your own records.'); } executeQuery("DELETE FROM investments WHERE id = ?", [$investmentId]); logSystemActivity('Delete ' . ucfirst($existingInvestment['type']), "Deleted {$existingInvestment['type']}: {$existingInvestment['title']}"); $success = ucfirst($existingInvestment['type']) . ' deleted successfully!'; break; } } catch (Exception $e) { $error = $e->getMessage(); } } // Get filter parameters $typeFilter = $_GET['type'] ?? ''; $statusFilter = $_GET['status'] ?? ''; $segmentFilter = $_GET['segment'] ?? ''; $search = $_GET['search'] ?? ''; // Build query for investments list $whereConditions = []; $params = []; // Type filter if ($typeFilter) { $whereConditions[] = "i.type = ?"; $params[] = $typeFilter; } // Status filter if ($statusFilter) { $whereConditions[] = "i.status = ?"; $params[] = $statusFilter; } // Segment filter if ($segmentFilter) { $whereConditions[] = "i.segment_id = ?"; $params[] = $segmentFilter; } // Search filter if ($search) { $whereConditions[] = "(i.title LIKE ? OR i.lender LIKE ? OR i.description LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; $params[] = "%$search%"; } // User-specific filter for non-admin users if ($currentUser['role'] !== 'admin' && !hasPermission('manage_investments')) { $whereConditions[] = "i.created_by = ?"; $params[] = $currentUser['id']; } $whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : ''; // Get investments with related data $investmentsQuery = " SELECT i.*, bs.name as segment_name, u.full_name as created_by_name FROM investments i LEFT JOIN business_segments bs ON i.segment_id = bs.id LEFT JOIN users u ON i.created_by = u.id {$whereClause} ORDER BY i.start_date DESC, i.created_at DESC "; $investments = fetchAll($investmentsQuery, $params); // Calculate totals and statistics $totalInvestments = 0; $totalLoans = 0; $totalEMI = 0; $activeCount = 0; foreach ($investments as $investment) { if ($investment['type'] === 'investment') { $totalInvestments += $investment['amount']; } else { $totalLoans += $investment['amount']; if ($investment['status'] === 'active') { $totalEMI += $investment['emi_amount']; } } if ($investment['status'] === 'active') { $activeCount++; } } // Get data for dropdowns $businessSegments = getBusinessSegments(); include '../includes/header.php'; ?>
Manage your business investments, loans, and financing options.
Try adjusting your filters or search criteria. Start by adding your first investment or loan record.