prepare("SELECT COUNT(*) FROM clients WHERE client_code = ?"); $stmt->execute([$client_code]); } while ($stmt->fetchColumn() > 0); $stmt = $pdo->prepare(" INSERT INTO clients (client_code, company_name, industry, contact_person, email, phone, address, city, country, postal_code, website, notes, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW()) "); $stmt->execute([ $client_code, $company_name, $industry, $contact_person, $email, $phone, $address, $city, $country, $postal_code, $website, $notes, $_SESSION['admin_id'] ]); $client_id = $pdo->lastInsertId(); // Handle file uploads if (!empty($_FILES['attachments']['name'][0])) { $upload_dir = 'uploads/clients/'; if (!file_exists($upload_dir)) { mkdir($upload_dir, 0755, true); } $allowed_types = ['application/pdf', 'image/jpeg', 'image/jpg', 'image/png', 'image/gif']; $max_files = 10; $max_size = 5 * 1024 * 1024; // 5MB for ($i = 0; $i < min(count($_FILES['attachments']['name']), $max_files); $i++) { if ($_FILES['attachments']['error'][$i] === UPLOAD_ERR_OK) { $file_type = $_FILES['attachments']['type'][$i]; $file_size = $_FILES['attachments']['size'][$i]; if (in_array($file_type, $allowed_types) && $file_size <= $max_size) { $file_name = $_FILES['attachments']['name'][$i]; $file_tmp = $_FILES['attachments']['tmp_name'][$i]; $extension = pathinfo($file_name, PATHINFO_EXTENSION); $unique_name = $client_code . '_' . time() . '_' . $i . '.' . $extension; $file_path = $upload_dir . $unique_name; if (move_uploaded_file($file_tmp, $file_path)) { $attachStmt = $pdo->prepare(" INSERT INTO client_attachments (client_id, file_name, file_path, file_type, file_size, uploaded_at) VALUES (?, ?, ?, ?, ?, NOW()) "); $attachStmt->execute([ $client_id, $file_name, $file_path, $file_type, $file_size ]); } } } } } logActivity($_SESSION['admin_id'], 'create_client', "Created client: $client_code", 'client', $client_id); header('Location: clients.php?success=created&code=' . $client_code); exit; } catch (Exception $e) { $error = 'An error occurred. Please try again.'; error_log("Create client error: " . $e->getMessage()); } } } include 'includes/header.php'; ?>